0

i have to write a program that reads names and ages from the user until an empty line is entered. The name and age are separated by a comma.After reading all user input, the program prints the age of the oldest person. Now i'm using the following method

import java.util.Scanner;

public class AgeOfTheOldest {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while(true){
            String text = scanner.nextLine();
            if(text.equals("")){
                break;
            }else{
                String[] pieces = text.split(",");
                int[] ages = Integer.valueOf(pieces[1]); 
                
            }
            
        }
    }
}

But the int[] ages line gives me this errorenter image description here so how do i convert string values and assign it to an integer array?

  • It may help if you explain why you think you need an array - to just determine the "AgeOfTheOldest" you just need an int set to -1, parse the value (as you have done) and check if it is greater than current oldest and set if it is. With that said, one has to ask why is the name entered at all if it is not part of your output requirements? – Computable Aug 23 '23 at 16:01
  • Add brackets, _int[] ages = { Integer.valueOf(pieces[1]) }_. – Reilas Aug 23 '23 at 16:20

1 Answers1

0

Integer.valueOf(pieces[1]) will take the second string in the pieces array (java is 0-index based, so pieces[0] is the first, pieces[1] is the second, and so on), and converts it to one int value.

You are attempting to assign it to an array of int values.

That's not what you wrote. You wrote: Convert the second string. Not 'convert all of them'.

Perhaps you are looking for something like:

int[] ages = new int[pieces.length];
for (int i = 0; i < pieces.length; i++) ages[i] = Integer.valueOf(pieces[i]);

Or perhaps:

Arrays.stream(pieces)
  .mapToInt(Integer::parseInt)
  .toArray();
rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
  • 1
    But I want to convert the second string of 'pieces' into an integer and assign it to an integer array. why does that show me an error? – itsasaddayfs Aug 23 '23 at 15:57
  • 1
    @itsasaddayfs " I want to convert the second string of pieces into an integer and assign it to an integer array. " <- But an integer is not an integer array. You can't assign an integer to an integer array no matter how hard you want to. You can only assign an integer to a specific index of an integer array. – OH GOD SPIDERS Aug 23 '23 at 15:59
  • @itsaddayfs your statement is nonsense. A single int cannot be an entire array. You can make a new 1-elem array and have its one and only element be that value (`myIntArray = new int[] {Integer.parseInt(parts[1])};` would do that), or you can have an existing array and assign to a specific slot. Let's say the 4th: `myIntArray[3] = Integer.parseInt(parts[1]);`. – rzwitserloot Aug 23 '23 at 21:43