0
當我提示用戶寫兩個單詞時,如何打印哪個單詞首先按字母順序排列?以及如何檢查掃描字中是否存在某個字符?如何在字符串中查找字母以及如何按字母順序返回兩個字符串? java
例如:如果用戶寫了「Word」和「Apple」,我怎樣才能按字母順序打印這兩個單詞。另外,我編寫了一個程序來檢查字符「z」是否出現在字中,但我不知道它有什麼問題?這裏是我的程序:
import java.util.*;
public class Pr7{
public static void main(String[] args){
//print two words and read them..
Scanner scan = new Scanner (System.in);
String Word1;
String Word2;
System.out.println();
System.out.print("* Please write one word: ");
Word1 = scan.nextLine();
System.out.print("* Please write one word: ");
Word2 = scan.nextLine();
//Prints which word has more characters in it..
if (Word1.length() > Word2.length())
System.out.println("- " + "(" + Word1 + ")" + " has more characters.");
else if (Word2.length() > Word1.length())
System.out.println("- " + "(" + Word2 + ")" + " has more characters.");
else
System.out.println("- " + "(" + Word1 + ")" + " has equal characters with " + "(" + Word2 + ")");
//Prints which word comes first (alphabetically)..
/*
char ch;
int compare = Word1.compareTO(Word2);
*/
//Prints whether the letter 'z' appears in either word..
if (Word1.indexOf('z') == true)
System.out.print("- Letter 'z' appears in the first word.");
else if (Word2.indexOf('z') ==)
System.out.print("- Letter 'z' appears in the second word.");
else
System.out.print("- Letter 'z' doesn't appears in either word.");
System.out.println();
//Prompts the user for a sentence and reads it..
String Str1;
String Str2;
System.out.println();
System.out.print("* Please write a string: ");
Str1 = scan.nextLine();
System.out.print("* Please write a string: ");
Str2 = scan.nextLine();
//Prints how many characters are in the first sentence and the second sentence..
if (Str1.length() > Str2.length()){
System.out.println("- " + "(" + Str1 + ")" + " has more characters.");
System.out.print("- " + "(" + Str1 + ")" + " = " + Str2.length() + " Character(s)" + " && " + "(" + Word2 + ")" + " = " + Word2.length() + " Character(s)");
}
else if (Str2.length() > Str1.length()){
System.out.println("- " + "(" + Str2 + ")" + " has more characters.");
System.out.print("- " + "(" + Str2 + ")" + " = " + Str2.length() + " Character(s)" + " && " + "(" + Word1 + ")" + " = " + Word1.length() + " Character(s)");
}
else{
System.out.println("- " + "(" + Str1 + ")" + " has equal characters with " + "(" + Str2 + ")");
System.out.print("- " + "(" + Str1 + ")" + " = " + Str1.length() + " Character(s)" + " && " + "(" + Word2 + ")" + " = " + Word2.length() + " Character(s)");
}
System.out.println();
}//main
}//Pr7
我知道我需要調用的方法,但我不知道如何使用它。