need help making a looping user input program - java

I'm making a looping user input program and my problem is that it cannot loop, it always end after displaying the statement "Again?" without asking for an user input again.
Here's the code:
public static void main(String[] args){
String yes;
do{
Scanner scan = new Scanner (System.in);
System.out.print("Enter a number from 1 to 10: ");
int num = scan.nextInt();
switch(num){
case 1:
System.out.print("One");
break;
case 2:
System.out.print("Two");
break;
case 3:
System.out.print("Three");
break;
case 4:
System.out.print("Four");
break;
case 5:
System.out.print("Five");
break;
case 6:
System.out.print("Six");
break;
case 7:
System.out.print("Seven");
break;
case 8:
System.out.print("Eight");
break;
case 9:
System.out.print("Nine");
break;
case 10:
System.out.print("Ten");
break;
default:
System.out.print ("Invalid Number!");
break;
}
System.out.print("\nAgain? y/n");
yes = scan.nextLine();
}while(yes.equals('y'));
}
}

try to use scanner.next() instead of nextLine.
And at the loop. You defined 'y'. The single quotes there means that this is a char and not a string. For that reason the loop condition is never 'true'.
See the equal of String
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String aString = (String)anObject;
if (coder() == aString.coder()) {
return isLatin1() ? StringLatin1.equals(value, aString.value)
: StringUTF16.equals(value, aString.value);
}
}
return false;
}
The given value is not instance of String => false
PS: You should also try not to define the scanner on every loop cycle ;)

Related

Entering character for switch statement selection

This question is regarding switch statement. These are a few similar posts on this (below) but I am still having trouble understanding.
Using user-inputted characters in If/Switch statements
How do I used a char as the case in a switch-case?
Multiple characters in a switch statement?
Please consider the following:
public class main
{
public int selection;
public main()
{
System.out.println("MENU");
Scanner in = new Scanner(System.in);
do {
showMenu();
selection = in.nextInt();
switch (selection)
{
case 1:
doSomething();
break;
case 2:
case 3:
default:
System.out.println("Instruction is invalid");
}
}
while (selection !=7);
{ System.exit(0); }
}
public static void showMenu()
{
System.out.print('\u000c');
System.out.println("option 1 \n");
System.out.println("option 2 \n");
System.out.println("7 - exit.\n");
System.out.println("Select Option:\n");
}
}
So this is a switch statement is for the user to choose options within the do while loop. The user enters an integer from the printed list to choose an option, after completion of the case, it loops back to menu.
My teacher informs me that its better practice to use char instead of int to get user input for the switch. I expect it to look something like this, but it doesn't work and I'm not sure why.
public class main
{
public int selection;
public main()
{
System.out.println("MENU");
Scanner in = new Scanner(System.in);
do {
showMenu();
String menu = "";
char selection = menu.charAt();
switch (selection)
{
case 'A':
doSomething();
break;
case 2, 3, 4, 5, 6
default:
System.out.println("Instruction is invalid");
}
}
while (selection != 'QQ');
{ System.exit(0); }
}
In the second link posted there was an answer which i think suggested using
hello.charAt(0)
as the switch condition?
switch (hello.charAt(0))
{
case 'a': ... break;
}
I have three specific questions on this code:
1) My code doesn't work. Should my condition be hello.charAt(0) ?
2) I would like to use QQ as the quit option on the switch. Is possible with the code above? From the second link, I think it should be fine.
3) It is also shown here (switch statement using char in the case condition?) that the case statement should have double quotations. Could someone please clarify this as well?
Something like this should work better:
do {
showMenu();
String menu = in.nextLine(); // read a line of input
char selection;
if (menu.length>0) selection = menu.charAt(0); // extract the first char of the line read
else selection = '\0'; // special char when input is empty...
switch (selection) {
case 'A': case 'a':
doSomething();
break;
case 'Q': case 'q':
break;
default:
System.out.println("Instruction is invalid");
}
} while (selection != 'Q' && selection != 'q');
menu stores the full input line. selection would be the first char (if it exists) of the line.
To use .charAt() you need to supply the index - so if you want to use the first character then use 0, etc.
In general one read an entire line instead of a single keystroke:
The first char of a String is gotten by charAt(0). However the string
could have length 0. There is the if-expression CONDITION ? TRUEVALUE : FALSEVALUE.
String menu = in.readLine();
char selection = menu.isEmpty() ? ' ' : menu.charAt(0);
switch (selection) {
case 'A':
doSomething();
break;
case '2':
case '3':
case '4':
...
break;
default:
System.out.println("Instruction is invalid");
}
There is an even more succint solution:
String menuSelection = in.readLine();
switch (menuSelection) {
case "A":
doSomething();
break;
case "2":
case "3":
case "4":
...
break;
default:
System.out.println("Instruction is invalid");
}

Want to create a condition that checks were the input is a integer ranging from 1 to 5

I Want to create a condition that checks were the input is a integer ranging from 1 to 5.
but it keeps saying input matching exception, can you guys help?
public static void main(String[] args) throws Exception {
//scanner for input
Scanner scan = new Scanner(System.in);
int choice = scan.nextInt();
System.out.println(">> You have selected ["+choice+"]");
//loops until input is an integer ranging from 1 to 5
while(!scan.hasNextInt() && choice>0 && choice<6){
switch (choice) {
case 1:
databaseInsertRecord();
break;
case 2:
databaseSelectAll();
break;
case 3:
databaseSearchRecord();
break;
case 4:
databaseUpdateRecord();
break;
case 5:
databaseDeleteRecord();
break;
default:
System.out.println(">> You put wrong input");
break;
}
}
}
Try this:
public static void main(String[] args) throws Exception {
//scanner for input
Scanner scan = new Scanner(System.in);
//input variable
String in;
//loops until input is an integer ranging from 1 to 5
while (scan.hasNextLine()) { //checks if there is a new line of input
in = scan.nextLine().trim(); //scans that line
if (!in.matches("^[1-5]$")) { //tests if input is a single positive digit 1-5
System.out.println(">> You put wrong input");
continue;
}
int choice = Integer.parseInt(in);
System.out.println(">> You have selected ["+choice+"]");
switch (choice) {
case 1:
databaseInsertRecord();
break;
case 2:
databaseSelectAll();
break;
case 3:
databaseSearchRecord();
break;
case 4:
databaseUpdateRecord();
break;
case 5:
databaseDeleteRecord();
break;
}
}
}
}
I have slightly altered your code to not only keep persisting the user for a valid input, but also correctly parse that input to avoid any errors. I also removed the default part of the switch block, only because the input validation prior eliminates the need for it.
I have not tested this code, but it should work properly :)
You are currently not updating the choice variable for each iteration, but rather only using the initial value. Furthermore, you're iterating until scan DOES NOT have an int, i.e. !scan.hasNextInt() and I guess you're intention is actually the opposite.
public static void main(String[] args) throws Exception {
//scanner for input
Scanner scan = new Scanner(System.in);
int choice;
//loops until input is an integer ranging from 1 to 5
while(scan.hasNextInt() && (choice = scan.nextInt()) > 0 && choice < 6){
switch (choice) {
case 1:
databaseInsertRecord();
break;
case 2:
databaseSelectAll();
break;
case 3:
databaseSearchRecord();
break;
case 4:
databaseUpdateRecord();
break;
case 5:
databaseDeleteRecord();
break;
default:
System.out.println(">> You put wrong input");
}
}
}
Hope it helps!

Checking if a String is a number using switch

I have to make a program which tells if a String that I type in my keyboard is a number, by using a switch. I know how to do it with try and catch, but I don't know how to do it with switch.
Any tips?
You would need to check each characer in the String. Something like this would probably work.
static boolean isNumber(String s) {
if (s == null) {
// Debatable.
return false;
}
int decimalCount = 0;
for (int i = 0; i < s.length(); i++) {
switch (s.charAt(i)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
// These are all allowed.
break;
case '.':
if (i == 0 || decimalCount > 0) {
// Only allow one decimal in the number and not at the start.
return false;
}
decimalCount += 1;
break;
default:
// Everything else not allowed.
return false;
}
}
return true;
}
Up to Java7 you can use switch(String) statement.
But here you have enough with switch(int) and a little workaround:
public static void main(String[] args) throws Exception {
String a = "2";
switch (Integer.parseInt(a)) {
default:
System.out.print("is a number");
break;
}
}
This is the solution I got asking to some classmates and thinking it quietly.
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner entry = new Scanner(System.in);
String myNumber;
int tf;
myNumber = entry.next();
try {
Double.parseDouble(myNumber);
tf = 1;
}
catch (Exception e) {
tf = 0;
}
switch(tf) {
case 1:
System.out.println("Is a number");
break;
default:
System.out.println("No es un nĂºmero");
break;
}
}
Thanks to the community for being so nice!
I came up with a shorter code BUT it uses regular expressions, which if Halo is just starting with Java, he may have not seen that topic yet. But then it answers the question too so here it is:
Scanner scanner = new Scanner(System.in);
String expression = scanner.nextLine();
String matches = new Boolean(expression.matches("\\d+")).toString();
switch (matches) {
case "true":
System.out.println("IT'S a number");
break;
case "false":
System.out.println("NOT a number");
}
scanner.close();

.hasNextInt() in switch statement

I'm basically trying to validate so that you can only enter an Integer. This is what I have at the moment, but if I type letters it goes through the switch and just leaves the result as blank.
I want it so that if anything other than an integer is entered it will go to default in the switch.
Any help would be great. Thanks!
while(loop && kb.hasNextInt())
{
choice = kb.nextInt();
switch(choice)
{
case 1 :
language = "FRENCH";
loop = false;
break;
case 2 :
language = "GERMAN";
loop = false;
break;
case 3 :
language = "SPANISH";
loop = false;
break;
default :
System.out.println("That is not a correct choice. Please try again!");
break;
}
}
If the next input is not an integer,
then .hasNextInt() will return false,
and therefore the loop will terminate early.
If you want to allow text input and respond to it,
then you need to read line by line, text instead of numbers,
and parse the line read with Integer.parseInt.
If the line cannot be parsed, you will get a NumberFormatException.
You can catch it, and handle appropriately.
while (loop && scanner.hasNextLine()) {
String line = scanner.nextLine();
try {
choice = Integer.parseInt(line);
} catch (NumberFormatException e) {
System.out.println("That is not an integer. Please try again!");
continue;
}
switch (choice) {
case 1:
language = "FRENCH";
loop = false;
break;
case 2:
language = "GERMAN";
loop = false;
break;
case 3:
language = "SPANISH";
loop = false;
break;
default:
System.out.println("That is not a correct choice. Please try again!");
break;
}
}
This is because a letter will cause your while(loop && kb.hasNextInt()) to be false. I suggest put an if statement with the hasNextInt() within the while loop.
Example (using a while loop instead of if statement to really try getting the number):
while(loop)
{
// validate int using while loop
while(!kb.hasNextInt())
{
System.out.println("you must enter a number! ");
kb.next();
}
choice = kb.nextInt();
switch(choice)
{
case 1 :
language = "FRENCH";
loop = false;
break;
case 2 :
language = "GERMAN";
loop = false;
break;
case 3 :
language = "SPANISH";
loop = false;
break;
}
}
System.out.println("Thank You " + studentID + " you have been registered for " + language);
This code will blow before it even begins if the user did not enter a number as the while required kb.hasNextInt() to be true (have a number) to even run.
What I do is that I usually put the validation around where I receive the input:
int choice;
Boolean retry = null;
while(retry == null) {
try{
String input = scanner.nextLine();
choice = Integer.parseInt(input);
retry = false;
}catch(NumberFormatException e){
System.out.println("Please enter a number from 1 to 4.");
}
}
switch(choice){
case 1:
// Do stuff
break;
case 2:
// Do stuff
break;
case 3:
// Do stuff
break;
case 4:
// Do stuff
break;
default:
System.out.println("Something went wrong!");
}

Switch statement + user input

Thanks for taking your time to help me. I need this switch statement to only accept ints 1-4. Any others entered will ask for input again. Entering 5 will quit the system.
System.out.println("A random numbers list has been generated for you:\n ");
System.out.println("Choose an option:\n1)Form list to be heapified.\n2)Enqueue the integer 10" +
"\n3)Dequeue the integer 10.\n4)Print the updated heap.\n5)Quit the system \n>>");
Scanner scanner = new Scanner( System.in );
int var = 0;
String input = scanner.next();
int answer = Integer.parseInt(input);
do{
input = scanner.next();
answer = Integer.parseInt(input);
var = answer;
switch(var){
case 1:
for (int i = 0; i < 20; i++) {
h.insert(new Integer((int)(100 * Math.random())), i);
}
break;
case 2:
System.out.println("\nEnqueue-ing 10...\n");
pushFoward(10, 20);//priority 20
break;
case 3:
System.out.println("\nDequeue-ing 10...\n");
dequeue;//priority highest deleted
break;
case 4:
while (h.heapsize() > 0) {
System.out.print(h.pop() + " ");
}
break;
}
}while(var ==1 || var==2 || var==3
|| var==4);
I cant seem to get it right. Keep making it worse.
Edited:
do{
String input = scanner.next();
int answer = Integer.parseInt(input);
switch(var){
case 1:
for (int i = 0; i < 20; i++) {
h.insert(new Integer((int)(100 * Math.random())), i);
}
break;
case 2:
System.out.println("\nEnqueue-ing 10...\n");
h.pushFoward(10, 20);//priority 20
break;
case 3:
System.out.println("\nDequeue-ing 10...\n");
h.dequeue();//priority highest deleted
break;
case 4:
while (h.heapsize() > 0) {
System.out.print(h.pop() + " ");
}
break;
default: input = scanner.next();
break;
}
}while(var!=5)
;
Try adding a "default:" statement, like this:
switch(var){
case 1:
for (int i = 0; i < 20; i++) {
h.insert(new Integer((int)(100 * Math.random())), i);
}
break;
case 2:
System.out.println("\nEnqueue-ing 10...\n");
pushFoward(10, 20);//priority 20
break;
case 3:
System.out.println("\nDequeue-ing 10...\n");
dequeue;//priority highest deleted
break;
case 4:
while (h.heapsize() > 0) {
System.out.print(h.pop() + " ");
}
break;
default:
*Add whatever code you want to execute if its greater then or equal to 5 here!*
}while(var ==1 || var==2 || var==3
|| var==4);
You can set a 'default' case.
default: doSomething();
break;
This will be invoked when a user enters a value that isn't one of your cases.
} while (answer != 5);
This should make the loop break when 5 is entered.
EDIT:
Also, you need to switch on the answer variable instead of 'var'
switch(answer) {
You don't need to put it in a loop. The use case is simple:
For 1-4 : do something and then return
For 5: quit/return Everything
else: ask for input again
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int answer = Integer.parseInt(scanner.next());
switch(answer) {
case 1:
System.out.println(1);
break;
case 2:
System.out.println(2);
break;
case 3:
System.out.println(3);
break;
case 4:
System.out.println(4);
break;
case 5:
return; // System.exit(0) or quit however you want to
default:
answer = Integer.parseInt(scanner.next());
}
}

Categories

Resources