Я создал этот код, чтобы получить неограниченные значения целых чисел, сохранить их и вычислить среднее значение. Он также делает это в квадратном формате. Моя проблема заключается в том, что я создал ее так, чтобы цикл while останавливался только при вводе числа 0. Тем не менее, я только помещаю его в качестве замены, так как это единственный способ проверить остальную часть кода, чтобы убедиться, что все это работает.While Loop not integer
Что я действительно хочу сделать, цикл while продолжается до тех пор, пока пользователь не предоставит ввод, который не является целым числом. Ive пробовал все, используя hasNextint()
или nextint
и так далее, что я могу сделать?
import java.io.*;
import java.util.*;
public class InputStats {
public static void main(String[] args) {
Scanner TextIO = new Scanner(System.in);
int inputNumber; // One of the integers input by the user.
int sum; // The sum of all the integers.
int count; // The number of integers that have been entered.
double mean; // The mean value of the integers, rounded to 2 decimal places.
int squarein; // Value of squared number.
int sumsquare; // The sum of the squares of all the integers.
double meansquare; // The mean value of the squares of integers, rounded to 2 decimal places.
/* Initialize the summation and counting variables. */
sum = 0;
count = 0;
sumsquare = 0;
meansquare = 0;
/* Read and process the user's input. */
System.out.println("Enter your first positive integer: ");
inputNumber = TextIO.nextInt();
while (inputNumber != 0) {
sum += inputNumber; // Add inputNumber to running sum.
squarein = inputNumber; //
sumsquare = squarein * squarein; //square inputs
count++; // Count the input by adding 1 to count.
System.out.println("Enter your next positive integer, or 0 to end: ");
inputNumber = TextIO.nextInt();
}
/* Display the result. */
if (count == 0) {
System.out.println("You didn't enter any data!");
} else {
mean = ((double)sum)/count;
meansquare = ((double)sumsquare)/count;
TextIO.nextInt();
System.out.println("Numbers entered: " + count + "\n");
System.out.println("Sum: " + sum + "\n");
System.out.println("Mean: " + mean + "\n");
System.out.println("Sum Squares: " + sumsquare + "\n");
System.out.println("Mean Square: " + meansquare + "\n");
}
} // end main()
} // end class InputStats
Вы слышали о цикле 'do ... while'? – BitNinja
Да, у меня есть lol. – David