我很难让我的程序读取文本文件并找到num
与wrkID
的匹配项,因此它可以打印出相关信息。
文本文件如下所示。数字455和367是wrkID
,我正在尝试获取我输入的数字以匹配:
Corner street^3^455^Collin^Sydney
David street^2^367^Spence^Sydney
public class Work
{
public static void main(String[] args) throws IOException
{
Scanner Keyboard = new Scanner(System.in);
System.out.print("Enter filename >> ");
String response = Keyboard.nextLine();
File inFile = new File(response);
Scanner wrk = new Scanner(inFile);
System.out.print("Enter job ID >> ");
int num = Keyboard.nextInt();
while (route.hasNextLine())
{
String Street = wrk.nextLine();
int stopNum = wrk.nextInt();
int wrkID = wrk.nextInt();
String road = wrk.nextLine();
String town = wrk.nextLine();
if(wrkID == num)
{
System.out.println("work id and street: " + trkID + Street);
}
}
}
}
答案 0 :(得分:0)
问题在这里:
String Street = wrk.nextLine();
int stopNum = wrk.nextInt();
int wrkID = wrk.nextInt();
String road = wrk.nextLine();
String town = wrk.nextLine();
当你调用wrk.nextLine()时,它将整个第一行文本分配到String street ... 如果你只需要整数,那么只需使用nextInt();
就可以丢弃其他输入答案 1 :(得分:0)
如果给定的输入匹配,则应打印整行。
public static void main(String[] args) throws IOException
{
Scanner Keyboard = new Scanner(System.in);
System.out.print("Enter filename >> ");
String response = Keyboard.nextLine();
File file = new File(response);
try {
BufferedReader br = new BufferedReader(new FileReader(file));
System.out.print("Enter job ID >> ");
String num = Keyboard.nextLine();
String line;
while ((line = br.readLine()) != null) {
String[] splitData = line.split("\\^");
for(String data:splitData){
if (data.equalsIgnoreCase(num)) {
System.out.println(line);
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}