當我運行程序並輸入排名&性別時,它對我大叫,並告訴我這是一個無效的性別。我不明白爲什麼如果我輸入「男性」到控制檯,它不等於字符串「男性」?可以請向我解釋爲什麼這不起作用,也許有一些建議如何解決它?謝謝!使用從掃描儀取得的字符串不工作?
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class BabyNames {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
System.out.print("Enter male or female: ");
String gender1 = input.next();
System.out.print("Enter rank: ");
int rank = input.nextInt();
while (!(gender1 == "female" || gender1 == "male")){
System.out.println("Please try again with a valid gender.");
System.out.println("");
System.out.println("Enter male or female: ");
gender1 = input.next();
}
while (rank <= 0 || rank > 1000){
System.out.println("Please try again with a valid rank.");
System.out.println("");
System.out.println("Enter rank: ");
rank = input.nextInt();
}
findRank(gender1, rank);
}
public static void findRank(String gender2, int rank) throws IOException {
File babyNames = new File("/home/skatty14/Downloads/BabyNames.txt");
Scanner input = new Scanner(babyNames);
int rankCount = 0;
while (input.hasNextLine()){
rankCount++;
System.out.println(rankCount);
if (gender2 == "male"){
String name = input.next();
System.out.println(name);
}
if (gender2 == "female"){
String name = input.next();
System.out.println(name);
}
}
}
}
使用不區分大小寫的字符串比較。 – zerodin 2010-10-27 02:05:28