(Java) use one code for multiple responses? - java

If in a code, I have two options - choosing 1 or 2 -- in '2' you go straight to another code, but with '1' you must do a few things before and then do to that code, is this possible with one code? This is an example:
Scanner scanner = new Scanner(System.in);
reader = scanner.nextInt();
if (reader == 1) {
System.out.println("Not yet, pick another one");
int number = scanner.nextInt();
}
} else if (reader == 2) {
System.out.println("Okay, you have picked 2!");
}
Is it possible to go directly from the first to the second? Provided the first one picks '2' in the second try, do I have to retype the code in that area or can I move it directly to the else if(reader == 2){....} code after this?
Thanks!

Sure, just modify you're conditions a bit:
int someVar = ...;
if(someVar == 1){
...
//do stuff before other code
}
...
//do stuff you do for 1 and 2

You can't use else-if in this scenario, since the else-if part will never be evaluated if the first condition is true. You need two separate conditions :
int reader = scanner.nextInt();
if (reader == 1){
System.out.println("Not yet, pick another one");
reader = scanner.nextInt();
}
if (reader == 2) {
System.out.println("Okay, you have picked 2!");
}
Note that you also have to read both integers into the same variable.

Related

Java loop confusion requiring assistance

So i need help, i am trying to input a Y/N program but it is not accepting a big 'Y' or 'N'. Also another thing that i am trying to do is after pressing 'Y'/'y' i am trying to get the program to loop back to the code written above. Example a program that displays '123' and do i need to continue? Y/N, if entered yes it goes back up to restart the program from scratch. Please help me.
System.out.println("continue? Yes or no ");
char check = s.next().charAt(0);
while (check != 'y' && response != 'n')// corrected this part, however need help with restarting the loop back to the first line of code in a loop {
System.out.println("\nInvalid response. Try again.");
check = s.next().charAt(0);
} if ((check == 'n') || (check == 'N')) {
// I tried (check == 'n' || check == 'N')
System.out.println("Program terminated goodbye.");
System.exit(0);
} else if (check == 'y') {
//need help with restarting the loop back to the first line of code in a loop
}
I think this is what you are looking for.
char check;
Scanner scanner = new Scanner(System.in);
do
{
//your piece of code in here e.g.
System.out.println("Printed 123");
System.out.println("Do you wish to continue?[Y/y] or [N/n]");
choice = scanner.next().charAt(0);
}while (check =='Y' || check == 'y');
System.out.println("Program terminated goodbye.");
A do-while loop runs at least once before the condition is checked and so when a user enters either Y or y, then the condition will be true, meaning that they wish for the loop to run again. If the user enters any other value, then the condition will become false since choice is neither Y nor y and the loop will terminate.
Use String.equals() to compare the value of strings, == compares the strings in memory.
If you want to check without case-sensitive, you should convert the char to a String, then do s1.equalsIgnoreCase(s2);
So
while(true) {
System.out.println("Continue? [Y/N]");
char check_char = s.next().charAt(0);
String check = Character.toString(check_char);
while(check.equalsIgnoreCase("y") && !response.equalsIgnoreCase("n")) {
System.out.println("\nInvalid response. Try again.");
check = s.next().charAt(0);
}
if (check.equalsIgnoreCase("n")) {
System.out.println("Program terminated goodbye.");
System.exit(0);
}
}
For returning to the first line, I used a while loop that loops forever.
To the end if it is n then exits, otherwise it returns back to the first line of the loop.

Try-catch around a choice menu

I've made a choice menu in a while loop. To make sure that users put in a valid choice, i put the menu itself in a try catch block:
I want the user to get a new chance if an exception was caught, so I put the try-catch block in a while(true) loop. However, using this kind of loop, the part where the actions are coded becomes unreachable code.
Is there a way to do this better?
And an extra question, How do i prevent a user from entering a choice option that does not exist?
while (choice != 0) {
/* Ask for player's choice */
while(true) {
try
{
BufferedReader menuInput = new BufferedReader(new InputStreamReader(System.in));
System.out.println();
System.out.println("Please choose between the following options:'");
System.out.println(" (1) Make new animal");
System.out.println(" (2) Feed Animals");
System.out.println(" (3) Count animals");
System.out.println(" (0) Quit");
System.out.print("Enter your choice: ");;
choice = Integer.parseInt(menuInput.readLine());
} catch (NumberFormatException ex) {
System.err.println("Not a valid number");
} catch (IOException e) {
System.out.println("Failed to get input");
}
}
// first choice option:
if (choice == 1) {
//actions
}
// second choice option:
if (choice == 2) {
//actions
}
// third choice option:
if (choice == 3) {
//actions
}
}
System.out.print("Thank you for playing!")
The very simplest way of doing it is to set a boolean flag above your loop:
boolean waitingForAnswer = true;
and then just change your while loop condition to while(waitingForAnswer) and set waitingForAnswer to false after one has been accepted.
You can then use that same structure to prevent them entering 5, or whatever. Simply tag an if on the end there that checks if the value is an accepted one, if it isn't, don't change waitingForAnswer
EDIT:
Incidentally, your string of if statements at the bottom isn't terribly efficient. If the user inputs "1" then the if (choice==1) block will trigger and it will then go on to check if it equals 2, if it equals 3, etc when we know for a fact it won't. Use else if there.
Another EDIT:
Also, create your input stream reader outside of the loop. Currently you're creating a new one each time the loop runs.

Is there a way to shorten something like this?

In this part of the code, a scanner asks the user to input a number between one and five. I will need to rewrite this for a bunch of variables, so is there any way to make it shorter?
if (Q1 != 1 || Q1 != 2 || Q1 != 3 || Q1 !=4 || Q1 != 5) {
System.out.println("Error: Please enter a number between 1 and 5.");
}
Instead of typing Q1 != 1 or 2 or 3 etc, is there a way to write 1-5 or something like that?
Try this,
if(Q1 <1 || Q1 >5) System.out.println("Error: Please enter a number between 1 and 5.")
For the general case, use a set.
Declare a class field, or a local variable:
Set<Integer> accepted = new LinkedHashSet<>(Arrays.asList(1,2,3,4,5));
Then:
if (!accepted.contains(Q1))
System.out.println("Error: Please enter a number that is one of: " + accepted);
Use LinkedHashSet so the printed version has the same order as the declaration.
The above answers are nice for this specific problem, but if you have 5 separate Strings for example, and you want to check if each of them are valid (they aren't null or empty), then you should create a method, to do that.
public boolean isValid(String... args) {
for (String s : args) {
if (s == null or s.equals("")) {
//Something is invalid
return false;
}
}
//Everything is valid
return true;
}

Taking input using bufferedreader

I want to take input in the format: -prize 45
This is my code
static double prize_input(String list[]) throws IOException{
boolean flag=false;
double p=0;
while(true){
if(list.length!=2 || ( list[0].compareTo("-prize")!=0 ) ){
System.out.println("usage: -prize <Itemprize>");
flag=true;
}
else
{
try{
p=Double.parseDouble(list[1]);
flag=false;
}
catch(Exception e){
flag=true;
}
}
if(!flag)
return p;
else
list=br.readLine().split(" ");
}
}
When I input: -prize abc where second argument is also a string it prompts me for another enter key from user instead of display the appropriate message. Please tell me what am I missing and how should I correct it.
usage: -prize <Itemprize> will be printed only if this condition will fail
if (list.length != 2 || (list[0].compareTo("-prize") != 0))
so only if
user didn't provided two elements,
and if first element is not -prize.
Since for -price aaa both conditions are fulfilled so user will not see this info, but flag representing correctness of data will be set to false while failed parsing second parameter, so in
else
list = br.readLine().split(" ");
program will be waiting for new data form
To improve user experience you should print usage info right before reading new data from user, so try moving line
System.out.println("usage: -prize <Itemprize>");
right before br.readLine()
else{
System.out.println("usage: -prize <Itemprize>");
list = br.readLine().split(" ");
}
your condition is worng as you are taking while(true) as a loop condition and also you are taking a input in which loop will go as forever and also buffer reader waits for the next line to be splited.

Java Scanner strange behavior

I have a java scanner and two loops to handle user input, However it throws an NoSuchElement exception the second it hits the first loop with out asking for any input from the user.
Scanner Guess_input = new Scanner( System.in );
while (guess > 0){
failure = true;
while(failure)
{
System.out.println("Please input");
try
{
if (Guess_input.nextLine().length() == 1 && guesses.size() >= 1) {
guesses.add(Guess_input.nextLine());
System.out.println("You guessed" + guesses.get(guesses.size()) + "");
}
else if (Guess_input.nextLine().length() == 0) {
System.err.println("ERROR:");
Guess_input.nextLine(); //Clean Buffer
failure = true;
}
else
{
System.err.println("ERROR");
Guess_input.nextLine(); //Clean Buffer
failure = true;
}
}
catch(InputMismatchException ime)
{
System.err.println("error");
}
finally
{
Guess_input.close();
}
}
}
From the java documentation, when using the next() method of the Scanner class, you'll get
NoSuchElementException - if no such tokens are available
Whenever you call the nextLine() method, you are supposed to enter a String. You should first store the result of nextLine() in local variable unless that's what you want.
Another problem is that your try catch finally is done in your while loop. It means that for each iteration, your finally bloc will be executed everytime, so you'll think that there is an exception, while might be none. Apply these changes
try {
while (guess > 0) {
while (.....) {
.....
}
}
} catch (...){
....
}
finally{ .... }
The errant statement is guesses.get(guesses.size()). In Java lists use zero-based indexes, i.e. the index of the first element is always 0 and the last element is size - 1. By definition the size of a list is an invalid index.
You probably should just hold the next line in its own variable before adding it to the list so that your sysout statement can just reference the variable instead of pulling the value back out of the list. But the easy solution is to just change the code to guesses.get(guesses.size() - 1)
You're calling guesses.nextLine() way too many times. Every call to nextLine() will block the app and expect input. Furthermore, theres other issues to worry about there... like other people pointed out.
I'll stick to the scanner though.

Categories

Resources