Java Scanner Not Blocking During Loop - java

I am running into a problem where Scanner isn't blocking for user input during an indefinite while loop. I've tried using hasNextLine() and that hasn't worked. It just runs the loop infinitely calling displayMenu().
do {
displayMenu();
int response;
while (iStream.hasNextLine()) {
response = Integer.parseInt(iStream.nextLine());
switch (response) {
case 1:
decodeMessage(getPhrase());
break;
case 2:
encodeMessage(getPhrase());
break;
case 3:
displayAlphabet();
break;
case 4:
done = true;
System.out.println("Goodbye.");
break;
default:
done = false;
}
}
}
while (!done);
I've also tried not using hasNextLine() but I end up with a NoSuchElementException as it runs through perfectly the first time but on the second iteration, it doesn't block for user input.
do {
displayMenu();
int response = Integer.parseInt(iStream.nextLine());
switch (response) {
case 1:
decodeMessage(getPhrase());
break;
case 2:
encodeMessage(getPhrase());
break;
case 3:
displayAlphabet();
break;
case 4:
done = true;
System.out.println("Goodbye.");
break;
default:
done = false;
}
}
while (!done);
Any thoughts?

The following works fine for me:
private static void displayMenu ()
{
System.out.println ("Menu:");
System.out.println ("\t1: Decode message");
System.out.println ("\t2: Encode message");
System.out.println ("\t3: Display alphabet");
System.out.println ("\t4: Exit");
}
public static void main (String [] args)
{
Scanner scanner = new Scanner (System.in);
boolean done = false;
while (!done)
{
displayMenu();
switch (Integer.parseInt (scanner.nextLine ()))
{
case 1:
System.out.println ("Decoding...");
break;
case 2:
System.out.println ("Encoding...");
break;
case 3:
System.out.println ("Displaying alphabet...");
break;
case 4:
System.out.println("Exitting...");
done = true;
break;
default:
done = false;
}
}
}

Related

I need a way to exit my infinity loop in java when the user inputs anything, but the loop pauses while its looking for inputs

I am making a clock and I obviously don't want the clock to pause while it's looking for inputs.
i first use the switch-case statement which changes the value of timezone_str and then the local time method prints it
So please tell me a way using which I can help the user exit my infinity loop (it's fine if it's not by inputting). || PLS NOTE: I USE BLUE J ||
Here is my code:-
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Scanner;
public class AnalogClock_Project {
public static void main(String[] args) {
int choose = 0;
boolean PutAnEndToThis = true;
String timezone_str = new String();
Scanner sc = new Scanner(System.in);
choose = sc.nextInt();
switch(choose) {
case 1:
timezone_str = "UTC";
break;
case 2:
timezone_str = "GMT";
break;
case 3:
timezone_str = "US/Central";
break;
case 4:
timezone_str = "PST";
break;
case 5:
timezone_str = "Asia/Kolkata";
break;
case 6:
timezone_str = "Japan";
break;
case 7:
timezone_str = "Europe/London";
break;
case 8:
timezone_str = "Hongkong";
break;
case 9:
timezone_str = "Australia/Sydney";
break;
case 10:
timezone_str = "Europe/Rome";
break;
case 11:
timezone_str = "US/Eastern";
break;
case 12:
timezone_str = "US/Hawaii";
break;
case 13:
timezone_str = "Africa/Cairo";
break;
case 14:
timezone_str = "America/Mexico_City";
break;
case 15:
timezone_str = "Asia/Riyadh";
break;
case 16:
timezone_str = "Europe/Moscow";
break;
case 17:
timezone_str = "Asia/Manila";
break;
}
System.out.print('\f');
Scanner sC = new Scanner(System.in);
while (PutAnEndToThis) {
LocalTime time = LocalTime.now(ZoneId.of(timezone_str));
System.out.print(time);
try{
Thread.sleep(500);
}
catch(InterruptedException ie) {}
System.out.print('\f');
}
System.out.print("\f thank you for using you clock \n hopefully you can get rich enough \n to buy a watch next time");
}
}
Start a separate Thread to print the time. Use Scanner to accept a value from the user. When the user enters a value, interrupt the Thread.
final String timezone_str = "UTC";
Thread thrd = new Thread(() -> {
while (true) {
LocalTime time = LocalTime.now(ZoneId.of(timezone_str));
System.out.print(time);
try {
Thread.sleep(1000);
}
catch (InterruptedException ie) {
break;
}
System.out.print('\f');
}
});
thrd.start();
Scanner in = new Scanner(System.in);
in.next();
thrd.interrupt();
The user needs to press some key on the keyboard and then press <ENTER>. As soon as she does, the Thread will terminate.
Note that I used an arbitrary value for timezone_str since it was not clear to me, from your question, how you assign a value to that variable.
Try to change 1=1 to a boolean variable and break the loop with it.
Example:
boolean key = true;
while (key)
{
LocalTime time = LocalTime.now(ZoneId.of(timezone_str));
System.out.print(time);
try{
Thread.sleep(100);
} catch(InterruptedException ie) {
//Do something to change key
}
//Do something to change key
}

input a txt file with bunch of number in every row

Hi i have a txt file that have a number in bunch of rows and i get this error
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
what can i add in my code to make it work it seems to be right to me but idont know why i get error
public static void main(String[] args) {
String input;
try {
Scanner scan = new Scanner(new File("andy.txt"));
while (scan.hasNextLine()) {
lineCounters++;
input = scan.nextLine();
putArray(sigFig(input));
}
calcPercentage();
makeGraph();
scan.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
here is my putArray
public static void putArray(char input) {
switch (input) {
case '1':
++digitCounters[0];
break;
case '2':
++digitCounters[1];
break;
case '3':
++digitCounters[2];
break;
case '4':
++digitCounters[3];
break;
case '5':
++digitCounters[4];
break;
case '6':
++digitCounters[5];
break;
case '7':
++digitCounters[6];
break;
case '8':
++digitCounters[7];
break;
case '9':
++digitCounters[8];
break;
}
}
It might be your putArray function which launches that exception. Can I have a look of it?

How to switchcases inside if loop

I'm stuck at a question that requests me if the user insert something else instead "e" "x" nums between 1 to 10, then it's returning "incorrect"
here's the code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try{
int Num = 0;
Num = sc.nextInt();
String str = sc.nextLine();
switch (Num) {
case 1: case 2: case 3: case 4:
case 5: case 6: case 7: case 8:
case 9: case 10:
System.out.println("this is a volume");
break;
case : if((Num>10)||(Num <0))
System.out.println("this is incorrect");
break;
}
switch (str) {
case "e": case "E":
System.out.println("Shutting Down");
break;
case "x" : case "X":
System.out.println("Mute");
break;
case "a":case "b":case "c":case "d":case "f":case "g":case "h":case "i":case "j":
case "k":case "l":case "m":case "n":case "o":case "p":case "q":case "r":case "s":
case "t":case "u":case "v":case "w":case "y":case "z":
System.out.println("this is incorrect");
break;
default:
break;
}
}
catch(Exception e) {
System.out.println("stopped");
}
}
}
thank you
If I understand your question properly, as you did not specify how many time the user should enter the input. However, you can have a look at this example, take the idea of the approach and then create your own one.
import java.util.Scanner;
public class ParseInput {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Insert E for Shutdown, X for Mute and Numbers between 1 to 10 for Volume");
String input = in.nextLine().trim(); // read the entire line after removing spaces if any, then parse it
if(input.length()>0){ // that means the user entered something
try{
int volumeValue = Integer.parseInt(input); // if it's not a number, it will throw exception that will be handled in the catch block
if(volumeValue>=1 && volumeValue<=10){// then evaluate the value
System.out.println("This is a Volume");
}
else{
System.out.println("Incorrect Volume Value");
}
}catch(NumberFormatException e){ // if you reach this block that means it's not a number
if(input.equalsIgnoreCase("e")){ // to accept both uppercase and lowercase
System.out.println("Shutting Down");
}
else if(input.equalsIgnoreCase("x")){
System.out.println("Mute");
}
else{
System.out.println("Incorrect Input");
}
}
}
else{
System.out.println("You have NOT entered anything!");
}
}
}
Test
Insert E for Shutdown, X for Mute and Numbers between 1 to 10 for Volume
e -> Shutting Down
x -> Mute
5 -> This is a Volume
12 -> Incorrect Volume Value
ZzZ -> Incorrect Input
-> You have NOT entered anything!
Please try the below code
switch (Num)
{
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
System.out.println("this is a volume");
break;
default:
{
if ((Num > 10) || (Num < 0))
{
System.out.println("this is incorrect");
}
break;
}
}

Java command prompt loop

I have this simple code that works like a small command prompt. User is asked to enter a command and is displayed a message according to what he entered. I just want to make it loop so that the user is asked to enter a command again and again and again until he types 'exit'. How do I do that?
Here is the code:
public static void main(String[] args) {
Scanner command = new Scanner(System.in);
System.out.println("Enter command: ");
String text = command.nextLine();
switch(text){
case "start":
System.out.println("Machine started!");
break;
case "stop":
System.out.println("Machine stopped.");
break;
case "exit":
System.out.println("Application Closed");
break;
default:
System.out.println("Command not recognized!");
break;
}
command.close();
}
Thank you
I prefer:
public static void main(String[] args) {
Scanner command = new Scanner(System.in);
System.out.println("Enter command: ");
boolean running = true;
while(running){
switch(command.nextLine()){
case "start":
System.out.println("Machine started!");
break;
case "stop":
System.out.println("Machine stopped.");
break;
case "exit":
System.out.println("Application Closed");
running = false;
break;
default:
System.out.println("Command not recognized!");
break;
}
}
command.close();
}
You can put it in a while loop like this:
String text = "";
while(!text.equalsIgnoreCase("exit"))
{
System.out.println("Enter command: ");
text = command.nextLine();
switch(text){
case "start":
System.out.println("Machine started!");
break;
case "stop":
System.out.println("Machine stopped.");
break;
case "exit":
System.out.println("Application Closed");
break;
default:
System.out.println("Command not recognized!");
break;
}
}
Just let the condition for your while loop be while text <> "exit".
Something like this? I prefer do-while for this type of situation because you probably want to give at least one command.
public static void main(String[] args) {
boolean running = true;
Scanner command = new Scanner(System.in);
do {
System.out.println("Enter command: ");
String text = command.nextLine();
switch(text){
case "start":
System.out.println("Machine started!");
break;
case "stop":
System.out.println("Machine stopped.");
running = false; //here?
break;
case "exit":
System.out.println("Application Closed");
running = false; //..or here?
break;
default:
System.out.println("Command not recognized!");
break;
}
} while(running);
command.close();
}
If you want to use a switch, easiest way would probably be a simple infinite while-loop with a label. When the input matches "exit", we just break the loop.
loop:
while (true) {
String text = command.nextLine();
switch (text) {
// ...
case "exit":
break loop;
}
}
while loop is missing in the initial example:
public static void main(String args[]) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String command = br.readLine().toLowerCase();
switch (command) {
case "exit": {
// exit here
} break;
default: {
// unrecognised command
}
}
}
}

Java How can I break a while loop under a switch statement?

I have a homework to implement a simple testing application, below is my current code:
import java.util.*;
public class Test{
private static int typing;
public static void main(String argv[]){
Scanner sc = new Scanner(System.in);
System.out.println("Testing starts");
while(sc.hasNextInt()){
typing = sc.nextInt();
switch(typing){
case 0:
break; //Here I want to break the while loop
case 1:
System.out.println("You choosed 1");
break;
case 2:
System.out.println("You choosed 2");
break;
default:
System.out.println("No such choice");
}
}
System.out.println("Test is done");
}
}
What I want to do now is that when 0 is pressed, it means that the user wants to quit the test, then I break the while loop and print Test is done, but it doesn't work like that, I know the reason might be that the "break" breaks the switch, how can I let it break the while loop instead?
You can label your while loop, and break the labeled loop, which should be like this:
loop: while(sc.hasNextInt()){
typing = sc.nextInt();
switch(typing){
case 0:
break loop;
case 1:
System.out.println("You choosed 1");
break;
case 2:
System.out.println("You choosed 2");
break;
default:
System.out.println("No such choice");
}
}
And the label can be any word you want, for example "loop1".
You need a boolean variable e.g. shouldBreak.
boolean shouldBreak = false;
switch(typing){
case 0:
shouldBreak = true;
break; //Here I want to break the while loop
case 1:
System.out.println("You choosed 1");
break;
case 2:
System.out.println("You choosed 2");
break;
default:
System.out.println("No such choice");
}
if (shouldBreak) break;
Put the while inside a function and when you press 0 instead of break just return. For example :
import java.util.*;
public class Test{
private static int typing;
public static void main(String argv[]){
Scanner sc = new Scanner(System.in);
func(sc);
System.out.println("Test is done");
}
}
public static void func(Scanner sc) {
System.out.println("Testing starts");
while(sc.hasNextInt()){
typing = sc.nextInt();
switch(typing){
case 0:
return; //Here I want to break the while loop
case 1:
System.out.println("You choosed 1");
break;
case 2:
System.out.println("You choosed 2");
break;
default:
System.out.println("No such choice");
}
}
}
}
How to terminate inner menu ?
Example Code :
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner input = new Scanner(System.in); //used to get input
int option1, option2 = 0;
boolean loop_terminate = true; //flag used to terminate inner while loop
//Main Menu
while (true) {
//Main Menu options
System.out.println("1.Option 1");
System.out.println("2.Option 2");
System.out.println("3.Option 3");
System.out.println("4.Option 4");
System.out.println("5.Exit main menu");
System.out.print("Please enter your choice : ");
option1 = input.nextInt();
switch (option1) {
case 1:
//do something here
break;
case 2:
//do something here
break;
case 3:
while (loop_terminate) {
//Inner menu options
System.out.println("1.Inner Menu option 1");
System.out.println("2.Inner Menu option 2");
System.out.println("3.Inner Menu option 3");
System.out.println("4.Return to Main Menu");
System.out.print("Please enter your choice : ");
option2 = input.nextInt();
switch (option2) {
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
loop_terminate = false; //this will terminate inner menu
break;
default:
System.out.println("Invalid option");
break;
}
}
break; //never forget to add this break statement
case 4:
break;
case 5:
return; //terminate outer menu
default:
System.out.println("Invalid option");
}
}
}
}

Categories