顶部的方法,是否将其声明为全局变量,因为它实际上没有接受任何内容。
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()
之前,不会读取名称本身。
要解决此问题,您应该在 Menu()
方法中调用 nextInt()
后立即调用 nextLine()
,只需清除多余的换行符。
关于java - 将扫描仪设置为全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20751385/