Print specific user input in java

I need to create a program that receives 3 user inputs in the form:

Name1   (any number of spaces)  age1
Name2   (any number of spaces)  age3
Name3   (any number of spaces)  age3

Then print the line that has the highest age (suppose Name3 age3 had the highest age that I would print on my line).

My code is:

import java.util.*;
public class RankAge{
    public static void main(String[] args){
    System.out.println("Enter 3 different names and the age of each person respectively:");
    Scanner sc = new Scanner(System.in);
    String n1 = sc.nextLine();
    String n2 = sc.nextLine();
    String n3 = sc.nextLine();

    }
}

I know how to scan user inputs, but I don’t know how to compare the numbers inside the resulting string to print a specific one (also, since there can be any number of spaces that seems even more complicated to me).

+4
source share
3 answers

You can use splitto get a person’s age:

String age = "Jon       57".split("\\s+")[1]; // contains "57"

Integer.parseInt(age), , .


, ([]). , [2] .
+2

frenchDolphin. , ( ):

import java.util.*;
public class RankAge{
    public static void main(String[] args){
    System.out.println("Enter 3 different names and the age of each person respectively:");
    Scanner sc = new Scanner(System.in);
    String n1 = sc.nextLine();
    String a1 = n1.split("\\s+")[1];
    String n2 = sc.nextLine();
    String a2 = n2.split("\\s+")[1];
    String n3 = sc.nextLine();
    String a3 = n3.split("\\s+")[1];

    if(Integer.parseInt(a1) > Integer.parseInt(a2)){
    } if(Integer.parseInt(a1) > Integer.parseInt(a3)){
            System.out.println(n1);
    }else if(Integer.parseInt(a2) > Integer.parseInt(a3)){
        System.out.println(n2);
    }else{
        System.out.println(n3);
    }
    }
}
+2

+1, , , . ,

import java.util.*;

public class RankAge {

   public static void main(String s[]){
        System.out.println("Enter 3 different names and the age of each person respectively:");
        Scanner sc = new Scanner(System.in);
        String n[] = new String[3];
        for(int i=0;i<3;i++){
            n[i] = sc.nextLine();
        }

        int age[] = new int[3];

        age[0] = Integer.parseInt(n[0].split("\\s+")[1]);
        age[1] = Integer.parseInt(n[1].split("\\s+")[1]);
        age[2] = Integer.parseInt(n[2].split("\\s+")[1]);
        int ageTemp[] = age;
        for(int i=0;i<age.length;i++){
            for(int j=i+1;j<age.length;j++){
                int tempAge = 0;
                String tempN = "";
                if(age[i]<ageTemp[j]){
                    tempAge = age[i];
                    tempN = n[i];
                    age[i] = age[j];
                    n[i] = n[j];
                    age[j] = tempAge;
                    n[j] = tempN;
                }
            }
        }

        for(int i=0;i<3;i++){
            System.out.println(n[i]);
        }

   }

}
0

Source: https://habr.com/ru/post/1609713/


All Articles