【发布时间】:2018-11-17 07:06:16
【问题描述】:
我有这个程序从输入文件中读取数字,然后要求用户输入一个数字。然后程序读取文件中的所有数字,如果输入的数字在文件中,程序打印回,“数字在文件中”,如果输入的数字不在文件中,程序打印回来,“数字不是在档案中。”如果用户输入'q',我还需要让它能够退出程序,但我不确定我该怎么做,看到'q' 是char 并且程序正在寻找输入int。我确实创建了一个变量char quit = 'q',但我不确定在哪里使用它,如果这甚至是正确的开始方式。
package classwork7_2;
import java.util.*;
import java.io.*;
public class ClassWork7_2 {
public static void main(String[] args)throws IOException {
Scanner s = new Scanner(System.in);
int[] numbers = fileToArray();
Arrays.sort(numbers);
char quit = 'q';
while (true) {
System.out.print("Enter a number in the file: ");
int numb = s.nextInt();
int i = Arrays.binarySearch(numbers, numb);
if (i < 0) {
System.out.print("Number is not in file\n");
} else {
System.out.print("Number is in file\n");
}
}
}
public static int[] fileToArray() throws IOException{
Scanner s = new Scanner(System.in);
int[] array = new int[7];
System.out.print("Enter name of file: ");
String filename = s.nextLine();
File f = new File(filename);
Scanner inputFile = new Scanner(f);
int i = 0;
while(inputFile.hasNext()){
array[i] = inputFile.nextInt();
i++;
}
inputFile.close();
return array;
}
}
【问题讨论】:
-
不要使用 nextInt(),也许使用:
int numb; String str = s.nextLine(); if (str,charAt(0) == 'q') { break; } if (!str.matches("\\d+") { System.out.println("Invalid Entry!"); continue; } numb = Integer.parseInt(str); // the reset of your code -
好的方法是用户 Scanner.hasNextXXX 方法,如我的回答中所述。