这是我的代码的一部分来自一个给出错误的项目。我正在练习封装,但是,当我在Array-list中设置值时,无法弄清楚为什么我会收到此错误。
有两个班级
1)Create_accountant
2)Adminstoreroom
它们都在同一个包裹下:com.admin
package com.admin;
import java.util.InputMismatchException;
import java.util.Scanner;
class Create_accountant {
Adminstoreroom admin = new Adminstoreroom();
void Creating() {
System.out.println();
System.out.println("\t\t\t\t Create New Accoutant");
System.out.println();
name();
pass();
}
void name() {
Scanner input = new Scanner(System.in);
System.out.println();
System.out.print("Enter his/her name: \t");
String name = null;
try {
admin.setAccName(input.nextLine());
System.out.println("done");
}
catch(InputMismatchException e) {
System.out.println("Wrong input. Please enter the name again.");
name();
}
catch(Exception e) {
System.out.println("Here is the main problem " + e);
}
admin.setAccName(name);
input.close();
}
private void pass() {
Scanner input = new Scanner(System.in);
System.out.println();
System.out.print("Enter his/her password: \t");
try {
admin.setAccPassword(input.nextLine());
}
catch(InputMismatchException e) {
System.out.println("Wrong input. Please enter the password again.");
pass();
}
catch(Exception e) {
System.out.println("Here is the main problem");
}
input.close();
}
问题出在2个试块内。
try {
admin.setAccName(input.nextLine());
System.out.println("done");
}
name()
和pass()
都用于捕获(异常e)块。当我运行此代码时,上面尝试的输出是
以下是主要问题
java.util.NoSuchElementException: No line found
第二课
package com.admin;
import java.util.ArrayList;
class Adminstoreroom {
//These arrays are used for Storing accountant info in the admin sections
private static ArrayList<String> accName = new ArrayList<String>(30);
private static ArrayList<String> accPassword = new ArrayList<String>(30);
//Accountant Names
public void setAccName(String an) {
accName.add(an);
}
public String getAccName(int i) {
return accName.get(i);
}
//Accountant Password
public void setAccPassword(String ap) {
accPassword.add(ap);
}
public String getAccPassword(int i) {
return accPassword.get(i);
}