How should I structure this while loop? (JAVA) - java

New to Java. How should I structure this while loop to re-enter the loop when user input is 'Y'? Should the while go at the very beginning? The sample of the output is below code.
import java.util.Scanner;
public class RamosSLE33 {
public static void main(String[] args) {
char cont = 'Y';
String anniversaryGift = " ";
int year = 0;
Scanner input = new Scanner(System.in);
System.out.printf("ANNIVERSARY YEAR%n%n1. 50%n2. 55%n3. 60%n4. None of the above."
+ "%n%nSelect the anniversary year: ");
year = input.nextInt();
if (year == 1)
System.out.printf("The anniversary gift is gold.");
if (year == 2)
System.out.printf("The anniversary gift is emerald.");
if (year == 3)
System.out.printf("The anniversary gift is diamond.");
if (year == 4)
System.out.printf("Go to www.bernardine.com/jewelry-anniv.htm#traditional for more gift choices.");
cont = 'N';
while(Character.toUpperCase(cont) == 'Y') {
System.out.printf("%nSearch for another anniversary gift? Enter 'Y' or 'N': ");
cont = input.nextLine().charAt(0);
} // End while == Y
} //End main()
} //End class RamosSLE33
SAMPLE OUTPUT

You have few mistakes in the program.
Your while loop doesn't repetitively run the entire program
The Scanner input might be a Resource leak hence you have not closed it.
Please refer to the corrected program as below
public class RamosSLE33 {
public static void main(String[] args) {
char cont = 'Y';
int year = 0;
Scanner input = new Scanner(System.in);
while (Character.toUpperCase(cont) == 'Y') {
System.out.printf("ANNIVERSARY YEAR%n%n1. 50%n2. 55%n3. 60%n4. None of the above."
+ "%n%nSelect the anniversary year: ");
year = input.nextInt();
if (year == 1) {
System.out.printf("The anniversary gift is gold.");
} else if (year == 2) {
System.out.printf("The anniversary gift is emerald.");
} else if (year == 3) {
System.out.printf("The anniversary gift is diamond.");
} else if (year == 4) {
System.out.printf("Go to www.bernardine.com/jewelry-anniv.htm#traditional for more gift choices.");
} else {
System.out.printf("An invalid Input Number");
}
cont = 'N';
System.out.printf("%nSearch for another anniversary gift? Enter 'Y' or 'N': ");
cont = input.next(".").charAt(0);
} // End while == Y
input.close();
System.out.printf("%n The progrm ends: ");
} // End main()
}

Not sure if you shortcutted copying the code, but the shorthand ifs only do one line you'd need braces{} for 2.
this part
if (year == 4)
System.out.printf("Go to www.bernardine.com/jewelry-anniv.htm#traditional for more gift choices.");
cont = 'N';
Hence cont always equals 'N' before that loop, so it's never entered. That's probably what's getting you, rest is just me doing light code critiquing really.
You may also consider 'Y'.equals(cont.touppercase()) to avoid nullpointer exceptions when cont is null, though I think your Character factory might dodge that it's a good habit to do constants first.
maybe also using a do while instead so it always enters the thing to grab the input.nextline() before evaluating if it's Y and deciding to continue.
If you want it to reenter the whole method at the end look into recursion. You may need to make the cont variable class level or break it out into another method with cont as an argument; remember to have an exit condition if you go that route.

Related

Code after while loop not accepting input [Java]

So, in this program when the while loop ends, it properly displays "You Win!" and it does execute the code asking if the user wants to view credits. However, the input isn't being accepted after the question and the program ends without accepting any input.
Scanner scan = new Scanner(System.in);
System.out.println("Would you like to play a game called Threes? Y/N");
String answer = scan.nextLine(); //Simple yes or no
if (answer.contains("Y") || (answer.contains("y"))) {
System.out.println("OK, want to know how it works? Y/N");
String answer2 = scan.nextLine();
if (answer2.contains("n") || (answer2.contains("N"))) {
System.out.println("OK, Enter a single number.");
int mistake = 0; //Used as a counter for number of division mistakes made
int numstart = scan.nextInt(); //First number input
int current = numstart; //Current number displayed - starts as the first number
System.out.println("Enter 1 or -1 if you're adding or subtracting, and 0 to divide.");
System.out.println(numstart); //Displays first number input
int input = scan.nextInt(); //First function performed by user
while (current != 1) { //The game will run until the number '1' is reached
if (input == 1) { //If '1' is input, add one to the number, and display new number
current++;
System.out.println(current);
input = scan.nextInt();
}
if (input == -1) { //If '-1' is input, subtract one from the number, and display new number
current--;
System.out.println(current);
input = scan.nextInt();
}
if (input == 0) { //If '0' is input, try to divide
if (current % 3 != 0 && current != 1) { //If you can't divide by three, try again
System.out.println("Try again.");
mistake++;
input = scan.nextInt();
}
if (current % 3 == 0) { //If you can divide, do it and display new number
current = current / 3;
System.out.println(current);
input = scan.nextInt();
}
}
if (input == 69 || input == 666) //Cheat code! If you input 69 or 666, you automatically win
break;
if (((input > 1) && (input != 69) && (input != 666)) || input < -1) { //If input is not valid, try again and display error
System.out.println("Error - wrong input.");
input = scan.nextInt();
}
}
System.out.println("You Win! Mistakes: " + mistake + "\n"); //Will display a win condition, and amount of division errors
System.out.println("Thank you for playing Threes \n - Chris Burbach");
}
System.out.println("Credits? Y/N");
String credits = scan.nextLine();
if(credits.contains("Y")||credits.contains("y"))
{
System.out.println("\n***********************************************************************");
System.out.println("*Threes: a game of dividing by three - inspired by my boredom in class*");
System.out.println("***********************************************************************");
Sorry for any confusion, I figured it out. After each instance of "You Win!", outside of its nested if statement, I needed to addscan.nextLine(); because of it returning a newline character and terminating the program due to an empty input.

Wrong Quiz result

This is the output of the program
I was able to do till to get this result by doing this program below
import java.util.Scanner;
public class aLittleQuiz {
public static void main(String[] args) {
// declaring varibles
String quizStart;
int quizAns1, quizAns2, quizAns3;
Scanner input = new Scanner(System.in);
System.out.println("Are you ready for a quiz? (y / n)");
quizStart = input.next();
System.out.println("Okay, here it comes!");
// quiz answer 1
System.out.println("\nWhat is the capital of Alaska? \n1) Melbourne\n2) Anchorage\n3) Juneau");
quizAns1 = input.nextInt();
if (quizAns1 == 3) {
System.out.println("That's right");
} else {
System.out.println("Your answer is wrong, sorry!");
}
// quiz answer 2
System.out.println("Q2) Can you store the value ''cat'' in a variable of type int? \n1) yes \n2) no");
quizAns2 = input.nextInt();
if (quizAns2 == 1) {
System.out.println("Sorry, ''cat'' is a string. ints can only store numbers.");
} else if (quizAns2 == 2) {
System.out.println("Correct!");
}
// quiz answer 3
System.out.println("What is the result of 9+6/3? \n1) 5\n2) 11 \n3) 15/3");
quizAns3 = input.nextInt();
if (quizAns3 == 2) {
System.out.println("That's correct!");
} else {
System.out.println("");
}
// if (quizAns == 3 && quizAns == ) {
// }
}
}
but how I can program this part?
"Overall, you got 2 out of 3 correct.
Thanks for playing!"
Declare a variable like int marks and increment it by one inside if\else block(which made for correct answer). And at the end print
System.out.println("Overall, you got" +marks+" out of 3 correct. Thanks for playing!");
Assuming your no of question is fixed( 3 )
String quizStart;
int quizAns1, quizAns2, quizAns3;
int marks=0;
Scanner input = new Scanner(System.in);
System.out.println("Are you ready for a quiz? (y / n)");
quizStart = input.next();
System.out.println("Okay, here it comes!");
// quiz answer 1
System.out.println("\nWhat is the capital of Alaska? \n1) Melbourne\n2) Anchorage\n3) Juneau");
quizAns1 = input.nextInt();
if (quizAns1 == 3) {
System.out.println("That's right");
++marks;
} else {
System.out.println("Your answer is wrong, sorry!");
}
// quiz answer 2
System.out.println("Q2) Can you store the value ''cat'' in a variable of type int? \n1) yes \n2) no");
quizAns2 = input.nextInt();
if (quizAns2 == 1) {
System.out.println("Sorry, ''cat'' is a string. ints can only store numbers.");
} else if (quizAns2 == 2) {
System.out.println("Correct!");
++marks;
}
// quiz answer 3
System.out.println("What is the result of 9+6/3? \n1) 5\n2) 11 \n3) 15/3");
quizAns3 = input.nextInt();
if (quizAns3 == 2) {
System.out.println("That's correct!");
++marks;
} else {
System.out.println("");
}
System.out.println("Overall, you got " +marks+" out of 3 correct. Thanks for playing!");

Can I use "return" in here or any ideas?

I'm really new to Java and most of my knowledge are self- taught. can you help me to figure out this.
Our teacher wants us to make a menu about Java. Where the output something like this..
Menu
1 - Java History
2- Java Keywords
3 - Java Arrays and so on. .
Do you want to read one (Yes/No):
//if yes
Please enter a menu number:
// then it will display an information..
//my problem is that how can I connect the new entered value to the first method so that I don't have write it all over again...
this is whats on my mind..
but im stuck..
import java.util.Scanner;
public class Program {
public static void main (String [] args) {
System.out.println("Please enter a number:");
int x = nextInt();
if (x == 1) {
for (int x = 5; x == 5;x++) // array of 1(first menu)
System.out.println ("Do you want to read another? (Yes/No):");
System.out.println ("Please enter a menu number:")
// return to if with it's new entered value....
}
else if (x == 2) {
for loop of array 2
System.out.println ("Do you want to read another? (Yes/No):");
System.out.println ("Please enter a menu number:")
// return to if with it's new entered value....
}
else if (x == 3) {
for loop of array 3
System.out.println ("Do you want to read another? (Yes/No):");
System.out.println ("Please enter a menu number:")
// return to if with it's new entered value....
else if (x ==4) {
for loop of array 4
else if (x == 5) {
for loop of array 5
else if (x == 6) {
for loop of array 6
else if (x == 7) {
for loop of array 7
else if (x == 8) {
for loop of array 8
else if (x == 9) {
for loop of array 9
else if (x == 10) {
for loop of array 10
else {
//exit the program
If I understand correctly, you would want to implement the While or do while statement in your program.
Example of While and Do While Loops
Im not really sure what you are trying to accomplish with your program but here is a little example I made quickly of how to utilize the for loop in your case. `import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean keepGoing = true; //As long as this is true the while statement will continue;
while (keepGoing) {
System.out.println("Enter a number");
int x = scan.nextInt();
//logic
if (x == 1) {
System.out.println("X is equal to 1");
} else if (x == 2)
System.out.println("X is equal to 2");
//prompts the user if they want to keep going.
System.out.println("Would you like to keep going? Y/N");
String decision = scan.next();
if (decision.equalsIgnoreCase("y")) {
keepGoing = true;
} else {
System.out.println("Quitting...");
keepGoing = false;
}
}
}
}
`

Cant figure out how to exit the loop of my program

I am writing a program for class that is a leap year checker. I have the loop working from what I understand however it goes into an infinite loop still? Zero wont terminate the program. I've tried using else if, if, while, what have I done wrong? This is my third go at rewriting this and am completely lost now -_-. Any help or tips would be appreciated.
import java.util.Scanner;
public class LeapYearChecker {
public static void main(String[] args){
System.out.println("Please enter a date to find out if the year is a leap year.");
Scanner userInput = new Scanner(System.in);
int year = userInput.nextInt();
while(year == 0)
{
System.out.println();
}
if (year < 1582){
System.out.println("Please enter a date after 1582. The date you entered was" + year + ".");
}if((year % 4 == 0) && (year % 100 !=0) || (year % 400 == 0)){
System.out.println("That is a leap year");
}else{
System.out.println(year +" is not a leap year.");
}
}
}
while (year == 0)
{
System.out.println();
}
There's your problem, if the year is 0, your program will infinitely output a new line.
Furthermore, your ifs for checking if it is a leap year isn't inside the loop body, so even if you enter a non-zero number, the code will only run once.
Try the following code, be sure to read the comments to understand what's going on:
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int year = -1; //Give your int a default value so the main loop will execute
while (year != 0) //-1 not equal to zero, so your code will start
{
System.out.print("Please enter a year: "); //Now we get the value of the year
year = in.nextInt(); //Put it into our variable
if (year < 1582) //And if it's less than 1582
{
if (year != 0)
System.out.println("Year must not be less than 1582!"); //Notify the user, unless they are exiting the program
continue; //restart the while loop, this is quite a useful statement!
}
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) //Check if it's a leap year
System.out.println("That is a leap year!\n");
else
System.out.println("That is not a leap year :(\n");
//End of the loop, so it goes back to the beginning, which asks the user again for the year
//So if you enter 0 next the program will close
}
}
The first loop is infinite. You forgot to read the user input inside.
Your loop will only run if a user enters 0. And once they do, your program will be stuck in an infinite loop since you haven't changed the value of year inside your while.
I'm assuming that you want to keep prompting the user to keep entering numbers until they enter 0? Then I would restructure your main method so that it surrounds the code where you retrieve and process input. Like so:
System.out.println("Please enter a date to find out if the year is a leap year.");
Scanner userInput = new Scanner(System.in);
int year;
do {
year = userInput.nextInt();
/**
* Print some message based input.
*/
} while (year != 0); // Loop until user enters 0

Java: Loop issues

I'm writing a relatively simple Java program that calculates discounts for shoppers if they have certain vouchers or bonuses. It's working okay, but I have an issue when the program asks the user if they have any vouchers.
If they type "n", they still have to go through the loop as if they responded with "y" once before they can exit. I know it's probably a dumb mistake in there somewhere, but it's been driving me crazy and I'd appreciate a pair of fresh eyes to once it over.
do {
System.out.println("Please enter the total price of the goods");
price = keyboard.nextDouble();
if (price < limits[0] || price > limits[1]) {
System.out.println("Invalid price. Please try again");
validPrice = false;
} else {
validPrice = true;
}
} while (!validPrice);
keyboard.nextLine();
do {
System.out.println("Does the customer have any additional discounts? y/n");
choice = keyboard.nextLine();
if (!choice.matches(inputRegexMatchPattern)) {
System.out.println("Invalid input – please re-enter");
} else if (choice.toLowerCase().charAt(0) == 'y') ;
{
System.out.println(choice);
do {
System.out.println("What type of discount does the customer have? [L]oyalty Card/[D]iscount Voucher");
input = keyboard.nextLine();
if (!input.matches(discountRegexMatchPattern)) {
System.out.println("Invalid input – please re-enter");
}
} while (!input.matches(discountRegexMatchPattern));
if (input.charAt(0) == 'l' || input.charAt(0) == 'L') {
voucherDiscounts += voucherDiscountsArray[0];
System.out.println("Loyalty Card discount accepted");
} else if (input.charAt(0) == 'd' || input.charAt(0) == 'D') {
voucherDiscounts += voucherDiscountsArray[1];
System.out.println("Discount Voucher accepted");
}
}
} while (!(choice.toLowerCase().charAt(0) == 'n'));
You have a semicolon here:
else if (choice.toLowerCase().charAt(0) == 'y') ;
What that means is your loop will continue to execute in spite of the selection you make. Java interprets this if statement as not having any body.
Remove the semicolon and you should be good to go.
The do while construct always performs the content of the loop BEFORE it actually tests the condition.
I guess what you want here is a simple while loop.

Categories