Java扫描器连续用户输入?

8

为了练习Java编程,我正在尝试创建一个程序,该程序从键盘读取整数,直到输入负数为止。

同时,它会打印出忽略了负数后的最大值和最小值。

有没有一种方法可以在同一个程序中实现连续输入?我不想每次都要重新运行程序来输入数字。

非常感谢您的帮助。

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

        }
    }
}

这是我的代码一部分 - 它能工作,但我认为有更简单的方法来实现我想要的,但不确定怎么做!

3个回答

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

    }
}

您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - user4412408
while循环隐式地检查条件是否被满足,例如输入值是否大于零或者大于0。当用户输入一个负数或者一个小于零的数字时,控制跳出while循环块并执行succeeding block中的Number is negative!语句,因此我们不需要使用if语句进行显式检查。if语句通常用于与for循环结合使用。 - CodeWalker

2
您可以这样做:
Scanner input = new Scanner(System.in);
int num;
while((num = input.nextInt()) >= 0) {
    //do something
}

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

2
一个简单的循环可以解决您的问题。
    Scanner s = new Scanner(System.in);
    int num = 1;
    while(num>0)
    {
        num = s.nextInt();
        //Do whatever you want with the number
    }

上面的循环将一直运行,直到遇到负数。
希望这能帮到你。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接