bimyou :
I've been staring at this problem for too long.. This is an exercise from https://java-programming.mooc.fi/part-3/4-using-strings and I have to get the name of the oldest person through splitting the strings and finding the name with the oldest age.
> Sample Input: Johnny, 5
> Rose, 19
> Sam, 10
Desired Output: Rose
Any help would genuinely be appreciated. Thanks!
import java.util.Scanner;
public class NameOfTheOldest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String name = "";
while (true) {
String input = scanner.nextLine();
if (input.equals("")) {
break;
}
String[] pieces = input.split(",");
int age = Integer.valueOf(pieces[1]);
int oldest = 0;
if (age > oldest) {
name = pieces[0];
oldest = age;
}
}
System.out.println("Name of the oldest: " + name);
}
}
Rodentman87 :
You placed the variable declaration for oldest
inside of the loop, so each time that a new line of input is read, oldest
is set back to 0, if you move that outside of the while loop, your code should work properly as is.
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=374612&siteId=1