当我想使用扫描仪读取用户的名称,然后在字符串中分配名称的值,然后调用方法 getName 并给它一个名称参数以打印出我的名字时,我的名字是.. ..,我的代码崩溃了并且无法工作我试图找出问题所在,但我无法解决
public void getName(String name)
{
String s = "your name is: "+name ;
}
public void userInput()
{
print();
Scanner s = new Scanner(System.in);
String read = s.nextLine();
String op = read;
while(!read.equals("Exit"))
{
switch (op){
case "a" :
System.out.println("type your name:");
read = s.nextLine();
getName(read);
print();
read = s.nextLine();
op = read;
break;
case"b" :
System.out.println("by");
print();
read = s.nextLine();
op = read;
break;
}
}
}
public void print()
{
System.out.println("press a");
System.out.println("press b");
}
最佳答案
要使 while 条件为 false,请在开关中添加 default
语句:
while (!read.equals("Exit")) {
switch (op) {
case "a":
System.out.println("type your name:");
read = s.nextLine();
getName(read);
print();
read = s.nextLine();
op = read;
break;
case "b":
System.out.println("by");
print();
read = s.nextLine();
op = read;
break;
default: // Add this to finish loop when you type "Exit"
read = s.nextLine();
}
}
编辑
您对 getName(read) 方法的调用没有用,请尝试以下操作之一:
1. 您可以使 getName()
返回一个字符串并将其存储在 userInput()
中以供稍后使用。顺便说一下,getSomething() 方法通常用于返回一些东西。
public static String getName(String name) {
String s = "Your name is: " + name;
return s;
}
这在 userInput()
方法中:
String name = getName(read);
2. 或者在 void getName(String name)
方法中打印一些内容:
System.out.println("Your name is: " + name);
并在userInput()
方法中调用getName(read)
:
getName(read);
关于java - 使用扫描仪读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19599085/