-1
例如一個角色,我有如何獲得位於前另一個字符
Scanner scan = new Scanner(System.in);
String a = scan.nextLine();
讓我們假設一個用戶輸入abctd
。
getCharcterBeforeT(example)
- 在這部分需要幫助
例如一個角色,我有如何獲得位於前另一個字符
Scanner scan = new Scanner(System.in);
String a = scan.nextLine();
讓我們假設一個用戶輸入abctd
。
getCharcterBeforeT(example)
- 在這部分需要幫助
怎麼是這樣的:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a string:");
String intialString = scan.nextLine();
System.out.print("What is the character you would like to get the character before:");
String character = "";
while(true){
character = scan.nextLine();
if(character.length()==1)
break;
else
System.out.print("Please enter only 1 character:");
}
System.out.println(getCharcterBeforeT(intialString, character.charAt(0)));
}
public static char getCharcterBeforeT(String str, char c){
char returnChar = ' ';
if (str.indexOf(c) == -1){
System.out.println("Character '" + c + "' not found");
} else if (str.indexOf(c) == 0){
System.out.println("Character '" + c + "' is at start of string");
} else {
returnChar = str.charAt(str.indexOf(c) - 1);
}
return returnChar;
}
}
控制檯:
Enter a string: abctd
What is the character you would like to get the character before: a
Character 'a' is at start of string
Enter a string: abctd
What is the character you would like to get the character before: b
a
Enter a string: abctd
What is the character you would like to get the character before: q
Character 'q' not found
試試吧here!