Java 无法输出同一事件中的字符
用户将输入一个在短语中出现两次的字符,我需要输出两次出现字符之间的短语部分。例如,如果字符是Java 无法输出同一事件中的字符,java,Java,用户将输入一个在短语中出现两次的字符,我需要输出两次出现字符之间的短语部分。例如,如果字符是*,短语是奶牛*跳*过月球,则输出将是跳 我的一部分代码正在工作,它检查短语中字符的出现情况,但我面临着在该字符中输出单词的困难。此外,这只能使用for循环来完成 char x = keyboard.next().charAt(0); for (int y = 0; y < phrase.length(); y++) { char n = phrase.charAt(y); if (
*
,短语是奶牛*跳*过月球
,则输出将是跳
我的一部分代码正在工作,它检查短语中字符的出现情况,但我面临着在该字符中输出单词的困难。此外,这只能使用for
循环来完成
char x = keyboard.next().charAt(0);
for (int y = 0; y < phrase.length(); y++) {
char n = phrase.charAt(y);
if (n == x)
System.out.print(n);
}
charx=keyboard.next().charAt(0);
对于(int y=0;y
您要做的是设置一个“is in printing state”(处于打印状态)变量,告诉代码在遇到字符时打印,然后在再次碰到字符时停止打印。有更好的方法来处理它,这取决于您期望输入的外观,但为了清楚起见,让我们坚持您正在尝试的内容:
char x = keyboard.next().charAt(0);
boolean isPrinting = false;
for (int y = 0; y < phrase.length(); y++){
char n = phrase.charAt(y);
if (n == x){
isPrinting = !isPrinting; //start or stop printing
}
else{
//print the characters if and only if we are in
//a printing state and the current character is
//not the control character
if(isPrinting)
System.out.print(n);
}
}
charx=keyboard.next().charAt(0);
布尔isPrinting=false;
对于(int y=0;y
按以下步骤操作:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter option: ");
int option = Integer.parseInt(keyboard.nextLine());
System.out.print("Enter the phrase: ");
String phrase = keyboard.nextLine();
if (option == 4) {
System.out.print("Enter the character: ");
char marker = keyboard.nextLine().charAt(0);
int counter = 0;
for (int y = 0; y < phrase.length(); y++) {
if (phrase.charAt(y) == marker) {
counter++;
continue;
}
if (counter == 1) {
System.out.print(phrase.charAt(y));
} else if (counter == 2) {
break;
}
}
}
}
}
你为什么想要另一种方式?