shanky singh
shanky singh

Reputation: 1141

String array not getting correct value

I am trying to get the value of string and integer so I can make use of that. I have taken the value and trying to store in array and then printing the value. For some reason I am not getting the value of string correctly. Can you please help me to make my code correct.

public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
         int r = sc.nextInt();
         int [] numbers = new int[r];
         String names[] = new String[r];
         for(int i=0; i<r; i++){
             numbers[i] += sc.nextInt();
             names[i] += sc.next();
        }
         System.out.println(Arrays.toString(numbers));
         System.out.println(Arrays.toString(names));
    }

Output : [2,2]
         [nullAA, nullBB]

And also How can I get the indexes of both the arrays after print statement.

Upvotes: 0

Views: 55

Answers (1)

Eran
Eran

Reputation: 393811

You are appending the default value of names[i] (null) to the value read from the Scanner.

Change

names[i] += sc.next();

to

names[i] = sc.next();

And if you want to print the indices of the arrays, use a loop :

for (int i = 0; i < r; i++)
    System.out.print(i + " ");
System.out.println();

Upvotes: 3

Related Questions