Home > Net >  Separating Strings by a comma
Separating Strings by a comma

Time:04-03

I have to separate a string with a comma into two names. So if the input is Sarah, Low: then the first name is Sarah and the second name is Low. But to figure that out, it uses a comma. My code doesn't run and I am confused why. I think that the error is in the nested if statement, but I don't know what else to do. Any help would be much appreciated.

Code:

  String userInput; 
  String name1; 
  String name2; 
  
  while (true) { 
     System.out.println("Enter input string:"); 
     userInput = scnr.nextLine(); 
     userInput = userInput.trim(); 
     if (userInput.equals("q")) { 
        break; 
     } 
  } 
  for (int i = 0; i < userInput.length(); i  ) { 
     if (userInput(i).equals(",") {
        name1 = userInput.substring(0, userInput.indexOf(",")); 
        name2 = userInput.substring(userInput.indexOf(",")   1, userInput.length()); 
        System.out.println("First word:"   name1); 
        System.out.println("Second words:"   name2); 
     } 
     else { 
        System.out.println("Error: No comma in string."); 
     } 
  } 

CodePudding user response:

Your code asks for some user input in an infinite loop and only breaks from it when the user types q. It means that your userInput will always be q when you start the for loop.

In addition to that your code does not even compile as a Java code because of other errors already described by others.

CodePudding user response:

Based on my understanding of your question, I believe you would like to keep entering names with comma and let the program separate the userInput using comma into two names- name1 and name2 respectively. When you are done, you would press q to exit the program. Here is a cleaner code snippet to do the job instead of using a for loop-

while(true) {
            Scanner scanner = new Scanner(System.in);
            System.out.println("Enter Name with comma OR type q to Quit:");
            String userInput = scanner.nextLine();
            userInput = userInput.trim();
            if (userInput.equals("q")) {
                System.out.println("Stopped.");
                return;
            }
            String[] nameSplitByComma = userInput.split(",");
            if (nameSplitByComma.length < 2) {
                System.out.println("Error: No comma in string.");
            } else {
                String name1 = nameSplitByComma[0];
                String name2 = nameSplitByComma[1];
                System.out.println("First word:"   name1);
                System.out.println("Second words:"   name2);
            }
        }
  • Related