Do-While Qualifiers and Totalling in Java - java

I am trying my hand a few basic do-while codes, and am running into a couple of problems.
I want the code to ask the user to input 1 of 3 options (choosing which group they would like to add a number to, or to exit and total), give an error if they input an irrelevant option, and then total all ints at the end for each group.
public static void main(String[] args) {
String answer = "default";
int grp1 = 0;
int grp2 = 0;
int input1 = 0;
int input2 = 0;
do{
System.out.println("Make a selection:\n");
System.out.println("A: Enter a number for Group 1.");
System.out.println("B: Enter a number for Group 2.");
System.out.println("X: Exit and total the numbers for each group.\n");
System.out.println("Select your option: ");
answer = keyboard.next();
if (answer.equalsIgnoreCase("A")){
System.out.println("Enter int: ");
input1 = keyboard.nextInt(); // add an int to grp1
}
else if (answer.equalsIgnoreCase("B")){
System.out.println("Enter int: ");
input2 = keyboard.nextInt(); // add an int to grp2
}
else if (answer.equalsIgnoreCase("X")){
} // exit and total
else {
System.out.println("Invalid option - Try again.");
} // Invalid input - restart
}
while (answer.equals("A") || answer.equals("B"));
grp1 += input1;
grp2 += input2;
keyboard.close();
System.out.println("Group 1's total is: + grp1);
System.out.println("Group 2's total is: + grp2);
}
I need the to add a qualifier for if the user does not input a valid option, I tried using else:
else {
System.out.println("Invalid option - Try again.")
}
but this just skips to printing the totals, and does not ask the user for another input. How would I best achieve this?
Also,
grp1 += input1;
grp2 += input2;
Only counts the lasted entered int, is there a way to have it add all the entered ints?
Any help would be greatly appreciated, even outside of the questions I asked.

I think you have two confusions.
1) The "while" line in your code applies to the "do" block above it. That means that based on where the grp1 += and grp2 += lines are, they will only ever be run once. I suggest moving those calls to the end of the loop. You could move each line inside the relevant if block so that the code is run every time the user successfully enters a number after A or B.
2) The while condition is asking if the user entered "A" or "B". It's saying if they did, continue looping by going back to "do". If they entered literally anything else (any invalid answer), it will stop and run the code after the "while" line. I think what you really want is while (!answer.equals("X")), which will continue the loop until the user correctly enters an "X" character.
You'll also want to move those grp += lines up a bit.

Just change the condition inside while And also shift the totalling logic
do{
System.out.println("Make a selection:\n");
System.out.println("A: Enter a number for Group 1.");
System.out.println("B: Enter a number for Group 2.");
System.out.println("X: Exit and total the numbers for each group.\n");
System.out.println("Select your option: ");
answer = keyboard.next();
if (answer.equalsIgnoreCase("A")){
System.out.println("Enter int: ");
input1 = keyboard.nextInt(); // add an int to grp1
grp1 += input1;
}
else if (answer.equalsIgnoreCase("B")){
System.out.println("Enter int: ");
input2 = keyboard.nextInt(); // add an int to grp2
grp2 += input2;
}
else if (answer.equalsIgnoreCase("X")){
} // exit and total
else {
System.out.println("Invalid option - Try again.");
} // Invalid input - restart
}
while (!answer.equals("X"));
keyboard.close();
This will make your do while loop running i.e showing options to user until they wishes to exit. And also group total would be updated properly. I have updated answer based on answer by #Devin Howard

Related

Java - 2-Do-While Loops in a For Loop

I'm quite new to programming so excuse my basic and limited understanding. Essentially, I am creating a Memory Game for a school project. I want to do 2 do-while loops in a for loop that works like this: the user will be prompted to enter a 4 random letters which will be done in the first do-while loop and the second do-while loop will ask the user to re-input the phrase that they had initially entered.
So my first question is, why does only the first do-while execute? I'm assuming that the for loop executes the first-do-while and than repeats based on my parameters therefore the second one will never execute but, I'd appreciate any help understanding why, and reformatting my program accordingly perhaps.
My second question is that, I want to have a sort of score counter that nets the user 10 points for every correctly guessed letter in the correct sequence and deduct 10 for every incorrect character in the wrong sequence. How would I go about doing so, and what may I have to utilize to make this possible?
Lastly, I would appreciate if anyone could point towards a way of concealing the letters that the user inputs.
Any other suggestions to make my program more efficient would be greatly appreciated!
import java.util.Scanner;
import java.lang.String;
public class MemoryGame {
public static void main(String[]args){
Scanner input = new Scanner(System.in);
int choice;
System.out.println("This is a M E M O R Y G A M E");
System.out.println("Press '1' for instructions");
System.out.println("Press '2' to play");
choice = input.nextInt(); //Checks user selection and redirects
if (choice == 1) {
Instructions();
} else {
playGame();
}
input.close();
}
public static void Instructions() { //Instructions method
int choice;
Scanner input = new Scanner(System.in);
System.out.println("This is a memory game. Below are a few instructions on how to play as well as few hints, and tricks");
System.out.println("> Players wlll be given a input box to input a given number of letters or numbers depending on the stage level.");
System.out.println("> To progress and gain points, users must sucessfully recall the set phrase that they have inputted.");
System.out.println("> Based on the number of correct letters, users will gain points and progress through a set of levels that increase in difficulty.");
System.out.println("> Upon making 3 incorrect character selections users will be displayed a 'Game Over' screen from which they may:");
System.out.println("1. Head to the main menu");
System.out.println("2. View the instructions");
System.out.println("3. Play again");
System.out.println("If users successfully oomplete 5 stages with no errors, they will be prompted a challenge level in which more characters will be required");
System.out.println(" ");
System.out.println("1. Press '1' to return to play");
choice = input.nextInt();
if (choice == 1) {
playGame();
}
input.close(); //Closes input.
}
public static void playGame() {
int userNumbers1;
int userNumbers2;
String userLetters1;
String userLetters2;
int scorePlayer;
int livesPlayer = 3;
int stagePlayer = 4;
int stageGeneral = 1;
Scanner input = new Scanner(System.in);
System.out.println("This is the M E M O R Y G A M E");
System.out.println("Stage 1 initializing . . .");
System.out.println("Please enter " + stagePlayer + " letters of your choice.");
for (int i = 0; i <= 10; i++) {
do {
userLetters1 = input.nextLine();
userLetters1 = userLetters1.toLowerCase(); userLetters1.trim();
if (userLetters1.length()==stagePlayer) {
System.out.println (". . .!");
stagePlayer = stagePlayer + 2;
stageGeneral = stageGeneral + 1;
} else {
System.out.println("Please enter " + stagePlayer + " letters");
}
}
while ( userLetters1.length() != stagePlayer);
do {
userLetters2 = input.nextLine();
userLetters2 = userLetters2.toLowerCase(); userLetters2.trim();
if (userLetters2.length()==userLetters1.length() && userLetters2.equals (userLetters1)) {
System.out.println (". . .");
System.out.println ("Great job!");
System.out.println("Stage " + stageGeneral + " initializing . . .");
System.out.println("Please enter " + stagePlayer + " letters of your choice.");
} else {
System.out.println ("Please enter " + userLetters1.length() + "letters that were previously entered.");
}
}
while ( userLetters1.length() != userLetters2.length());
}
}
}
Don't assume. Debug instead. Look what happens line by line and determine the reason the first do lop never exits. It if exited I see no reason why the second one didn't execute.
For second question I'd enciurage to read String class documentation. All you need is to iterate through characters and react accordingly to results of copmarisions.
In console, to hide previous user input you could clear the screen like:
Runtime.getRuntime().exex("cls);

hasNextInt() keeps waiting for input when pressing Enter

First post/question here and very new to java. Trying to make a small text based movie database app. One part of it is to add a review. The problem is when I just hit [enter] when asked for a Score number [0-10] on the review, the prompt just drops one step down and keeps waiting for input. I want it to be impossible to leave this field blank. Here is what I have so far:
int score;
do {
while (!sc.hasNextInt()) {
sc.next();
System.out.print("\nInvalid input! ");
System.out.print("Please enter a number from 0-10: ");
}
score = sc.nextInt();
if (!(score >= 0 && score <= 10)) {
System.out.print("\nInvalid input! ");
System.out.print("Please enter a number from 0-10: ");
}
} while (!(score >= 0 && score <= 10 ));
Scanner is reading tokens, i.e. text separated by whitespaces. That means, that as long as you just press Enter, the next token hasn't even started yet.
One of the fallacies of Scanner is that it's so easy to use, but even easier to misuse, e.g. mishandling user input.
Example: What should happen if used enters 123 abc<enter>? Your code will read 123 and continue, leaving abc in the buffer for the next prompt, which might want text and hence read the abc as that text. Oops!!
Most of the time, to handle bad user input, you should never use hasNextXxx() and nextXxx() methods other than nextLine(). It's the only way to ensure you get one answer (input) for one prompt.
So, you should do something like this:
int score;
for (;;) {
System.out.print("Please enter a number from 0-10: ");
String line = sc.nextLine();
try {
score = Integer.parseInt(line.trim());
} catch (NumberFormatException e) {
System.out.println("Invalid input! Not a number.");
continue;
}
if (score < 0 || score > 10) {
System.out.println("Invalid input! Out of range.");
continue;
}
break;
}

How can you check user input validation in Java?

I'm making a simple program that asks the user to input five numbers between 0-19. I would like to add something (like an if statement) after every number to make sure it's within that range. If not, the program should say "please read instructions again" and will then System.exit(0). This is the piece of the code that is relevant:
System.out.println("Please enter 5 numbers between 0 and 19");
System.out.print("1st Number: ");
userNum1 = scan.nextInt();
System.out.print("2nd Number: ");
userNum2 = scan.nextInt();
System.out.print("3rd Number: ");
userNum3 = scan.nextInt();
System.out.print("4th Number: ");
userNum4 = scan.nextInt();
System.out.print("5th Number: ");
userNum5 = scan.nextInt();
Any help would be greatly appreciated.
You can put this after each of your inputs, but you might want to think about putting this logic into its own method, then you can reuse the code and just call it with something like validateInput(userNum1);.
Replace val with your actual variable names.
if (val < 0 || val > 19) {
System.out.println("please read the instructions again");
System.exit(0);
}
First of all, I would create a for-loop that iterates N times, with N being the number of numbers you want to ask for (in your case, 5). Imagine your example with 50 numbers; it would be very repetitive.
Then, when you get each number with scan.nextInt() within your for-loop, you can validate however you want:
if (userNum < 0 || userNum > 19) {
// print error message, and quit here
}
Also, instead of just exiting when they input a number outside the range, you could have your logic inside a while loop so that it re-prompts them for the numbers. This way the user doesn't have to restart the application. Something like:
boolean runApplication = true;
while(runApplication) {
// do your for-loop with user input scanning
}
Then set the runApplication flag as needed based on whether or not the user put in valid numbers.
This code will do the trick for you, i added some securities :
public static void main(String[] args) {
int count = 1;
Scanner scan = new Scanner(System.in);
List<Integer> myNumbers = new ArrayList<Integer>();
System.out.println("Please enter 5 numbers between 0 and 19");
do {
System.out.println("Enter Number "+count+" ");
if(scan.hasNextInt()){
int input = scan.nextInt();
if(input >= 0 && input <= 19){
myNumbers.add(input);
count++;
}else{
System.out.println("Please read instructions again");
System.exit(0);
}
}else{
scan.nextLine();
System.out.println("Enter a valid Integer value");
}
}while(count < 6);
/* NUMBERS */
System.out.println("\n/** MY NUMBERS **/\n");
for (Integer myNumber : myNumbers) {
System.out.println(myNumber);
}
}
Hope it helps
Since you already know how many numbers you want the user to input, I suggest you use a for loop. It makes your code more elegant and you can add as many more entries as you want by changing the end condition of the loop. The only reason it looks long is because number 1, 2, 3 all end in a different format i.e firST secoND thiRD, but the rest of the numbers all end with TH. This is why I had to implement some if else statements inside the loop.
To explain the code, every time it loops it first tells the user the count of the number he/she is entering. Then numEntry is updated every time the loop loops, therefore you do not need to assign multiple inputs to multiple variables. It is more efficient to update the same variable as you go on. If the input the user inputs is less than 0 OR it is more than 19, the system exits after an error message.
System.out.println("Please enter a number between 0 and 19");
Scanner scan = new Scanner(System.in);
for(int i = 1; i <=5; i++){
if(i == 1)
System.out.println("1st Number");
else if(i == 2)
System.out.println("2nd Number");
else if(i == 3)
System.out.println("3rd Number");
else
System.out.println(i + "th Number");
int numEntry = scan.nextInt();
if(numEntry < 0 || numEntry > 19){
System.out.println("Please read instructions again.");
System.exit(1);
}

Having Problems With do...while Loop

I have a little problem with this do while loop; when I run the program it is working, at least partially, what I mean is first you need to make a choice for convertion from C to F or from F to C and after you enter the values the program stops what I want to do is to keep asking for values until you enter 3. I tried to do it with a do while loop but it is not working so if someone has any ideas I would be grateful. Here is the code:
import java.util.Scanner;
public class DegreesInConversion2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Conversion table: ");
int choice = input.nextInt();
do {
System.out.println();
System.out.println("1 for convertion from Celsious to Fahrenhait: ");
System.out.println("2 for convertion froom Fahrenheit to Celsious: ");
System.out.println("3 for Exit: ");
System.out.println();
System.out.println("Make a choice between 1 - 3 ");
choice = input.nextInt();
System.out.println();
switch (choice) {
case 1:
System.out.println("Enter temperature in Celsious: ");
double cel = input.nextDouble();
if (cel < -273.15) {
System.out.println("Invalid values, please enter temperature greater than -273.15 in C:");
} else {
System.out.println("You enetered " + cel + "C " + "which is " + (((cel * 9) / 5) + 32) + "F");
}
break;
case 2:
System.out.println("Enter temperature in Farhneit: ");
double far = input.nextDouble();
if (far < -459.67) {
System.out.println("Invalid values, please enter temperature greater than -459.67 in F:");
} else {
System.out.println("You enetered " + far + "F " + "which is " + (((far - 32) * 5) / 9) + "C");
}
break;
case 3:
System.out.println("Goodbyu have a nice day: ");
break;
default:
System.out.println("Invalid entry: Please enter a number between 1-3:");
}
} while (choice != 3);
}
}
Like in your other question, here you're scanning for input before prompting the user for input.
You need to remove the second line below:
System.out.println("Conversion table: ");
int choice = input.nextInt();
do
With your code as is, it outputs
Conversion table:
and then blocks waiting for input. Whereas you want it instead to continue into the while loop and output
1 for convertion from Celsious to Fahrenhait:
2 for convertion froom Fahrenheit to Celsious:
3 for Exit:
Make a choice between 1 - 3
before blocking to scan for input.
As is, if you enter any number at the first block, your program enters the loop and behaves as you wanted. So you're nearly there!
The code does work. the problem is most likely the
int choice = input.nextInt();
before the do
Remove this, and change
choice = input.nextInt();
to
int choice = input.nextInt();
Besides the fact that you have: int choice = input.nextInt(); outside of the loop which is unnecessarily getting input before showing the menu, it seems to all work relatively fine. You can just declare int choice inside the loop where you have choice = input.nextInt(); (ie. just change that to intchoice = input.nextInt();).
I tested your code, and it works fine if you change the line int choice = input.nextInt(); (just before your do{} while() block) into int choice;.
As others have already mentioned, you should not read input before your do{} while() block, since the question has not been asked yet.
you forgot the break; after your default case

Using a while loop to go back to start

/---------------------------------------
-----------------Quizzes.java------------
----------------------------------------/
import java.util.Scanner;
import java.text.NumberFormat;
public class Quizzes
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
NumberFormat per = NumberFormat.getPercentInstance();
//User to input keys for quiz
System.out.println("How many questions are in the quiz?");
int numques = scan.nextInt();
int[] keys = new int[numques];
for (int i=0; i<keys.length; i++)
{
System.out.print("Please enter the key for # " + (i+1)+ ": " );
keys[i] = scan.nextInt();
}
//User to input answer
System.out.println("\nGrading Quizzes");
System.out.println("--------------------");
int correct=0;
for (int i=0; i<keys.length; i++)
{
System.out.println("Please enter the answer for # " + (i+1)+ ": ");
int answer= scan.nextInt();
if (answer== keys [i])
{
System.out.print("Number "+(i+1)+" is correct.\n");
correct++;
}
else
{
System.out.print("Number "+(i+1)+" is incorrect.\n");
}
}
double cal=(double) correct/numques;
System.out.println("Total number of correct is "+correct);
System.out.println("The percent correct is " +per.format(cal));
System.out.println("Would you like to grade another quiz? (y/n)");
String user_input=scan.next();
while(user_input.equals("y"))
{ correct=0;
for (int i=0; i<keys.length; i++)
{
System.out.println("Please enter the answer for # " + (i+1)+ ": ");
int answer= scan.nextInt();
if (answer== keys [i])
{
System.out.print("Number "+(i+1)+" is correct.\n");
correct++;
}
else {
System.out.print("Number "+(i+1)+" is incorrect.\n"); }
}
cal=(double) correct/numques;
System.out.println("Total number of correct is "+correct);
System.out.println("The percent correct is " +per.format(cal));
}
System.out.println("Goodbye!");
}
}
How would I make the program go back to where the user would have to enter the answer using the while loop? No matter what I tried, right when it prints out, "Would you like to grade another quiz, and if the user type y, it would just end. Can anyone point out what I'm doing wrong
Edit 1: Well I got it to re-run again after the while loop but it keep asking me to input the answer for the question over and over and over again, it doesn't break out of the loop,it doesn't go back to the part where it asked if I wanted to grade another. This is the output
How many questions are in the quiz?
2
Please enter the key for # 1: 1
Please enter the key for # 2: 2
Grading Quizzes
Please enter the answer for # 1:
1
Number 1 is correct.
Please enter the answer for # 2:
3
Number 2 is incorrect.
Total number of correct is 1
The percent correct is 50%
Would you like to grade another quiz? (y/n)
y
Please enter the answer for # 1:
1
Number 1 is correct.
Please enter the answer for # 2:
2
Number 2 is correct.
Total number of correct is 2
The percent correct is 100%
Please enter the answer for # 1:
1
Number 1 is correct.
Please enter the answer for # 2:
2
Number 2 is correct.
Total number of correct is 2
The percent correct is 100%
Please enter the answer for # 1:
while(user_input.equals('y'))
should be
while(user_input.equals("y")) // see the double quotes here
Problem with your code is that character 'y' is autoboxed to instance of Character class which is the subclass of Object.
Class Object is the root of the class
hierarchy. Every class has Object as a
superclass. All objects, including
arrays, implement the methods of this
class
So is the candidate for public boolean equals(Object).
String implementation of boolean equals(Object) checks whether the instance is of type String. if it fails, it will simply return false.
If you want to compare with 'y', then try this.
while(user_input.equals(((Character)'y').toString()))
I will put the question a while loop and it will be something like
while (true) {
// ask the users the questions
// ask if he wants to continue... if no then break; else continue
}
Ok add a while(true) at the beginning of your program and add the appropriate brackets to encompass the whole method's contents. Then, delete the current while loop you have. Say after you get your input for user_input:
if (user_input.equals("y")) {
}
else {
break;
}
You will replace this while with your while(user_input.equals("y")) loop and the problem you pointed will go away but i think still your code will not work as you expected. I think your will need these more correction on your code
while loop should be this one while(user_input.equalsIgnoreCase("y"))
Put the opening and closing braces for while loop and in end while after finishing your for loop put these two statement to check again and again.
follow the following snap of code
while(user_input.equalsIgnoreCase("y"))
{
for (int i=0; i<keys.length; i++)
{
....
}
System.out.println("Would you like to grade another quiz? (y/n)");
user_input=scan.next();
}

Categories

Resources