将扫描仪设置为全局变量

在顶部的方法,它被声明为全局变量,因为它实际上没有任何东西。

public class java_1 { static Scanner stdin = new Scanner(System.in); import java.util.Scanner; 

这是用于声明它的代码,如果你能以另一种方式声明它,我可以获得文档的链接。

 public class java_1 { static Scanner stdin = new Scanner(System.in); static String getLastName (String Name){ String lastName; int spacePos,length; spacePos = fullName.indexOf(""); length = fullName.length(); lastName = fullName.substring(spacePos + 1); return lastName; } static String getInitial (String fullName){ String initial; initial = fullName.substring(0,1); return initial; } static String =Name (){ String fullName; String userName; String initial; String lastName; System.out.println("name"); fullName = stdin.nextLine(); initial = getInitial(fullName); lastName = getLastName(fullName); userName = initial + lastName; System.out.println(userName); return userName; } static String printuserName (){ String fullName,userName,initial,lastName; System.out.println("enter name"); fullName = stdin.nextLine(); initial = getInitial(fullName); userName = initial + lastName; System.out.println("username: " + userName); return userName; } static int menu(){ int choice; System.out.println("Input a number from the table, corresponding to the task required"); System.out.println("1 = User name"); System.out.println("2 = Factor"); System.out.println("3 = Quit"); choice = stdin.nextInt(); while (choice != 1){ System.out.println("Re enter"); choice = stdin.nextInt(); } return choice; } } } } 

问题是,当您使用stdin.nextInt()读取菜单选项时,仍然有一个换行符在扫描仪中等待。 一段时间后调用stdin.nextLine()时,你会获得该行的其余部分 – 这只是一个空字符串。 在对nextLine()进行FOLLOWING调用之前,不会读取名称本身。

要解决这个问题,你应该在Menu()方法中调用nextInt()后立即调用nextLine() ,只是为了清除那个额外的换行符。

该错误是由getInitial()内的这行代码生成的:

 initial = fullName.substring(0,1); 

StringIndexOutOfBoundsException意味着1超出字符串的末尾(意味着输入字符串为空)。 如果你还不熟悉你正在使用的任何IDE中的逐行调试,那么这将是一个尝试的好时机。 您可以单步执行代码以确定将空字符串传递到getInitial()