0

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.

1 Answer 1

3

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks It is working. Do I need a loop to get the indexes or someother way also exists
Thanks. I am beginner therefore getting bit of confuse. I will accept answer after 10 min. Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.