java - 如何使用扫描仪读取文本文件
问题描述
我试图从文件中读取文本并将其与用户输入进行比较。但是当我运行它时,我会收到一个错误消息。我不知道出了什么问题,任何帮助将不胜感激!
线程“主”java.lang.IllegalStateException 中的异常:扫描程序在 java.base/java.util.Scanner.next(Scanner.java:第 1573 章)
import java.util.Scanner;
import java.io.*;
public class test123 {
public static void main(String[] args) throws IOException {
Scanner sc1 = new Scanner(System.in);
System.out.println("Please enter correct credentials to log in");
System.out.println("Username: ");
System.out.println("Password: ");
String userName = sc1.nextLine();
String passWord = sc1.nextLine();
File inFile = new File("employee.txt");
Scanner sc = new Scanner(inFile);
String uName = sc.nextLine();
String pWord = sc.nextLine();
sc.close();
if (userName.equals(uName) && passWord.equals(pWord)) {
System.out.println("Welcome " + userName + "!");
System.out.println("Menu: ");
System.out.println("\t1) Account");
System.out.println("\t2) Payroll");
System.out.println("\t3) Attendance Report");
System.out.println("\t4) Service Desk");
int answer = sc.nextInt();
switch (answer) {
case 1:
System.out.print("Welcome to Account!");
break;
case 2:
System.out.print("Welcome to Payroll!");
break;
case 3:
System.out.print("Welcome to Attendance Report!");
break;
case 4:
System.out.print("Welcome to Service Desk!");
break;
default:
System.out.print("Enter correct menu option");
}
} else {
System.out.println("Sorry, you entered invalid credentials. Try again. ");
}
}
}
解决方案
您正在关闭它:
sc.close();
然后尝试从中读取:
if(userName.equals(uName) && passWord.equals(pWord))
{
System.out.println("Welcome " + userName + "!");
System.out.println("Menu: ");
System.out.println("\t1) Account");
System.out.println("\t2) Payroll");
System.out.println("\t3) Attendance Report");
System.out.println("\t4) Service Desk");
int answer = sc.nextInt(); //here
switch (answer) {
case 1:
System.out.print("Welcome to Account!");
break;
case 2:
System.out.print("Welcome to Payroll!");
break;
case 3:
System.out.print("Welcome to Attendance Report!");
break;
case 4:
System.out.print("Welcome to Service Desk!");
break;
default:
System.out.print("Enter correct menu option");
}
}
else
{
System.out.println("Sorry, you entered invalid credentials. Try again. ");
}
推荐阅读
- ios - 如何在IOS App swift上去除顶部栏的透明度
- c# - 为什么当输入与typof(X).GetFullName 完全相同的输入时,Type.GetType 不返回类型?
- java - 实例化 Java AWT 对象会导致在 macOS 上打开空应用程序
- java - 从本机库回调到 JNI 接口
- python-3.x - KERAS-更新说明:放置器自动处理的托管
- driverless-ai - 对于 13M 行的数据集,实验在 24 小时后保持在 0%
- uinavigationbar - 更改导航栏颜色
- php - 获取列集合或字符集类型(latin1_swedish_ci 或 utf8_general_ci)
- python - 如何监控应用程序进行的 Windows 系统 API 调用?
- java - 根据时间戳检索kafka主题中的偏移量