在这段代码中,用户可以猜出名字中的3个字母,然后用户就可以猜出实际的名字。有人知道如何修复这个代码吗?如果用户输入“m”,即使名称以大写字母m开头,他们仍然会被告知它的位置?
//import java scanner
import java.util.Scanner;
//declare variables
class Main
{
Scanner scan = new Scanner(System.in);
String name = "Matt";
String guessedName;
int nameLength, position, guesses;
char guess;
//method for guessLetter
public void guessLetter()
{
nameLength = name.length();
System.out.println("The name I am thinking of is " + nameLength + " letters long.\nYou will be able to pick three letters and I'll let you know the location letter occurs in the name. Then you can guess the name.");
guesses = 3;
while(guesses >= 1)
{
System.out.println("Guess one letter?");
guess = scan.nextLine().charAt(0);
letters();
guesses -= 1;
}
}
//method for guess Name
public void guessedName()
{
System.out.println("Guess what you think the name is?");
guessedName = scan.nextLine();
if(guessedName.equalsIgnoreCase(name)){
System.out.println("Correct, that is the name!");
}
else{
System.out.println("Wrong, that is not the correct name.");
System.out.println("The name is " + name + ".");
}
}
//method for letters
public void letters()
{
if(name.indexOf(guess)>-1)
{
position = name.indexOf(guess);
System.out.println(guess + " is at position " + position + ".");
}
else
{
System.out.println(guess + " is not in the name!");
}
}
public static void main(String[] args)
{
Main prog = new Main ();
prog.guessLetter();
prog.guessedName();
}
}
2条答案
按热度按时间brtdzjyr1#
只需检查循环中的字符。那是什么
indexOf
做。像这样的。0md85ypi2#
如果希望比较忽略大小写,但不希望转换
name
,则需要测试两次-每种情况一次。基本上,上述代码执行以下操作:
如果
guess
匹配中的字母name
那我们就完了。如果没有,则检查
guess
.如果
guess
是大写,转换成小写。如果
guess
是小写,转换成大写。重新检查是否已转换
guess
匹配中的字母name
.请参阅java.lang.character类
或者,可以使用正则表达式。