在 Java 中,我无法使用用户输入的单个整数序列运行多个循环。单独地,它们单独运行良好,但一起打印出不正确的数字。
我不知道是什么导致了这个问题。
这是我的代码。
import java.util.Scanner;
public class SequenceTester
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a sequence of integers. " +
"Enter a non-integer to terminate");
int sequence = in.nextInt();
//Print One
int min = sequence;
while(in.hasNextInt())
{
int input = in.nextInt();
if(input < smallest)
{
smallest = input;
}
}
System.out.println(smallest);
//Print Two
int max = sequence;
while(in.hasNextInt())
{
int input = in.nextInt();
if(input > max)
{
max = input;
}
}
System.out.println(max);
//Print Three
int even = 0;
int odd = 0;
while(in.hasNextInt())
{
int input = in.nextInt();
if((input %2) == 0)
{
even++;
}
else
{
odd++;
}
}
System.out.println( even);
System.out.println(odd);
//Print Four
double total = 0;
int count = 0;
while (in.hasNextInt())
{
Int input = in.nextInt();
total = total + input;
count++;
}
double average = 0;
if (count > 0)
{
average = total / count;
}
System.out.println(average);
}
}