简体   繁体   中英

Reading multiple inputs from Scanner

(I'm a beginner at Java) I am trying to write a program that asks for 6 digits from the user using a scanner, then from those 6 individual digits find the second highest number. So far this works however I'd like to have the input read from a single line rather than 6 separate lines. I've heard of delimiters and tokenisation, but have no idea how to implement it. I'ld like to have it read like "Enter 6 digits: 1 2 3 4 5 6" and parsing each digit as a separate variable so i can then place them in an array as shown. If anyone could give me a run-down of how this would work it would be much appreciated. Cheers for your time.

    public static void main(String[] args)
    {
        //Ask user input 
        System.out.println("Enter 6 digits: ");            
        //New Scanner
        Scanner input = new Scanner(System.in);

        //Assign 6 variables for each digit
        int num1 = input.nextInt();            
        int num2 = input.nextInt();            
        int num3 = input.nextInt();            
        int num4 = input.nextInt();            
        int num5 = input.nextInt();            
        int num6 = input.nextInt();            

      //unsorted array
      int num[] = {num1, num2, num3, num4, num5, num6};     
      //Length 
      int n = num.length;     
       //Sort 
      Arrays.sort(num);
       //After sorting
      // Second highest number is at n-2 position

       System.out.println("Second highest Number: "+num[n-2]);

 }           
}   

There are several ways to do that:

take a single line string, then parse it.

        Scanner input = new Scanner(System.in);

        ....
        String numString = input.nextLine();
        String[] split = numString.split("\\s+");
        int num[] = new int[split];
        // assuming there will be always atleast 6 numbers.
        for (int i = 0; i < split.length; i++) {
            num[i] = Integer.parseInt(split[i]);
        }
        ... 
      //Sort 
      Arrays.sort(num);
       //After sorting
      // Second highest number is at n-2 position

       System.out.println("Second highest Number: "+num[n-2]);

Of course, there are many ways to do that. I will give you two ways: 1. Use lambda functions - this way is more advanced but very practical:

Integer[] s = Arrays.stream(input.nextLine().split(" ")).map(Integer::parseInt).toArray(Integer[]::new);
  • first create a stream, you can read more about streams here
  • than read the whole line "1 2 3 ...."
  • split the line by space " " and after this point the stream will look like ["1", "2", "3" ....]
  • to convert the strings to int "map" operator is used
  • and finally collect the stream into Integer[]

    1. You can use an iterator and loop as many times as you need and read from the console.

      int num[] = new int[6]; for (int i = 0; i < 6; i++) { num[i] = input.nextInt(); }

Your solution does this allready!

If you go through the documentation of scaner you will find out that your code works with different inputs, as long they are integers separated by whitespace and/or line seperators.

But you can optimice your code, to let it look nicer:

public static void main6(String[] args) {
    // Ask user input
    System.out.println("Enter 6 digits: ");
    // New Scanner
    Scanner input = new Scanner(System.in);

    // Assign 6 variables for each digit
    int size=6;
    int[] num=new int[size];
    for (int i=0;i<size;i++) {
        num[i]=input.nextInt();
    }
    Arrays.sort(num);
    // After sorting
    // Second highest number is at n-2 position

    System.out.println("Second highest Number: " + num[size - 2]);
}

As an additional hint, i like to mention this code still produces lot of overhead you can avoid this by using:

public static void main7(String[] args) {
    // Ask user input
    System.out.println("Enter 6 digits: ");
    // New Scanner
    Scanner input = new Scanner(System.in);

    // Assign 6 variables for each digit
    int size=6;
    int highest=Integer.MIN_VALUE;
    int secondhighest=Integer.MIN_VALUE;
    for (int i=0;i<size-1;i++) {
        int value=input.nextInt();
        if (value>highest) {
            secondhighest=highest;
            highest=value;
        } else if (value>secondhighest) {
            secondhighest=value;
        }
    }
    //give out second highest
    System.out.println("Second highest Number: " + secondhighest);
}

if you do not like to point on highest if there are multiple highest, you can replace the else if:

public static void main7(String[] args) {
    // Ask user input
    System.out.println("Enter 6 digits: ");
    // New Scanner
    Scanner input = new Scanner(System.in);

    // Assign 6 variables for each digit
    int size = 6;
    int highest = Integer.MIN_VALUE;
    int secondhighest = Integer.MIN_VALUE;
    for (int i = 0; i < size - 1; i++) {
        int value = input.nextInt();
        if (value > highest) {
            secondhighest = highest;
            highest = value;
        } else if (secondhighest==Integer.MIN_VALUE&&value!=highest) {
            secondhighest=value;
        }
    }
    // give out second highest
    System.out.println("Second highest Number: " + secondhighest);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM