我为Scanner创建了一个方法:
public static char getStatus() {
Scanner kb = new Scanner(System.in);
System.out.print("You are in state student or not(yes for Y/y,no for N/n)");
char state = kb.nextLine().charAt(0);
if (state == 'Y'||state == 'y') {
String instate = "In State";
System.out.println(instate);
int statusfee = 5;
return instate;
} else if (state == 'N'||state == 'n') {
String outstate = "Out-of-State";
System.out.println(outstate);
int statusfee = 5+2;
return outstate;
} else {
String false = "FALSE";
System.out.print(false);
return false;
}
}
我尝试打印出来供我选择。 例如:
System.out.println("Residencey:" + state);
我想输入“Y或y”时 然后输出是Residencey:In State。
错误是:
错误:不兼容的类型:字符串无法转换为char
我不知道为什么,java不能返回String或句子吗? 我是java的初学者,所以我不能使用一些困难的方法。
答案 0 :(得分:1)
如果您的要求是char status = getStatus();
我认为你的班级看起来像:
public class ScannerTest {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
char status = getStatus(kb);
if (status == 'Y') {
// System.out.println("In State");
} else if (status == 'N') {
// System.out.println("Out-of-State");
} else {
// System.out.println("FALSE");
}
System.out.println("Status is " + status);
}
public static char getStatus(Scanner kb) {
System.out
.print("You are in state student or not(yes for Y/y,no for N/n)");
char state = kb.nextLine().charAt(0);
if (state == 'Y' || state == 'y') {
String instate = "In State";
System.out.println(instate);
int statusfee = 5;
return 'Y';
} else if (state == 'N' || state == 'n') {
String outstate = "Out-of-State";
System.out.println(outstate);
int statusfee = 5 + 2;
return 'N';
} else {
String myfalse = "FALSE";
System.out.print(myfalse);
return 'F';
}
}
}
我希望它会对你有所帮助:)。
答案 1 :(得分:0)
你的方法返回类型是char,你返回的字符串是显示错误的原因。 这是您的代码具有正确的返回类型
public static String getStatus () {
Scanner kb = new Scanner (System.in);
System.out.print ("You are in state student or not(yes for Y/y,no for N/n)");
char state = kb.nextLine ().charAt (0);
if ((state == 'Y') || (state == 'y')) {
String instate = "In State";
System.out.println (instate);
int statusfee = 5;
return instate;
} else if ((state == 'N') || (state == 'n')) {
String outstate = "Out-of-State";
System.out.println (outstate);
int statusfee = 5 + 2;
return outstate;
} else {
String FALSE = "FALSE";
System.out.print (false);
return FALSE;
}
}
答案 2 :(得分:0)
请将您的方法返回类型更改为String
。实施例
public class ScannerTest {
public static void main(String[] args) {
getStatus();
}
public static String getStatus() {
Scanner kb = new Scanner(System.in);
System.out.print("You are in state student or not(yes for Y/y,no for N/n)");
char state = kb.nextLine().charAt(0);
if (state == 'Y' || state == 'y') {
String instate = "In State";
System.out.println(instate);
int statusfee = 5;
return instate;
} else if (state == 'N' || state == 'n') {
String outstate = "Out-of-State";
System.out.println(outstate);
int statusfee = 5 + 2;
return outstate;
} else {
String myfalse = "FALSE";
System.out.print(myfalse);
return myfalse;
}
}
}
我更改了您的变量名称。