public void longestName(Scanner console, int num) {
String longest = "";
boolean tie = false;
for(int i = 1; i <= num; i++) {
System.out.print("name #" + i + "? " );
String name = console.next();
if(name.length() == longest.length()) {
tie = true;
} else if(name.length() > longest.length()) {
tie = false;
longest = name;
}
}
String capitalized = longest.substring(0, 1).toUpperCase() +
longest.substring(1).toLowerCase();
System.out.println(capitalized + "'s name is longest");
if(tie)
System.out.println("(There was a tie!)");
}}
if循环总是返回tie为true。如何检查最长名称的领带?
答案 0 :(得分:0)
只有当多个名称具有相同字符并且最长时,if
才会返回true。或者,领带是假的
将您的代码更改为可运行的类,测试如下:
import java.util.Scanner;
public class Test {
public static void main(String args[]){
longestName(new Scanner(System.in), 3);
}
public static void longestName(Scanner console, int num) {
String longest = "";
boolean tie = false;
for (int i = 1; i <= num; i++) {
System.out.print("name #" + i + "? ");
String name = console.next();
if (name.length() == longest.length()) {
tie = true;
} else if (name.length() > longest.length()) {
tie = false;
longest = name;
}
}
String capitalized = longest.substring(0, 1).toUpperCase() +
longest.substring(1).toLowerCase();
System.out.println(capitalized + "'s name is longest");
if (tie)
System.out.println("(There was a tie!)");
}
}
输入是jordan,tom和bob,输出如下:
name #1? jordan
name #2? tom
name #3? bob
Jordan's name is longest
另一个测试是:
name #1? mary
name #2? andy
name #3? tom
Mary's name is longest
(There was a tie!)