I have following code:
String inputString;
Scanner in = new Scanner(System.in);
while (true) {
System.out.print("jcp>");
inputString = in.nextLine();
String[] tokens = inputString.split(" ");
switch (tokens[0]) {
case "new":
createNewInstance(tokens);
break;
case "call":
callMethod(tokens);
break;
case "print":
Object obj = hashMap.get(tokens[1]);
print(obj);
break;
default:
System.out.println("Illegal command!");
break;
}
}
I simply want the program to break out of while loop when user hits ctrl+Z
nextLine() will throw NoSuchElementException when the stream has reached its end. Or you can use in.hasNextLine().
Ctrl+Z to exit the program would be bad, Ctrl+C|Ctrl+D already ends the program execution on terminal, so it would be good the same way you expect users to type in commands, tell them to type exit as the command to EXIT your program and shortcuts like x or e can be used instead of complete word.
How about following code,
String inputString;
Scanner in = new Scanner(System.in);
while (true) {
System.out.print("jcp>");
inputString = in.nextLine();
String[] tokens = inputString.split(" ");
switch (tokens[0]) {
case "n":
case "new":
createNewInstance(tokens);
break;
case "c":
case "call":
callMethod(tokens);
break;
case "p":
case "print":
Object obj = hashMap.get(tokens[1]);
print(obj);
break;
case "e":
case "x":
case "exit":
return;
default:
System.out.println("Illegal command!");
break;
}
}
If return; won't work you can replace that with System.exit(0);
Related
I am trying to write a program that receives the number of sides from the
user and determines the type of figure using switch structure and a while sentinel-controlled loop, but every time I get an infinite loop. How can that be fixed?
import java.util.Scanner;
public class P1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number of sides:");
int s = input.nextInt();
while ( s!=-1)
{
switch (s)
{
case 1: System.out.println("Line");
break;
case 2:System.out.println("Angle");
break;
case 3:System.out.println("Triangle");
break;
case 4:System.out.println("Quadrilateral");
break;
case 5:System.out.println("Pentagon ");
break;
case 6:System.out.println("Hexagon");
break;
case 7:System.out.println("Heptagon");
break;
case 8:System.out.println("Octagon");
break;
case 9:System.out.println("Nonagon");
break;
case 10:System.out.println("Decagon");
break;
default: System.out.println("Enter a valid value:");
}
}
}
}
The while loop is written to continue as long as s!=-1; so you need to change s so that this expression is no longer true.
I run the program and it reaches while loop with input set on "" before the loop. When it enters the while loop it prints "Wrong input!" and then it asks to type in input = sc.nextLine(). Why? It hasn't even entered the switch-case statement.
Thank you in advance.
Scanner sc = new Scanner(System.in);
int size;
size = sc.nextInt();
String[] mem = new String[size];
int[] mem_index = new int[size];
String input = "";
while(!input.equals("quit")) {
input = sc.nextLine();
switch(input) {
case "Z": mem = memAlloc(mem, allocRequest);
memPrint(mem, mem_index);
allocRequest++;
break;
case "O": System.out.print("Type memory data id: ");
delRequest = sc.nextInt();
mem = memDel(mem, mem_index, delRequest);
memPrint(mem, mem_index);
break;
case "F": mem = memFrag(mem, mem_index);
memPrint(mem, mem_index);
break;
case "quit": break;
default: System.out.println("Wrong input!");
break;
}
}
You probably have something else in your scanner. Try adding this line:
sc.next();
before you go into the while loop or right in the beginning of your loop.
I know about the return statement and have tried it. System.exit(0) also does the same. But using it here terminates the program. Is there any way i can use so that if the user types other input except 1-7 , the program doesn't terminate , so that i don't have to recompile and rerun the program ? Or is it not possible in Java ?
import java.util.Scanner;
public class NewShoppingCart{
public static void main(String args[]) {
boolean flag = true;
long code;
String choice;
NewShop aShop = new NewShop();
Scanner sc = new Scanner(System.in);
Integer parse = 0;
System.out.println("-----ITEM------");
do {
System.out.println("1. Display all items");
System.out.println("2. Search items");
System.out.println("3. Add items to list");
System.out.println("4. Add items to cart");
System.out.println("5. Display cart");
System.out.println("6. Issue item");
System.out.println("7. Exit");
System.out.println("Choice:");
choice = sc.nextLine();
try{
parse = Integer.parseInt(choice);
}
catch(Exception e){
System.out.println("Please enter a valid integer");
return;
}
if (parse >=1 && parse <= 7 )
{
switch (parse) {
case 1:
aShop.display();
break;
case 2:
aShop.searchItem();
break;
case 3:
aShop.addItem();
break;
case 4:
aShop.addItemtoCart();
break;
case 5:
aShop.displayCart();
break;
case 6:
aShop.issueItem();
break;
case 7:
System.out.println("Thank you!\n");
flag = false;
break;
default :
System.out.println("Please enter choice relevant to context");
}
}
else return;
}
while (flag != false);
sc.close();
}
}
Change this
catch(Exception e){
System.out.println("Please enter a valid integer");
return;
}
to
catch(Exception e){
System.out.println("Please enter a valid integer");
continue;
}
also in your else block have continue instead of return.
You can never go out of main with just one thread. This is likely an XY problem. What you really want is to go back to the start of the loop if the user inputs something invalid.
The continue keyword will stop executing the current iteration of the enclosing loop and start a new iteration immediately. This is what you should use in place of return.
try{
parse = Integer.parseInt(choice);
}
catch(Exception e){
System.out.println("Please enter a valid integer");
return; // <--- change this to "continue;"
}
Also, this:
if (parse >=1 && parse <= 7 )
{
switch (parse) {
case 1:
aShop.display();
break;
case 2:
aShop.searchItem();
break;
case 3:
aShop.addItem();
break;
case 4:
aShop.addItemtoCart();
break;
case 5:
aShop.displayCart();
break;
case 6:
aShop.issueItem();
break;
case 7:
System.out.println("Thank you!\n");
flag = false;
break;
default :
System.out.println("Please enter choice relevant to context");
}
}
else return;
should really be:
if (parse >=1 && parse <= 7 )
{
switch (parse) {
case 1:
aShop.display();
break;
case 2:
aShop.searchItem();
break;
case 3:
aShop.addItem();
break;
case 4:
aShop.addItemtoCart();
break;
case 5:
aShop.displayCart();
break;
case 6:
aShop.issueItem();
break;
case 7:
System.out.println("Thank you!\n");
flag = false;
break;
}
}
else {
System.out.println("Please enter choice relevant to context");
continue;
}
The "Please enter choice relevant to context" message should really be printed in the else statement. Because in your if, you already checked whether parse is between 1 and 7, so in the switch, parse can't be anything else so the default branch is never reached. After you print the message, you continue; in order to go back to the start of the 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
}
}
}
}
New to Java and I'm having troubles with my code, it's a switch statement within a while loop. I like to use letters or "char" instead of numbered cases "int" and I have 'q' to quit. Thanks for your input. This is the main code.
import java.util.Scanner;
import java.util.*;
public class supraCritters {
public static void main(String [] arguments) {
Critter nastybat = new Critter();
nastybat.health = 100;
nastybat.mood = 50;
nastybat.hunger = 25;
System.out.println("Your critter has just been born,");
System.out.println("here are the stats of your critter.");
nastybat.checkStats();
System.out.println("\nPlease choose a letter");
System.out.println("[c]heck stats \n[f]eed \n[p]lay \n[r]ead \n[t]rain");
System.out.println("[q]uit");
Scanner sChoice = new Scanner(System.in);
char choice = ' ';
while (choice != 'q') {
switch (choice) {
case 'c':
nastybat.checkStats();
break;
case 'f':
nastybat.feed();
break;
case 'p':
nastybat.play();
break;
case 'r':
nastybat.read();
break;
case 't':
nastybat.train();
break;
case 'q':
System.out.println("good bye");
break;
default:
System.out.println("invalid entry");
break;
}
choice = sChoice.next().charAt(0);
}
}
}
When I enter corresponding letter the loop doesn't show Input method or repeat and 'q' does nothing. Default displays "invalid entry" before input.
Code edited and still have problems.
The input is taken only once, the first time! Therefore the loop always returns the same result. You should duplicate the getting input code inside the loop!
Scanner sChoice = new Scanner(System.in);
char choice = '';
while (choice != 'q') {
switch (choice) {
case 'c':
nastybat.checkStats();
break;
.
.
.
.
.
choice = sChoice.next().charAt(0);
The first line gets input for the first switch run, and the one inside the loop gets the rest.
UPDATE:
The choice = sChoice.next().charAt(0); should be place at the final of the loop, if not, as #proskor says, when user hits 'q' the program will return an 'invalid entry'.
I finished the code and it seems to work. Testing out the methods the object can use now.
Final
import java.util.Scanner;
import java.util.*;
public class supraCritters {
public static void main(String [] arguments) {
Critter nastybat = new Critter();
nastybat.health = 100;
nastybat.mood = 50;
nastybat.hunger = 25;
System.out.println("Your critter has just been born,");
System.out.println("here are the stats of your critter.");
nastybat.checkStats();
Scanner sChoice = new Scanner(System.in);
char choice = ' ';
while (choice != 'q') {
switch (choice) {
case 'c': case 'C':
nastybat.checkStats();
break;
case 'f': case 'F':
nastybat.feed();
break;
case 'p': case 'P':
nastybat.play();
break;
case 'r': case 'R':
nastybat.read();
break;
case 't': case 'T':
nastybat.train();
break;
case 'q': case 'Q':
System.out.println("good bye");
break;
default:
System.out.println("invalid entry");
break;
}
System.out.println("\nPlease choose a letter");
System.out.println("[c]heck stats \n[f]eed \n[p]lay \n[r]ead \n[t]rain");
System.out.println("[q]uit");
choice = sChoice.next().charAt(0);
}
}
}