8

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.

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!

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

    }
}
2
  • Thank you! Could you just explain why you close the while loop and didnt add anything like an if statement? For example, after you closed the loop you went directly to { ... }?
    – user4412408
    Jan 28, 2015 at 20:29
  • while implicitly checks for condition being met as in the input being above zero or greater than zero. When the user enters a negative number or a number lesser than zero, the control jumps out of the while block to the succeeding block executing the Number is negative! Hence we don't need an explicit check with an if statement. if statements are generally used while looping with for
    – CodeWalker
    Jan 28, 2015 at 20:35
2

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.

2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.