Java Scanner 连续用户输入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28201384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 05:46:22  来源:igfitidea点击:

Java Scanner Continuous User input?

javaintegerjava.util.scanner

提问by

For java practice, i am trying to create a program that reads integers from the keyboard until a negative one is entered.

对于 java 练习,我正在尝试创建一个从键盘读取整数直到输入负数的程序。

and it prints the maximum and minimum of the integer ignoring the negative.

并打印忽略负数的整数的最大值和最小值。

Is there a way to have continuous input in the same program once it runs? I have to keep running the program each time to enter a number.

有没有办法在同一程序运行后连续输入?我每次都必须继续运行程序才能输入一个数字。

Any help would be appreciated

任何帮助,将不胜感激

public class CS {
    public static void main(String []args) {

        Scanner keys = new Scanner(System.in);
        System.out.println("Enter a number: ");
        int n = keys.nextInt();

        while(true)
        {
            if(n>0)
            {
                System.out.println("Enter again: ");
                n = keys.nextInt();
            }
            else
            {
                System.out.println("Number is negative! System Shutdown!");
                System.exit(1);
            }

        }
    }
}

Here is a part of my code - It works, but i think there is an easier way of doing what i want but not sure how!

这是我的代码的一部分 - 它有效,但我认为有一种更简单的方法可以做我想做的事,但不确定如何做!

采纳答案by CodeWalker

import java.util.Scanner;

public class ABC {
public static void main(String []args) {
        int num;
        Scanner scanner = new Scanner(System.in);
        System.out.println("Feed me with numbers!");

        while((num = scanner.nextInt()) > 0) {
            System.out.println("Keep Going!");
        }

        {
            System.out.println("Number is negative! System Shutdown!");
            System.exit(1);
        }

    }
}

回答by haley

You could do something like:

你可以这样做:

Scanner input = new Scanner(System.in);
int num;
while((num = input.nextInt()) >= 0) {
    //do something
}

This will make num equal to the next integer, and check if it is greater than 0. If it's negative, it will fall out of the loop.

这将使 num 等于下一个整数,并检查它是否大于 0。如果它是负数,它将退出循环。

回答by Mario M

A simple loop can solve your problem.

一个简单的循环就可以解决您的问题。

    Scanner s = new Scanner(System.in);
    int num = 1;
    while(num>0)
    {
        num = s.nextInt();
        //Do whatever you want with the number
    }

The above loop will run until a negative number is met.

上面的循环将一直运行,直到遇到一个负数。

I hope this helps you

我希望这可以帮助你