You keep on getting new a new string and continue the loop if it's not empty. Simply insert a control in the loop for an exit string.

while(!s1.equals("exit") && sc.hasNext()) {
    // operate
}

If you want to declare the string inside the loop and not to do the operations in the loop body if the string is "exit":

while(sc.hasNext()) {
    String s1 = sc.next();
    if(s1.equals("exit")) {
        break;
    }
    //operate
}
Answer from İsmet Alkan on Stack Overflow
🌐
Coderanch
coderanch.com › t › 697352 › java › Loop-Scanner-Class
Using While Loop and Scanner Class [Solved] (Beginning Java forum at Coderanch)
July 31, 2018 - Two problems: A missing semicolon, and you need to calculate square root outside of loop. JavaRanch-FAQ HowToAskQuestionsOnJavaRanch UseCodeTags DontWriteLongLines ItDoesntWorkIsUseLess FormatCode JavaIndenter SSCCE API-17 JLS JavaLanguageSpecification MainIsAPain KeyboardUtility ... Also, the conditional statement used in the while block (num < 0) prevents any of the code withing the while block from being executed if a positive integer is entered by the user.
Discussions

java - While loop with Scanner - Stack Overflow
See similar questions with these tags. ... 0 distinguish the working of Scanner, System.in, and next() methods that the Scanner class provides in java? 1303 Removing objects from a collection in a loop without causing ConcurrentModificationException More on stackoverflow.com
🌐 stackoverflow.com
java - do while loop with input scanner - Stack Overflow
I would like to create option with do while were user after inputting correct letter will get out of the loop. I have try to make one but if I put while(type == "Y") it just throws me out of the loop More on stackoverflow.com
🌐 stackoverflow.com
how can i use java scanner in while loop - Stack Overflow
If you declare a variable INSIDE a try or a while or many other clauses, that variable is then local to that clause. ... Sign up to request clarification or add additional context in comments. ... from my understanding your requirement is to prompt the user again and again until you match the correct number. If this is the case it would as follows: the loop iterates as long as the user enters 1. Scanner ... More on stackoverflow.com
🌐 stackoverflow.com
java - Scanner while loop - Stack Overflow
So I am having issues with a while loop(been awhile). I am getting a compiling error while trying to set a scanner object to do a program while user input is "y". How do I get this to work? Error i... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Reddit
reddit.com › r/learnjava › scanner not working in a while loop
r/learnjava on Reddit: Scanner Not Working in a While Loop
May 28, 2020 -

So, I'm working on a personal project that allows the employer (user) to log there employees and what days each of them can work and then the code automatically creates a weekly schedule based on certain schedule parameters (ex. no one works less than 2 days or more than 4, at least one person everyday, etc.)

One part of this code is a method in the runner class that allows the user to add employees, represented by the Worker class (not shown), and what days in a Monday-Saturday work week to an ArrayList. However, as I was testing this, the scanner for the name of the employee isn't running after the first turn of the while loop. It just skips it entirely and puts it in as "" in the system.out.println asking about each workday. Am I doing something right?

//Iniatilizes roster to hold emplyoees
  public static ArrayList <Worker> makeRoster(){
    
   Scanner scan = new Scanner(System.in);
   
   //ArrayList to be returned by method
   ArrayList <Worker> roster = new ArrayList <Worker> (); 
   
   //Control variable for while loop that is set to false once "-1" is placed as name
   boolean c = true;
   
   //ID number for employee; all it's really used for is aesthetics and user-friendliness
   int id = 1;
   
   //Array of days so that a for-loop can be used for recording employee availability
   String [] week = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
   
   //String holding employee name
   String n = "";
  
   while(c){
     
    System.out.println("Please enter Employee #" + id + "'s name. Enter -1 if you have no more employees to add.");
     n = scan.nextLine();
     
    //Creates array recording employee avaliablity that, with name n, creates a new Worker object and adds it to the ArrayList
    if(!n.equals("-1")){
     boolean[] date = new boolean[6];
     
     for(int i = 0; i < date.length; i++){
       System.out.println("Is " + n + " avaliable " + week[i] + "? Enter 1 (true) or 0 (false).");
       int ava = scan.nextInt();
       
       if(ava == 1){
        date[i] = true; 
       }else{
        date[i] = false; 
       }
     }

    roster.add(new Worker(n, date));
     
    //If name is set to "-1" then c is set to false to end while loop
    }else{
     c = false; 
    }
    
    //Increment ID variable
    id++;
   } 
   
   
   return roster;
  }
🌐
Quora
quora.com › How-do-you-use-a-scanner-for-a-loop-in-Java
How to use a scanner for a loop in Java - Quora
... Create a Scanner tied to the input source. Use a loop (while, for, or do-while) that checks Scanner methods (hasNext, hasNextInt, hasNextLine, etc.) to avoid NoSuchElementException.
🌐
GitHub
gist.github.com › 7089502
Testing infinite while loop in java with scanner class · GitHub
Testing infinite while loop in java with scanner class - infinitiLoopMain.java
Find elsewhere
🌐
YouTube
youtube.com › alec parfitt
Java Scanner tutorial with while and for loops - YouTube
Learn how to use Java's Scanner to get user input, iterate over an input String, and continue prompting for input until the user is done.
Published   March 18, 2021
Views   22K
🌐
University of Washington
courses.cs.washington.edu › courses › cse121 › 24su › resources › cheatsheets › cheatsheet-09
While Loops, User Input, and Scanner - CSE 121
import java.util.*; // make sure you don't forget this! public class ScannerExample { public static void main(String[] args) { //Create a Scanner object Scanner console = new Scanner(System.in); // Get next integer user input from console and stores in num int num = console.nextInt(); } } (pulling one iteration out of the loop) int num = 1; System.out.print(num); // one number to start with while (num < 5) { num++; System.out.print(", " + num); // commas between numbers } ×Close ·
🌐
Programming Simplified
programmingsimplified.com › java › tutorial › java-while-loop
Java while loop | Programming Simplified
import java.util.Scanner; class BreakContinueWhileLoop { public static void main(String[] args) { int n; Scanner input = new Scanner(System.in); while (true) { System.out.println("Input an integer"); n = input.nextInt(); if (n != 0) { System.out.println("You entered " + n); continue; } else { break; } } } } Continue statement takes control to the beginning of the loop, and the body of the loop executes again. Whatever you can do with a while loop can be done with a for loop or a do-while loop.
🌐
Sololearn
sololearn.com › en › Discuss › 2670967 › problem-with-scannernextint-in-dowhile-loops
Problem with scanner.nextInt in do-while loops | Sololearn: Learn to code for FREE!
import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner sc = new Scanner(System.in); do{ int x = sc.nextInt(); if(x == 1){System.out.println("Language selection");} else if(x == 2){System.out.println("Customer support");} else if(x == 3){System.out.println("Check the balance");} else if(x == 4){System.out.println("Check loan balance");} else if(x == 0){System.out.println("Exit");} else{ } } while (sc.hasNextInt()); } }
🌐
BeginwithJava
beginwithjava.com › java › loops › do-while-loop.html
Do While Loop in Java
System.out.print("Enter integer: "); value = console.nextInt(); // add value to sum sum = sum + value; // Get the choice from the user to add more number System.out.print("Enter Y for yes or N for no: "); choice = console.next().charAt(0); } while ((choice == 'y') || (choice == 'Y')); //Display ...
🌐
W3Schools
w3schools.com › java › java_while_loop.asp
Java While Loop
In the next chapter, you will learn about the do while loop, which always runs the code at least once before checking the condition. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
Top answer
1 of 2
2

One problem is that System.in is basically an infinite stream: hasNext will always return true unless the user enters a special command that closes it.

So you need to have the user enter something that tells you they are done. For example:

while(input.hasNext()) {
    System.out.print("Enter an integer or 'end' to finish: ");
    String next = input.next();
    if("end".equalsIgnoreCase(next)) {
        break;
    }

    int theInt = Integer.parseInt(next);
    ...

For your program, you might have the input you are trying to parse end with a special character like 1,2;3,4;5,6;end or 1,2;3,4;5,6;# that you check for.

And on these lines:

System.out.print(i + ' ');
System.out.print(alist.get(i) + '\n');

It looks like you are trying to perform String concatenation but since char is a numerical type, it performs addition instead. That is why you get the crazy output. So you need to use String instead of char:

System.out.print(i + " ");
System.out.print(alist.get(i) + "\n");

Or just:

System.out.println(i + " " + alist.get(i));

Edit for comment.

You could, for example, pull the input using nextLine from a Scanner with a default delimiter, then create a second Scanner to scan the line:

Scanner sysIn = new Scanner(System.in);
while(sysIn.hasNextLine()) {
    String nextLine = sysIn.nextLine();
    if(nextLine.isEmpty()) {
        break;
    }

    Scanner lineIn = new Scanner(nextLine);
    lineIn.useDelimiter(";|\\,");

    while(lineIn.hasNextInt()) {
        int nextInt = lineIn.nextInt();
        ...
    }
}
2 of 2
0

Since Radiodef has already answered your actual problem(" instead of '), here are a few pointers I think could be helpful for you(This is more of a comment than an answer, but too long for an actual comment):

When you use Scanner, try to match the hasNextX function call to the nextX call. I.e. in your case, use hasNextInt and nextInt. This makes it much less likely that you will get an exception on unexpected input, while also making it easy to end input by just typing another delimiter.

Scanners useDelimiter call returns the Scanner, so it can be chained, as part of the initialisation of the Scanner. I.e. you can just write:

Scanner input = new Scanner(System.in).useDelimiter(";|\\,");

When you add to the end of an ArrayList, you don't need to(and usually should not) specify the index.

int i = 0, i++ is the textbook example of a for loop. Just because your test statement doesn't involve i does not mean you should not use a for loop.

Your code, with the above points addressed becomes as follows:

ArrayList<Integer> alist = new ArrayList<>();
Scanner input = new Scanner(System.in).useDelimiter(";|\\,");
for (int i = 0; input.hasNextInt(); i++) {
    alist.add(input.nextInt());
    System.out.println(i + " " + alist.get(i));
}
System.out.println('x');

Edit: Just had to mention one of my favorite delimiters for Scanner, since it is so suitable here:

Scanner input = new Scanner(System.in).useDelimiter("\\D");

This will make a Scanner over just numbers, splitting on anything that is not a number. Combined with hasNextInt it also ends input on the first blank line when reading from terminal input.

🌐
javaspring
javaspring.net › blog › how-to-get-out-of-while-loop-in-java-with-scanner-method-hasnext-as-condition
How to Exit a While Loop in Java When Using Scanner hasNext() as Condition (Fix for Endless Loop)
The endless loop occurs because hasNext() never returns false for interactive input streams (like System.in, which reads from the console) unless explicitly told to. Consider this simple code that reads input from the console using hasNext(): import java.util.Scanner; public class EndlessLoopExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter input (type 'exit' to quit)..."); while (scanner.hasNext()) { // Loop condition: hasNext() String input = scanner.next(); // Read next token System.out.println("You entered: " + input); } scanner.close(); // This line will NEVER execute!
🌐
Edureka
edureka.co › blog › java-while-loop
While Loop in Java | Java While Loop Examples | Edureka
August 28, 2024 - The while loop in Java is used to iterate a part of the program again and again. If the number of iteration is not fixed, then you can use Java while loop.
🌐
TheServerSide
theserverside.com › blog › Coffee-Talk-Java-News-Stories-and-Opinions › Java-Scanner-User-Input-example-String-next-int-long-char
Java Scanner User Input Example
You do not need to instantiate it with the new keyword each time. To continually grab input from the user, you can use the Scanner’s hasNext() method as the condition for a while loop.