Reputation: 37
Is there a way to make Java read each individual word per 'if' in string? I will try my best to explain this...
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!")
}
}
}
}
}
If you can help me I would really appreciate it.
Upvotes: 2
Views: 85
Reputation: 325
String[] array = sentence.split(" ");
//Scan first word \/
if(array[0].equals("testing1"){
//scan second word \/
if(array[1].equals("testing2"){
//scan third word \/
if(array[2].equals("testing3"){
System.out.println("Works good!")
}
}
}
Upvotes: 0
Reputation: 5613
You can use Scanner.next() like below:
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!");
}
}
}
}
}
Upvotes: 1
Reputation: 14062
If I understand your question properly, you may try something like this:
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!");
}
}
}
}
for example:
Insert First Word
testing1
Insert Second Word
testing2
Insert Third Word
testing3
Works good!
Upvotes: 1