我的老师分配我使用给定的方法 getScrabbleScore 和 scrabbleLetterValue 创建代码。代码中的所有内容都已预先编写,我只是被要求填写 getScrabbleScore。通过IntelliJ调试时发现,如果不是while循环的条件,输出是正确的。
import java.util.Scanner;
/**
* @author your_name
*/
/*You ONLY need to change the body of getScrabbleScore under the "TODO" comment. DO NOT change anything else.*/
public class WordScore {
int scrabbleScore;
String word;
/**
* @param word int to record scrabble word
*/
WordScore(String word) {
this.word = word.toLowerCase();
this.scrabbleScore = getScrabbleScore();
}
/**
* @param tile char to return value for
* @return point value for specific tile
*/
public int scrabbleLetterValue(char tile) {
switch (tile) {
case 'a':
case 'e':
case 'i':
case 'l':
case 'n':
case 'o':
case 'r':
case 's':
case 't':
case 'u':
return 1;
case 'd':
case 'g':
return 2;
case 'b':
case 'c':
case 'm':
case 'p':
return 3;
case 'f':
case 'h':
case 'v':
case 'w':
case 'y':
return 4;
case 'k':
return 5;
case 'j':
case 'x':
return 8;
case 'q':
case 'z':
return 10;
default:
return -1;
}
}
/**
* @return int word score value as described in project instructions
*/
public int getScrabbleScore() {
/** TODO: Defnition for getScrabbleScore
*/
for (int i = 0; i < word.length(); i++) {
scrabbleScore += scrabbleLetterValue(word.charAt(i));
}
return scrabbleScore;
}
/* DO NOT edit this main method. If you do, you can reset your assignment to restore the method.*/
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
WordScore ws;
while (read.hasNextLine()) {
ws = new WordScore(read.nextLine());
System.out.println(ws.getScrabbleScore());
}
}
}
我想要的输入(例如“标枪”)是 17,但我得到的是 34。
最佳答案
普遍的问题是代码结构很糟糕 - 不是来自你,而是来自你的老师。
方法 getScrabbleScore
应该是私有(private)的并调用一次或
该方法应该是公共(public)但不能通过不使用字段scrabbleScore
来更改WordScore
实例的状态。
现在您有两个选择,具体取决于您认为哪种方式更正确。
选项 1:将 scrabbleScore = 0
写入 getScrabbleScore
中的第一个语句,每次都会重置该字段你需要计算一下。
选项 2:在方法中添加一行 int Score = 0
并在末尾添加 return Score
,留下字段 scrabbleScore
未受影响。
这里没有绝对正确的答案,因为代码一开始就有缺陷。
关于java - 我的老师指示不要编辑的 while 循环返回我的 for 循环的值,但使其运行两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54465562/