【发布时间】:2022-11-29 10:27:26
【问题描述】:
我试图从名为 numbers.text 的文件中仅打印出数字的最后一个位置 #。 数字.文字:
10
23
43
5
12
23
9
8
10
1
16
9
基本上,我试图打印出一条语句(以 10 为例)“10 最后出现在位置 9”。
import java.io.File;
import java.util.*;
public class SortOf3 {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
Scanner datafile = new Scanner(new File("numbers.text"));
boolean duplicate = true;
int count = 0;
int duplicate = 0
while (datafile.hasNextInt()) {
if (duplicate) {
System.out.print("Enter a number: ");
lastNumber = scanner.nextInt();
count++;
duplicate = false;
} else {
System.out.print("Enter a number: ");
lastNumber = scanner.nextInt();
count++;
}
if (lastNumber == datafile.nextInt())
System.out.println(lastNumber + " last appears in the file at position " + count);
else
System.out.println(lastNumber + " does not appear in the file");
}
}
}
我尝试使用 boolean duplicate,希望在 lastNumber 第一次出现时忽略计数器,但它似乎没有做任何事情。如果这里没有办法使布尔值工作,那么打印出文件中数字最后位置的另一种方法是什么?
【问题讨论】:
-
你的代码有问题吗?
标签: java