mardi 27 juillet 2021

Advice needed. Question on Java fundamentals: Use of array and loop in Java but code not running

Am currently learning how to properly use Array in Java and ran into a problem. The question runs like this.

"You are given 2 arrays in a mix of strings and integers. Create a program that prints out all common elements in two arrays. You have to compare the elements of the second array to the elements of the first."

The input should be

  • inputFirst = Hey hello 2 4
  • inputSecond = 10 hey 4 hello
  • Result = 4 hello

My code runs like this but am not able to process it so will need your help in identifying the mistakes I made.

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
            // write your code here
            Scanner sc=new Scanner(System.in);

            String[] inputFirst=sc.nextLine().split(" ");
            String[] elementFirst=new String[inputFirst.length];

            String[] inputSecond=sc.nextLine().split(" ");
            String[] elementSecond=new String[inputSecond.length];

            int lengthFirst=inputFirst.length;
            int lengthSecond= inputSecond.length;

            for  (int i=0; i<lengthSecond; i++) {
                for (int j=0; j<lengthFirst; j++) {
                    if (elementSecond[i].equals(elementFirst[i])) {
                        System.out.print(elementSecond[i]+ " ");
                    }
                }
            }

        }
}

Aucun commentaire:

Enregistrer un commentaire