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 OverflowYou 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
}
The Scanner will continue to read until it finds an "end of file" condition.
As you're reading from stdin, that'll either be when you send an EOF character (usually ^d on Unix), or at the end of the file if you use < style redirection.
java - While loop with Scanner - Stack Overflow
java - do while loop with input scanner - Stack Overflow
how can i use java scanner in while loop - Stack Overflow
java - Scanner while loop - Stack Overflow
Videos
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;
}The nextInt() call does not consume your input (e.g. "abc") if it isn't an integer. So the next time in the loop it still sees the "abc" that you already entered, and that goes on forever. So better use Integer.parseInt(in.next()):
public static void main (String [] args) {
Scanner in = new Scanner(System.in);
int k = 0;
boolean askForInput = true;
while ( askForInput ) {
System.out.print("Enter an integer: ");
try {
k = Integer.parseInt(in.next());
askForInput = false;
} catch (NumberFormatException e) {
System.out.println("ERR: Not an integer!!");
}
}
}
From the documentation of nextInt:
This method will throw InputMismatchException if the next token cannot be translated into a valid int value as described below. If the translation is successful, the scanner advances past the input that matched.
In other words, nextInt leaves the token in the token stream if it is not recognized as a number. One fix might be to use next() to discard the token in the catch block.
you are declaring int question outside the loop and then again inside the loop.
remove the int declaration inside the loop.
In Java the scope of a variable is dependent on which clause it is declare in. If you declare a variable INSIDE a try or a while or many other clauses, that variable is then local to that clause.
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 sc = new Scanner(System.in);
System.out.println("Enter The Correct Number!");
int question = sc.nextInt();
while (question != 1) {
System.out.println("please try again!");
question = sc.nextInt();
}
System.out.println("Success");
Scanner in = new Scanner(System.in);
Scanner choice = new Scanner(System.in);
System.out.println("Do you want to run the program? Y or N");
choice = Scanner.nextLine(); //Error is here
while (choice.equalsIgnoreCase("y"))
The issue is you are improperly using Scanner.
It should be something like:
String userChoice = choice.nextLine();
To use it in your loop more effectively, you can try something like:
String userChoice = choice.nextLine();
while (userChoice.equalsIgnoreCase("y")) {
// do your loop logic
// then, to be structured, at the end of your loop, do...
System.out.print("Do you want to run the program again? Y or N: ");
userChoice = choice.nextLine();
}
This will re-test the condition after each loop has run. If the user selects "n", the loop will exit naturally.
You should only declare one Scanner to read from the input stream
Scanner scanner = new Scanner(System.in);
And then whenever you want to prompt for input, you can call scanner.next() and it will wait on input.
String input = scanner.next();
An example of this being done could be:
public static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws JSONException {
String input = scanner.next();
System.out.println(input);
}
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();
...
}
}
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.