英文:
Wondering why the condition for the else statement continues to be the output. Using String Variable
问题
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
System.out.print("输入:");
String name = inp.nextLine();
if(name.equals("Chen")){
System.out.print("老师");
}
else{
System.out.print("学生");
}
}
}
英文:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
System.out.print("In:");
String name = inp.nextLine();
if(inp.equals("Chen")){
System.out.print("teacher");
}
else{
System.out.print("student");
}
}
}
Continuously keep getting "student" no matter how much I play with the If portion. Not missing capitalization of the name Chen and even tried to store Chen in a variable and have that as part of the condition and still end with the else.
答案1
得分: 3
Your mistake is that you have compared a Scanner
object with a String
object. Do it as follows:
if ("Chen".equals(name)) {
System.out.print("teacher");
} else {
System.out.print("student");
}
Additional note:
If you want to do the comparison in a case-insensitive way, you should use equalsIgnoreCase
instead of equals
.
if ("Chen".equalsIgnoreCase(name)) {
System.out.print("teacher");
} else {
System.out.print("student");
}
Further additional note:
You can make it shorter by using the ternary operator. For example, the following line is equivalent to the complete block of code above.
System.out.println("Chen".equalsIgnoreCase(name) ? "teacher" : "student");
英文:
Your mistake is that you have compared a Scanner
object with a String
object. Do it as follows:
if ("Chen".equals(name)) {
System.out.print("teacher");
} else {
System.out.print("student");
}
Additional note:
If you want to do the comparison in a case-insensitive way, you should use equalsIgnoreCase
instead of equals
.
if ("Chen".equalsIgnoreCase(name)) {
System.out.print("teacher");
} else {
System.out.print("student");
}
Further additional note:
You can make it shorter by using the ternary operator e.g. the following line is equivalent to the complete whole block of code i.e. if() {..} else {..}
mentioned above.
System.out.println("Chen".equalsIgnoreCase(name) ? "teacher" : "student");
答案2
得分: 2
你的问题很容易解决。只需输入以下代码:
if (name.equals("Chen")) {
System.out.print("teacher");
}
因为你将输入的值保存在名为 "name" 的字符串变量中。这应该会解决这个问题。
英文:
your problem is easy to solve. Just type in
if(name.equals("Chen")){
System.out.print("teacher");
}
Because you save the value of your input in the String name. That should fix the issue
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论