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!
解決方案
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);
}
}
}