[英]Even and odd numbers with scanner Java
我嘗試僅將偶數添加到ArrayList
。 我認為使用掃描儀作為最合適的工具來處理文件。 該文件的路徑應在控制台中寫入。 我也使用2種最受歡迎的方式來定義偶數。 問題是-不僅偶數都添加到我的ArrayList
。 有我的代碼:
BufferedReader bfReader = new BufferedReader(new InputStreamReader(System.in));
InputStream inputStream = null;
List<Integer> myInts = new ArrayList<Integer>();
String filePath = null;
try {
filePath = bfReader.readLine();
inputStream = new FileInputStream(filePath);
} catch (IOException e) { }
Scanner scanner = new Scanner(inputStream);
while (scanner.hasNext()) {
if ((scanner.nextInt() % 2) == 0 && scanner.nextInt() != 1)
myInts.add(scanner.nextInt());
// if ((scanner.nextInt() & 1) == 0)
// myInts.add(scanner.nextInt());
}
for (Integer x : myInts) {
System.out.println(x);
}
我想我對Scanner
誤解。
很高興收到任何答案!
原因是nextInt()
每個新調用都會從輸入中讀取新的整數。
這是修改后的代碼段,說明您可能想要嘗試的操作:
Scanner scanner = new Scanner(inputStream);
int myInt;
while (scanner.hasNext()) {
myInt = scanner.nextInt();
if ((myInt % 2) == 0 && myInt != 1)
myInts.add(myInt);
}
有關更多信息,請參閱docs 。
每次調用nextInt
,它都會從掃描儀中取出一個項目。 這意味着一次遍歷循環將刪除多達三項,並且所添加的項與您要檢查的項不同。
假設您的輸入是4 3 1
您的代碼將執行以下操作:
if ((scanner.nextInt() /* 4 */ % 2) == 0 && scanner.nextInt() /* 3 */ != 1)
myInts.add(scanner.nextInt() /* 1 */);
並將1
添加到您的列表。
您應該將代碼更改為此:
while (scanner.hasNext())
{
int value = scanner.nextInt();
if ((value % 2) == 0)
myInts.add(value);
}
這只會讀取一個值,並在所有比較中使用它。
這里的問題在於
if ((scanner.nextInt() % 2) == 0 && scanner.nextInt() != 1)
每次調用scanner.nextInt()
,都會消耗下一個輸入。 因此,您最終將放棄大部分輸入。 要解決此問題,您需要使用類似
while (scanner.hasNext())
{
int i = scanner.nextInt;
if ((i % 2) == 0 && i != 1)
myInts.add(i);
}
這將正確消耗輸入,並且應正常工作。 包含此信息的掃描器javadoc可在以下位置找到: https : //docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
是的,我認為您理解錯了。 每當您使用掃描儀類指針的nextInt()方法時,哪個掃描文件就會移至nextInt()。 因此最好將整數值保存在臨時變量中。 下面是對代碼的修改,
BufferedReader bfReader = new BufferedReader(new InputStreamReader(System.in));
InputStream inputStream = null;
List<Integer> myInts = new ArrayList<Integer>();
String filePath = null;
try
{
filePath = bfReader.readLine();
inputStream = new FileInputStream(filePath);
}
catch (IOException e)
{
}
Scanner scanner = new Scanner(inputStream);
while (scanner.hasNext())
{
int firstNumber = scanner.nextInt();
if ((firstNumber % 2) == 0 && firstNumber != 1)
myInts.add(firstNumber);
//if ((scanner.nextInt() & 1) == 0)
// myInts.add(scanner.nextInt());
}
for (Integer x : myInts)
{
System.out.println(x);
}
每次您調用scanner.nextInt()
您都會得到另一個號碼。 如果要多次引用相同的數字,請分配給變量。
另外,檢查數字是否為偶數后,也不必檢查數字是否為1。
while (scanner.hasNext()) {
int n = scanner.nextInt();
if (n%2 == 0) {
myInts.add(n);
}
}
在行中
if ((scanner.nextInt() % 2) == 0 && scanner.nextInt() != 1)
您正在從輸入中讀取兩個整數,而不是兩次檢查相同的整數:
int nextInt = scanner.nextInt();
if ((nextInt % 2) == 0 && nextInt != 1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.