Java Scanner Continuous User input?

前端 未结 3 1413
半阙折子戏
半阙折子戏 2021-01-03 05:00

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 th

相关标签:
3条回答
  • 2021-01-03 05:35

    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.

    0 讨论(0)
  • 2021-01-03 05:39

    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

    0 讨论(0)
  • 2021-01-03 06:00
    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);
            }
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题