如何将三个while循环链接在一起? [英] How do I link three while loops together?
本文介绍了如何将三个while循环链接在一起?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嗨所有
我目前有一个使用三个while循环的程序,但是当程序运行时它只执行其中一个条件,例如我的程序有一个寻找奇数的循环,非常感谢偶数和数字的数量
hi all
I currently have a program which is using three while loops but when the program runs it only does one of the criteria so for example my program has a loop for looking for odd numbers,even numbers and the amount of numbers any help would be greatly appreciated
import java.util.Scanner;
/**
*
* @author Adam
*/
public class OddEvenAverage2 {
public static void main(String[] args) {
Scanner Scan = new Scanner (OddEvenAverage2.class.getResourceAsStream("Numbers.txt"));
int evensum = 0;
int evencount = 0;
int numbersCounter = 0;
int oddsum = 0;
while(Scan.hasNext()){
Scan.next();
numbersCounter++;
}
while (Scan.hasNext()){ //Starts the while loop
// Read the next number.
int numList = Scan.nextInt();
if (numList %2== 0 ) { // checks if the number can be divided by 2
evensum += numList;
}
}
while (Scan.hasNext()){ //Starts the while loop
// Read the next number.
int numList2 = Scan.nextInt();
if (numList2 %2== 1 ) { // checks if the number can be divided by 2
oddsum += numList2;
}
System.out.println("Number of words: " + numbersCounter);
System.out.println("Even number total is " + evensum);
System.out.println("odd number total is " + oddsum);
}
}
}
推荐答案
您在第一次使用扫描仪时会消耗扫描仪的来源-环。以下Scan.hasNext() - 调用返回false,因为扫描程序到达源的末尾。没有办法重置扫描仪到开头,给你两个选项:
1)所有计数都在一个循环中。
2)为每个循环创建一个新的扫描程序。
You consume the source of the scanner during the first while-loop. The following Scan.hasNext()-calls return false because the scanner reached the end of the source. There's no way to reset a scanner to the beginning, leaving you with two options:
1) Do all counting in a single loop.
2) Create a new scanner for each loop.
这篇关于如何将三个while循环链接在一起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文