How do I switch the order of the outcome? I would liked to be asked to enter output after the menu.
Welcome to the Library! Please make a selection from the menu:
1. View.
2. Show.
Enter a choice: 1
However, I am made to enter input first, and I see:
Enter a choice: 1
Welcome to the Library! Please make a selection from the menu:
1. View.
2. Show.
This is my code:
import java.util.*;
public class Store {
public static void main(String[] args) {
new Store().use();
}
public void use() {
char choice;
while ((choice = readChoice()) != 'X') {
switch (choice) {
case 1: view(); break;
case 2: show(); break;
default: help(); break;
}
}
}
private char readChoice() {
return In.nextChar();
}
private String view() {
return "";
}
private String show() {
return "";
}
}
private void help() {
System.out.println("Welcome! Please make a selection from the menu:");
System.out.println("1. View.");
System.out.println("2. Show."); }
Just add help() on top of the use() method:
public void use() {
help();
char choice;
while ((choice = readChoice()) != 'X') {
switch (choice) {
case 1: view(); break;
case 2: show(); break;
default: help(); break;
}
}
}
You also need to change 1 and 2 into '1' and '2' respectively, because you are switching over a char. The fact that this compiles is because the compiler applies a narrowing primitive conversion to convert int to char.
I think there are three reasons that the code does not do what you expect.
You are made to enter input first, because before printing anything on the console, the readChoice() function is called. Which waits until it reads one character from the console and then returns. So you must call Help() function once before the while loop.
I guess the switch-case will not do what you expect. I mean the view() and show() functions are not called when you enter 1 or 2. The reason is that you read 1 and 2 as characters not integers. So the switch-case should change to this:
switch (choice) {
case '1': view(); break; //1 changed to '1'
case '2': show(); break; //2 changed to '2'
default: help(); break;
}
I think you might have forgotten to print "Enter a choice:" before reading the character. (I used System.out.print() rather than System.out.println() because it seems that "Enter a choice:" and the choice entered should be in the same line)
private char readChoice() {
System.out.print("Enter a choice:");
return In.nextChar();
}
this is the entire code, hope it works correctly (I put comments so you see what changes I made):
import java.util.*;
public class Store {
public static void main(String[] args) {
new Store().use();
}
public void use() {
char choice;
help();//called help() once before the loop
while ((choice = readChoice()) != 'X') {
switch (choice) { //cases changed
case '1': view(); break;
case '2': show(); break;
default: help(); break;
}
}
}
private char readChoice() {
//printing "Enter a choice:"
System.out.print("Enter a choice: ");
//I used Scanner class to read the next char, because I don't have 'In' class to use.
//you might write "return In.nextChar();" insead of the following lines
Scanner reader = new Scanner(System.in);
char c = reader.next().charAt(0);
return c;
}
private String view() {
System.out.println("you selected view"); //to see this function is called
return "";
}
private String show() {
System.out.println("you selected show"); //to see this function is called
return "";
}
private void help() {
System.out.println("Welcome! Please make a selection from the menu:");
System.out.println("1. View.");
System.out.println("2. Show.");
}
};
Related
I'm a new to Java.
I'm currently doing a side project; making a text based game. and I realized that using Switch-statement would be very useful for this type of game.
So it is basically how it works.
I ask User, what would you like to do?
Eat
Walk
etc.
So, what would be the best way to build a switch-statement and Scanner together along with "default statement that asks User again"?
I've been doing this way(my code down here), but it seems it has so many potential problems.
Could you guys give me some hints on how to make a best switch-statement with Scanner?
Thank you very much in advance.
public static void ask() {
Scanner sc = new Scanner(System.in);
System.out.println("What do you want to do?");
while (!sc.hasNextInt()) {
sc.next();
}
select = sc.nextInt();
switch (select) {
case 1:
eat();
break;
case 2:
walk();
break;
case 3:
sleep();
break;
default:
System.out.println("choose from 1 to 3");
ask(); //would you re call itself again here? or is there any otherway to do without recalling itself?
}
Your code seems ok but I would refactor it. Also add while loop to ask again:
public static void ask() {
Scanner sc = new Scanner(System.in);
boolean isWrongAnswer;
do {
isWrongAnswer = false;
System.out.println("What do you want to do?");
switch (sc.nextInt()) {
case 1:
eat();
break;
case 2:
walk();
break;
case 3:
sleep();
break;
default:
System.out.println("choose from 1 to 3");
isWrongAnswer = true;
}
} while (isWrongAnswer);
}
It is good to check first that scanner has something or not then check for whether it is int value. To do that can use sc.hasNext() & sc.hasNextInt() like below,
public static void ask() {
Scanner sc = new Scanner(System.in);
System.out.println("What do you want to do?");
while (sc.hasNext()) {
int select = 0;
if (sc.hasNextInt()) {
select = sc.nextInt();
}
switch (select) {
case 1:
System.out.println("call eat()");
break;
case 2:
System.out.println("call walk()");
break;
case 3:
System.out.println("call sleep()");
break;
default:
System.out.println("choose from 1 to 3");
ask();
}
}
I advise you to use String in this case. To improve the readability of the code, and to avoid errors.(http://www.oracle.com/technetwork/java/codeconventions-150003.pdf)
private static final String EAT = "1";
private static final String WALK = "2";
private static final String SLEEP = "3";
public void ask() {
Scanner sc = new Scanner(System.in);
System.out.println("What do you want to do?");
switch (sc.next()) {
case EAT:
eat();
break;
case WALK:
walk();
break;
case SLEEP:
sleep();
break;
default:
System.out.println("choose from 1 to 3");
ask(); // as described above via "do while", but there is nothing wrong with recursion. The garbage collector works.
}
}
I doing a little practice on Computer Science because when I leave the military I want to start taking classes on the basics of java. I'm a little stuck on this question i was wondering if i can get some assistance.
a program that allows the user to enter a character. The only valid values are 'A', 'M', and 'S'. Validate the input using a while loop so that if the user enters any value other than one of those 3 characters, an error message is displayed and the user is prompted for another value. Once the user has finally entered valid data, print the character they entered back to the screen.
You can look into this basic example
import java.util.Scanner;
public class Read {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
boolean isCheck = true;
while (isCheck) {
String str = sc.next();
switch (str) {
case "A":
System.out.println("A");
isCheck = false;
break;
case "M":
System.out.println("M");
isCheck = false;
break;
case "S":
System.out.println("S");
isCheck = false;
break;
default:
System.out.println("Not Valid : Enter next");
isCheck = true;
}
}
}
}
Reading you input within the loop will enforce repetitive reading of input.
public class Read {
public static void main(String[] args) {
boolean isCheck = true;
while(isCheck){
Scanner sc = new Scanner(System.in);
String str = sc.next();
switch (str) {
case "A":
System.out.println("A");
isCheck = false;
break;
case "M":
System.out.println("M");
isCheck = false;
break;
case "S":
System.out.println("S");
isCheck = false;
break;
default:
System.out.println("Not Valid : Enter next.");
isCheck = true;
}
}
}
}
I'm just learning Java and trying to make a simple phone book. For this part I'm trying to prompt the user to choose one of the 3 options below.
public class PhoneBook {
public static void main (String[] args){
options();
/*This method prompts the user to enter phone number
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter Phone Number");
s = in.nextLine();
System.out.println("You entered phone number ");
System.out.println(s);*/
}
public static void options (){
//This method gives the user choices on what to do
char choice;
char enterNumber = 'n';
char showNumber = 's';
char closeBook = 'c';
String read;
String freeLine = "error";
Scanner keyboard = new Scanner(System.in);
while (true){
System.out.println("Please select from the following");
System.out.println("n to Enter the number");
System.out.println("s to Show the number ");
System.out.println("c to Close the Phone book");
read = keyboard.nextLine();
choice = read.charAt(0);
switch (choice) {
case 'n': enterNumber;
system.out.println();
case 's':showNumber;
system.out.println();
case 'c': closeBook;
break;
default: System.out.println("Invalid Entry");
}
}
}
}
When I compile it i get errors on lines 37, 39, and 41 saying "Error: not a statement". I feel like something is missing. If anyone can help it would be greatly appreciated.
I am assuming that with the following lines you want to achieve to print the letter n for enterNumber in the console?
case 'n': enterNumber;
system.out.println();
This is not correct Java syntax. You will have to pass the variable value to the System.out.println method call:
case 'n': System.out.println(enterNumber);
Also note that Java is case sensitive, so you have to spell System with a capital letter.
On a side note, you will want to break; after each of your case statements, otherwise the code of the following cases will be executed as well:
switch (choice) {
case 'n': System.out.println(enterNumber);
break;
case 's': System.out.println(showNumber);
break;
case 'c': System.out.println(closeBook);
break;
default: System.out.println("Invalid Entry");
}
you do not have to write variable after 'cast' statement.
Refer below code.
import java.util.Scanner;
public class PhoneBook {
public static void main (String[] args){
options();
/*This method prompts the user to enter phone number
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter Phone Number");
s = in.nextLine();
System.out.println("You entered phone number ");
System.out.println(s);*/
}
public static void options (){
//This method gives the user choices on what to do
char choice;
char enterNumber = 'n';
char showNumber = 's';
char closeBook = 'c';
String read;
String freeLine = "error";
Scanner keyboard = new Scanner(System.in);
while (true){
System.out.println("Please select from the following");
System.out.println("n to Enter the number");
System.out.println("s to Show the number ");
System.out.println("c to Close the Phone book");
read = keyboard.nextLine();
choice = read.charAt(0);
switch (choice) {
case 'n':
System.out.println();
case 's':
System.out.println();
case 'c':
break;
default: System.out.println("Invalid Entry");
}
}
}
}
I have made a special answer for you. I don't add additional explanation. It's a large answer. I tell more than you ask, but I've done my best to make a readable code, so that you can analyse step-by-step to understand what you need at least when trying to make a Phone Book (console test drive application). If you need more explanation, write under comments.
First make a PhoneEntry class:
import java.util.Objects;
public class PhoneEntry implements Comparable<PhoneEntry> {
// https://jex.im/regulex/#!embed=false&flags=&re=%5E%5Ba-zA-Z%5D%7B2%2C%7D((-%7C%5Cs)%5Ba-zA-Z%5D%7B2%2C%7D)*%24
private static final String NAME_PATTERN = "^[a-zA-Z]{2,}((\\-|\\s)[a-zA-Z]{2,})*$";
// https://jex.im/regulex/#!embed=false&flags=&re=%5E%5C%2B%3F%5Cd%2B((%5Cs%7C%5C-)%3F%5Cd%2B)%2B%24
private static final String NUMBER_PATTERN = "^\\+?\\d+((\\s|\\-)?\\d+)+$"; //^\+?\d+((\s|\-)?\d+)+$
private final String name;
private final String number;
public PhoneEntry(String name, String number) {
if (!name.matches(NAME_PATTERN) || !number.matches(NUMBER_PATTERN)) {
throw new IllegalArgumentException();
}
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
public String getNumber() {
return number;
}
public boolean nameContainsIgnoreCase(String keyword) {
return (keyword != null)
? name.toLowerCase().contains(keyword.toLowerCase())
: true;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!(obj instanceof PhoneEntry)) {
return false;
}
PhoneEntry phoneEntry = (PhoneEntry) obj;
return name.equalsIgnoreCase(phoneEntry.name)
&& number.equalsIgnoreCase(phoneEntry.number);
}
#Override
public int hashCode() {
int hash = 5;
hash = 17 * hash + Objects.hashCode(this.name.toLowerCase());
hash = 17 * hash + Objects.hashCode(this.number.toLowerCase());
return hash;
}
#Override
public int compareTo(PhoneEntry phoneEntry) {
return name.compareToIgnoreCase(phoneEntry.name);
}
}
Then the test drive
public class TestDrive {
private static final String choices = "nspc";
enum Choice {
CREATE, READ, PRINT, CLOSE;
static Choice getChoice(char c) {
switch (c) {
case 'n':
return Choice.CREATE;
case 's':
return Choice.READ;
case 'p':
return Choice.PRINT;
case 'c':
return Choice.CLOSE;
}
return null;
}
}
// Main
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
final Set<PhoneEntry> entries = new TreeSet<>();
Choice choice;
while ((choice = getChoice(kbd)) != Choice.CLOSE) {
switch (choice) {
case CREATE:
PhoneEntry entry = getPhoneEntry(kbd);
if (entry != null) {
entries.add(entry);
}
break;
case READ:
print(readEntries(entries, kbd));
break;
case PRINT:
print(entries);
break;
}
}
}
private static Choice getChoice(Scanner kbd) {
System.out.println("\nPlease select from the following");
System.out.println("\tn to Enter the number");
System.out.println("\ts to Show numbers by keyword ");
System.out.println("\tp to Show all numbers ");
System.out.println("\tc to Close the Phone book");
System.out.print("> ");
String input = kbd.nextLine();
Choice choice = null;
if (!input.isEmpty()
&& choices.contains(input.toLowerCase())
&& ((choice = Choice.getChoice(input.toLowerCase().charAt(0))) != null)) {
return choice;
}
System.out.println("ERR: INVALID ENTRY. TRY AGAIN");
return getChoice(kbd);
}
private static PhoneEntry getPhoneEntry(Scanner kbd) {
System.out.print("Type contact name: ");
String name = kbd.nextLine();
System.out.print("Type phone number: ");
String number = kbd.nextLine();
try {
return new PhoneEntry(name, number);
} catch (IllegalArgumentException ex) {
System.out.println("\nERR: WRONG ENTRY");
}
return null;
}
private static void print(Set<PhoneEntry> entries) {
System.out.println("\nPHONE NUMBERS\n");
entries.stream().forEach(entry -> {
System.out.printf("Name: %s%nPhone: %s%n%n",
entry.getName(), entry.getNumber());
});
}
private static Set<PhoneEntry> readEntries(Set<PhoneEntry> entries, Scanner kbd) {
System.out.print("Type keyword: ");
return entries.stream().filter(entry
-> entry.nameContainsIgnoreCase(kbd.nextLine()))
.collect(Collectors.toCollection(TreeSet::new));
}
}
Instead of enterNumber;, you have to write enterNumber();.
The parentheses mean: Call the method.
I have a program which plays a game of superhero top trumps and I need to repeat the menu every time a user plays the game. I've tried to create a method (displayMenus) which would be inserted into every switch statement (except for closing the program), however I don't understand how to get it to return this menu.
public class Heros {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int index = 0;
do {
int inp = input.nextInt();
switch (inp) {
//FIRST
case 1:
index = 0;
System.out.println(HerosAsList.getHeros().get(index));
System.out.println(displayMenus);
break;
//NEXT
case 2:
index++;
if (index > HerosAsList.getHeros().size() - 1) {
index = HerosAsList.getHeros().size() - 1;
}
System.out.println(HerosAsList.getHeros().get(index));
System.out.println(displayMenus);
break;
//PREV
case 3:
index--;
if (index < 0) {
index = 0;
}
System.out.println(HerosAsList.getHeros().get(index));
System.out.println(displayMenus);
break;
//LAST
case 4:
index = HerosAsList.getHeros().size() - 1;
System.out.println(HerosAsList.getHeros().get(index));
System.out.println(displayMenus);
break;
//QUIT
case 0:
System.out.println("Closing system");
System.exit(inp);
break;
}
}
while(index<HerosAsList.getHeros ().size());
}
public static displayMenus () {
System.out.println("First - 1");
System.out.println("Next - 2");
System.out.println("Prev - 3");
System.out.println("Last - 4");
System.out.println("Quit - 5");
System.out.println("");
System.out.println("Enter Choice:");
}
}
any help is greatly appreciated, I just can't seem to get my head around methods!
Firstly, the declaration of displayMenus is invalid. You need to give it a return type (even if that is void), e.g.:
public static void displayMenus () {
If you make it void, you would need to invoke displayMenus() without calling System.out.println:
displayMenus();
If you make it String, you would need to build a String in displayMenus and return it, e.g.:
public static String displayMenus() {
return "First - 1" + ...;
}
then you can invoke System.out.println(displayMenus()).
Just change displayMenus to return the menu as a String, rather than printing it:
public static String displayMenus() {
return "First - 1\nNext - 2\nPrev - 3\nLast - 4\nQuit - 5\n\nEnter Choice:\n";
}
I simplified the code down, because there were quite a few syntax errors in the code itself, but this should answer your question. Your displayMenus() function doesn't need to return a String, you can instead call this at the beginning of your do...while loop. The logic flow should be:
Initialize scanner
Create variable for choice
Enter do...while loop
Call displayMenus()
Read user choice from scanner
Do switch logic
Back to 3rd item if the loop isn't broken
I made a small class to demo this:
package zzzTestProj;
import java.util.Scanner;
public class NewClass {
public static void main(String[] args) {
Scanner userInputScanner = new Scanner(System.in);
int userMenuChoice;
do {
displayMenus();
userMenuChoice = userInputScanner.nextInt();
switch (userMenuChoice) {
// FIRST
case 1:
break;
// NEXT
case 2:
break;
case 0:
System.out.println("Closing system");
System.exit(userMenuChoice);
break;
}
} while (userMenuChoice != 5);
}
public static void displayMenus() {
System.out.println("First - 1");
System.out.println("Next - 2");
System.out.println("Prev - 3");
System.out.println("Last - 4");
System.out.println("Quit - 5");
System.out.println("");
System.out.print("Enter Choice:");
}
}
The ch variable is not recognised by the while loop although it is declared outside the loop. Why? There is no compilation error.
package calculator;
import java.util.Scanner;
public class Calculation {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int ch;
do {
System.out.print("ENTER YOUR CHOICE : ");
ch = s.nextInt();
switch (ch) {
case 1: {
}
.....
default: {
System.out.println("\n!!!ENTER VALID CHOICE !!!");
break;
}
}
} while (ch != 9);
s.close();
}
}
put your break statement of default case outside the braces. I think that is your problem. I tried the below code and gives me the output.
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
int ch;
do {
System.out.print("ENTER YOUR CHOICE : ");
ch=s.nextInt();
switch(ch)
{
case 1:
System.out.println("one");
break;
default:
System.out.println("\n!!!ENTER VALID CHOICE !!!");
break;
}
}while(ch!=9);
s.close();
}
}
This code is working fine. elements of parent block are always visible.
Don't use break in default case
Your code :
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int ch;
do {
System.out.print("ENTER YOUR CHOICE : ");
ch = s.nextInt();
switch (ch) {
case 1:
System.out.println("one");
break;
default:
System.out.println("\n!!!ENTER VALID CHOICE !!!");
}
} while (ch != 9);
s.close();
}
}
*Only the edit I made was I removed break from default block.
Running Example :
ENTER YOUR CHOICE : 1
one
ENTER YOUR CHOICE : 2
!!!ENTER VALID CHOICE !!!
ENTER YOUR CHOICE : 3
!!!ENTER VALID CHOICE !!!
ENTER YOUR CHOICE : 9
!!!ENTER VALID CHOICE !!!