我正在编写一个代码以从用户输入(a&b)中创建一个新单词(c),所以我需要一个代码来检查一个字符串是否等于另一个,但是它表明该字符串仅等于a另一个字符串的一部分。
import java.util.Scanner;
public class GabungKata_1402019129 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("----------------------------------");
System.out.println(" Program Gabung Kata");
System.out.println(" Dibuat oleh 1402019129");
System.out.println("----------------------------------");
System.out.print("Masukkan kata pertama: "); // Enter First word
String first = sc.nextLine(); // Bbxx
System.out.print("Masukkan kata kedua : "); // Enter Second word
String second = sc.nextLine(); // oxxx
String result = ""; // new String that is a combination from first and
// second
String[] names = {"Bob", "Zidan", "Fawzan", "Arkan", "Raihan"};
boolean data = true;
int n = 0;
do {
for (String check: names) {
if (result.equals(check)) {
data = false;
}else
data = true;
}
result += first.charAt(n);
result += second.charAt(n);
n++;
} while(data & n < first.length() & n < second.length());
System.out.println("New Word: " + result);
System.out.println("Is the new word is one of the names? " + !data);
}
}
新词将显示:“ Bobxxxxx”,但是我认为当结果等于“ Bob”时,它应该停止。我需要的是当结果等于名称之一时停止循环的代码块。我的英语不好,所以我希望你们能听懂。
答案 0 :(得分:0)
根据您的描述,这应该可以工作,尽管我确信有更好的方法可以做到这一点:
class Scratch {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("----------------------------------");
System.out.println(" Program Gabung Kata");
System.out.println(" Dibuat oleh 1402019129");
System.out.println("----------------------------------");
System.out.print("Enter First word: "); // Enter First word
String firstString = sc.nextLine(); // Bbxx
System.out.print("Enter Second word : "); // Enter Second word
String secondString = sc.nextLine(); // oxxx
String combinedString = ""; // new String that is a combination from first and
// second
String[] targetNames = {"Bob", "Zidan", "Fawzan", "Arkan", "Raihan"};
boolean shouldContinue = true;
int index = 0;
String interlacedString = createInterlacedString(firstString, secondString);
do {
for (String targetName: targetNames) {
if (combinedString.equals(targetName)) {
shouldContinue = false;
break;
}
}
if(shouldContinue){
combinedString += interlacedString.charAt(index);
index++;
}
} while(shouldContinue
&& (index < firstString.length())
&& (index < secondString.length())
);
System.out.println("New Word: " + combinedString);
System.out.println("Is the new word is one of the names? " + !shouldContinue);
}
public static String createInterlacedString(String stringOne, String stringTwo){
String interlacedString = "";
for(int i = 0; i < stringOne.length(); i++){
interlacedString += stringOne.charAt(i);
if(i < stringTwo.length()){
interlacedString += stringTwo.charAt(i);
}
}
if(stringTwo.length() > stringOne.length()){
interlacedString += stringTwo.substring(stringOne.length());
}
return interlacedString;
}
}
请注意,createInterlacedString的静态类仅是为了让我可以在IDE的临时文件中运行它。