Java Scanner连续用户输入? [英] Java Scanner Continuous User input?

查看:899
本文介绍了Java Scanner连续用户输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

任何帮助都将不胜感激

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!

推荐答案

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

    }
}

这篇关于Java Scanner连续用户输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆