有没有办法让Java在字符串中每个'if'读取每个单词? 我会尽力解释这个...
public class test{
public static void main(String[] args){
String sentence = "testing1 testing2 testing3 testing4"
//Scan first word \/
if(sentence.equals("testing1"){
//scan second word \/
if(sentence.equals("testing2"){
//scan third word \/
if(sentence.equals("testing3"){
System.out.println("Works good!")
}
}
}
}
}
如果你能帮助我,我会非常感激。
答案 0 :(得分:1)
您可以使用如下的Scanner.next():
String sentence = "testing1 testing2 testing3 testing4";
try (Scanner sc = new Scanner(sentence)) {
if (sc.next().equals("testing1")) {
if (sc.next().equals("testing2")) {
if (sc.next().equals("testing3")) {
if (sc.next().equals("testing4")) {
System.out.println("Works good!");
}
}
}
}
}
答案 1 :(得分:1)
如果我理解你的问题,你可以尝试这样的事情:
public static void main(String[] args){
String sentence = "testing1 testing2 testing3 testing4";
String[] arrayOfWords = sentence.split(" "); // split the sentence according to the spaces
Scanner in = new Scanner(System.in);
//Scan first word
System.out.println("Insert First Word");
if(arrayOfWords[0].equals(in.next())){
System.out.println("Insert Second Word");
if(arrayOfWords[1].equals(in.next())){
System.out.println("Insert Third Word");
if(arrayOfWords[2].equals(in.next())){
System.out.println("Works good!");
}
}
}
}
例如:
Insert First Word
testing1
Insert Second Word
testing2
Insert Third Word
testing3
Works good!
答案 2 :(得分:0)
url.dev/images/no-image.png