'I can't get the while loop to break when the user inputs a q
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input string:");
String name = sc.nextLine();
while(name.contains(",") == false) {
System.out.println("Error: No comma in string.");
System.out.println("Enter input string:");
name = sc.nextLine();
}
while(!name.equals("q") && !name.equalsIgnoreCase("q")) {
String[] splitting = name.split(",");
String first;
String second;
if(name.compareTo("q") == 1) {
break;
}
if(splitting[1].contains(" ")) {
first = splitting[0];
second = splitting[1].substring(splitting[1].indexOf(' ') + 1, splitting[1].length());
}
else {
first = splitting[0];
second = splitting[1];
}
System.out.println("First word: " + first);
System.out.println("Second word: " + second);
System.out.println("Enter input string:");
name = sc.nextLine();
while(name.contains(",") == false && name.equalsIgnoreCase("q")) {
System.out.println("Error: No comma in string.");
System.out.println("Enter input string:");
name = sc.nextLine();
}
}
System.out.println("Thank you!");
sc.close();
}
}
I'm trying to get this to work when the user inputs a q and it stops the while loop and says thank you at the end.
I have tried so many different ways to do this already.
Solution 1:[1]
sometimes it is simpler to break out of an endless loop:
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter input string (q to quit):");
String input = sc.nextLine();
if ("q".equals(input.toLowerCase())) {
break;
} else if (input.contains(",")) {
String[] splitting = input.split(",");
String first;
String second;
if (splitting[1].contains(" ")) {
first = splitting[0];
second = splitting[1].substring(
splitting[1].indexOf(' ') + 1,
splitting[1].length());
} else {
first = splitting[0];
second = splitting[1];
}
System.out.println("First word: " + first);
System.out.println("Second word: " + second);
}
}
System.out.println("Thank you!");
sc.close();
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
