简体   繁体   English

从扫描仪读取多个输入

[英]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. (我是 Java 的初学者)我正在尝试编写一个程序,该程序使用扫描仪向用户询问 6 位数字,然后从这 6 位个人数字中找到第二大数字。 So far this works however I'd like to have the input read from a single line rather than 6 separate lines.到目前为止,这是有效的,但是我希望从单行而不是 6 个单独的行读取输入。 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.我想让它读起来像“输入 6 位数字:1 2 3 4 5 6”并将每个数字解析为一个单独的变量,这样我就可以将它们放在一个数组中,如图所示。 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:我会给你两种方法: 1. 使用 lambda 函数——这种方法更高级但非常实用:

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 ...."比阅读整行“1 2 3 ....”
  • split the line by space " " and after this point the stream will look like ["1", "2", "3" ....]用空格“”分割线,在这一点之后,流看起来像 ["1", "2", "3" ....]
  • to convert the strings to int "map" operator is used将字符串转换为 int "map" 运算符
  • and finally collect the stream into Integer[]最后将流收集到 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.如果您查看 scaner 的文档,您会发现您的代码适用于不同的输入,只要它们是由空格和/或行分隔符分隔的整数。

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:如果您不喜欢在有多个最高点的情况下指向最高点,则可以在以下情况下替换 else:

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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