我还在学习编程并且真的需要一些帮助,我需要制作一个具有很多功能的程序,而且大部分功能已经完成,但是我在创建特定行时遇到了困难。我使用while循环让用户输入数字来计算最大,最小,以及随机生成数字的总和。我需要编程一种方式,如果用户输入退出语句-99,在输入任何其他数据之前,它会说"您没有输入任何数字。"并退出该计划。任何帮助都很棒,下面将是我的程序代码。
public class LargestSmallest
{
public static void main(String [] args)
{
//identifier declarations
int number;
int numberend = -99;
int largest = Integer.MIN_VALUE;
int smallest = Integer.MAX_VALUE;
int number1;
int sum1;
int sum2;
//create a Scanner object to read from the keyboard & input
Scanner input = new Scanner(System.in);
//create a random object
Random randomNumbers = new Random();
//get one random number
number1 = randomNumbers.nextInt(9);
//display prompts and get input
System.out.println("Enter an integer, or -99 to quit:");
//loop for number input
while ((number = input.nextInt()) != numberend) {
System.out.println("Enter an integer, or -99 to quit:");
//largest & smallest number sorting
if (number > largest) {
largest = number;
}
if (number < smallest) {
smallest = number;
}
}
//calculate final sums
sum1 = number1 + largest;
sum2 = number1 + smallest;
//final statements
System.out.println("Largest:" + largest);
System.out.println("Smallest:" + smallest);
System.out.println("Random:" + number1);
System.out.println("Largest + Random:" + sum1);
System.out.println("Smallest + Random:" + sum2);
}
}
答案 0 :(得分:0)
如果您只想在没有用户输入的情况下使用正确的消息结束程序,您可以执行以下操作:
while ((number = input.nextInt()) != numberend) {
System.out.println("Enter an integer, or -99 to quit:");
//largest & smallest number sorting
if (number > largest) {
largest = number;
}
if (number < smallest) {
smallest = number;
}
}
if (largest > Integer.MIN_VALUE) {
//calculate final sums
sum1 = number1 + largest;
sum2 = number1 + smallest;
//final statements
System.out.println("Largest:" + largest);
System.out.println("Smallest:" + smallest);
System.out.println("Random:" + number1);
System.out.println("Largest + Random:" + sum1);
System.out.println("Smallest + Random:" + sum2);
} else {
System.out.println("You have entered no numbers");
}
如果你想忽略-99并保持循环:
while ((number = input.nextInt()) != numberend || largest == Integer.MIN_VALUE) {
while (number == numberend) {
System.out.println("You have entered no numbers, you can't quit");
number = input.nextInt();
}
System.out.println("Enter an integer, or -99 to quit:");
//largest & smallest number sorting
if (number > largest) {
largest = number;
}
if (number < smallest) {
smallest = number;
}
}