[英]Java Lab: Trying to figure where I went wrong. My output does not match the output expected
试图弄清楚如何调整代码以匹配图片中的输出。 当我输入字符串时,在输出中第二次要求输入学生的名字时,我收到一条错误消息。 我试图让while循环继续向我询问学生的姓名和分数,直到我在程序中输入“ alldone”作为学生的姓名以显示得分最高的学生的姓名为止。
import java.util.Scanner;
public class practice {
public static void main(String[] args) {
//Scanner Object
Scanner input = new Scanner(System.in);
//Variables
String name = "Nobody";
String highName = "";
int highScore = 0;
//While-Loop
while (!name.equals("alldone")) {
//User Input Required
System.out.println("Please enter student's name, or \"alldone\" if finished >");
name = input.nextLine();
System.out.println("Please enter student's score >");
int score = input.nextInt();
//If statement
if ((name != "alldone") && (score > highScore)) {
highName = name;
highScore = score;
}else {
}
}
//Output: highName + highScore
System.out.println(highName + " had the highest score which was " + highScore);
//Closed Scanner Object
input.close();
}
}
您应该考虑一些事项,尤其是因为您是这种语言的新手。
A)在Java中,您真正应该真正使用“!=”或“ ==”的唯一方案是用于原始类型比较(int,long,byte,char,Enum等)。
//i.e
if (2 != 3) //False
if (1000 == 1000) //True
if (SomeEnum.SomeEnumType == SomeEnum.SomeOtherEnumType) //False
B)比较两个不是原始对象的对象时,必须通过内置在Java核心中的“ equals(Object obj)”方法进行比较。 此方法确定两个不同对象之间的相等性。 通过在自己的“公共布尔equals(Object obj)”实现之上添加“ @Override”注释,可以在所需的任何类或对象中实现自己的equals函数。
if ("This".equals("That")) //False
if (!("This".equals("That"))) //True
if (SomeRandomObject.equals(SomeOtherRandomObject)) //Truth value is dependent on what makes "SomeRandomObject" equals method return true for a comparative input
C)尽管在Java中,关键字“ do”并未得到广泛使用。.这是一种情形,在这种情况下它可能被证明更有效,而不是两次检查相同的真值。 您可以使用如下所示的do-while循环:
Scanner input = new Scanner(System.in);
String name = "";
do {
name = input.nextLine();
score = input.nextInt();
if (score > highScore) {
highScore = score;
highName = name;
}
} while (!name.equals("alldone"));
需要进行一些更改。 如上面每个人所提到的,一个就是!name.equals(“ alldone”)的名称!=“ alldone”。 另一种方法是,在打印分数提示之前尝试if(!name.equals(“ alldone”)。这样,您也不必检查下部的条件。而且,也可以不用name = input.nextLine (),尝试名称= input.next(),即尝试:
import java.util.Scanner;
public class practice {
public static void main(String[] args) {
//Scanner Object
Scanner input = new Scanner(System.in);
//Variables
String name = "Nobody";
String highName = "";
int highScore = 0;
int score = 0;
//While-Loop
while (!name.equals("alldone")) {
//User Input Required
System.out.println("Please enter student's name, or \"alldone\" if finished >");
name = input.next();
if(!name.equals("alldone")){
System.out.println("Please enter student's score >");
score = input.nextInt();
//If statement
if (score > highScore) {
highName = name;
highScore = score;
}
}
}
//Output: highName + highScore
System.out.println(highName + " had the highest score which was " + highScore);
//Closed Scanner Object
input.close();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.