How to go back into a while-loop, from an if statement? - java

Here's what i've been working on. I'm trying loop this while method, using booleans. (My teacher is incompetent, so i've been learning out of textbook.)
else { System.out.println("Do you want to restart? Y/N");
string answer = scn.next();
return;
if (scn.hasNext() && !no)) {
System.out.println("end");
} else{
continue;
}
/*if (repeat) {
continue;
} else {
System.out.println("End");
break;
}*/
}
This is nested in a while loop like so ....
import java.util.Scanner; import java.lang.String;
public class booleanvariables {
public static void main (String[] args){
Scanner scn = new Scanner(System.in);
int score1, score2;
String answer, e;
boolean bothHigh, atLeastOneHigh, atLeastOneModerate, noLow, tooLow, repeat;
while (true) {
System.out.print("Enter the first test score:\t");
score1 = scn.nextInt();
System.out.print("Enter the second test score:\t");
score2 = scn.nextInt();
answer = null;
e = "n";
bothHigh = (score1 >= 90 && score2 >= 90);
atLeastOneHigh = (score1 >= 90 || score2 >= 90);
atLeastOneModerate = (score1 >= 70 || score2 >= 70);
noLow = !(score1 < 50 || score2 < 50);
tooLow = (score1 <= 50 || score2 <= 50);
repeat = (answer == "yes" || answer == "y"); //|| answer == Y || answer == Yes);
if (tooLow)
System.out.println("Inputs are too low");
if (bothHigh)
System.out.println("Qualified to be a manager");
if (atLeastOneHigh)
System.out.println("Qualified to be a supervisor");
if (atLeastOneModerate && noLow)
System.out.println("Qualified to be a clerk");
/** NESTED WRONG I'M AWARE
*/
else { System.out.println("Do you want to restart? Y/N");
string answer = scn.next();
return;
if (scn.hasNext() && !no)) {
System.out.println("end");
} else{
continue;
}
/*if (repeat) {
continue;
} else {
System.out.println("End");
break;
}*/
}
}
}
}

This is much simpler than you think.
Just do it like this:
boolean stop = false;
while(!stop) {
//do whatever you want here
System.out.println("Do you want to quit?(yes or no");
String input = scan.nextLine();
if(input.equals("no")) {
stop = true;
}
}
That way, if you enter "no", it'll set the boolean to true, which then will make the condition for the while loop, !stop, equal to false.

answer == "yes"
You are checking if two objects are the same. You should use the equals method answer.equals("yes") || answer.equals("y")

Tested and Working to My Liking
I've reworked some branching. ( I use BlueJ as a compiler and it thinks this is an error without the input = scn.nextLine();
do {
//same booleans i've been using
if (!stop) {
System.out.print("Do you want to quit? (yes or no):\t");
//String input;
input = scn.nextLine();
}
//String input;
input = scn.next();
if(input.equals("yes")) {
stop = true;
System.out.println("Goodbye");
return;
}
} while (!stop);
I really don't know why blue J doesn't like it when initialize input from within the if statement

Related

Main will not call array

I made an array to randomly pick either "steak, pizza, or chips" but I upon running my program it errors out well before you even get to the question. It works for about 5 inputs before it gives me an exception.
I assume the problem lies within the
{System.out.println(FoodArray.getRandomWord(args));
but I can't seem to figure out what is wrong with it.
I just need my program to run correctly, and when it gets to the question about giving a random suggestion, it prints out steak, pizza or chips randomly.
public static void main(String[] args) {
int input = 0;
int sweet = 0;
int savory = 0;
int salty = 0;
Random r = new Random();
FoodArray a = new FoodArray();
Scanner myscanner = new Scanner(System.in);
System.out.println("Welcome, lets figure out what you're hungry for."
+ "Press 0 to continue");
input = myscanner.nextInt();
if (input > 0) {
}
{
System.out.println("What sounds the best to you right now?\n"
+ "1) Something sweet\n"
+ "2) Savory\n "
+ "3) Salty\n ");
}
input = myscanner.nextInt();
if (input == 1) {
System.out.println("something sweet. okay. next question");
sweet++;
} else if (input == 2) {
System.out.println("Savory eh? got it. lets move on.");
salty++;
} else if (input == 3) {
System.out.println("Sounds good. Lets proceed");
savory++;
}
System.out.println("Press 0 to continue");
input = myscanner.nextInt();
System.out.println("pick a number 1-3");
input = myscanner.nextInt();
if (input == 1) {
System.out.println("Very interesting.");
sweet++;
} else if (input == 2) {
System.out.println("Very interesting.");
salty++;
} else if (input == 3) {
System.out.println("Very interesting.");
savory++;
}
System.out.println("Press 0 to continue");
input = myscanner.nextInt();
System.out.println("Next question: "
+ "Would you rather, fly, (1) breath underwater, (2) or be invisible (3)");
input = myscanner.nextInt();
if (input == 1) {
System.out.println("Good choice.");
sweet++;
}
if (input == 2) {
System.out.println("Would be pretty cool");
salty++;
}
if (input == 3) {
System.out.println("Trick question, you already are invisible loser."
+ "Lets continue. ");
savory++;
}
System.out.println("Okay. now heres a random suggestion.");
{System.out.println(FoodArray.getRandomWord(args));
}
System.out.println("Okay. Lets see your final score."
+ "Press 0 to continue");
input = myscanner.nextInt();
if (sweet > salty && sweet > savory) {
System.out.println("Get something sweet. maybe cake.");
}
if (salty > sweet && salty > savory) {
System.out.println("Get something salty. Maybe potatoe chips");
}
if (savory > sweet && savory > salty) {
System.out.println("Savory! Steak steak steak!");
}
if (salty == sweet && salty == savory) {
System.out.println("Its a tie. Can't help you. sorry.");
}
if (sweet == salty && sweet == savory) {
System.out.println("Its a tie. Can't help you. sorry.");
}
if (savory == sweet && savory == salty) {
System.out.println("Its a tie. Can't help you. sorry.");
}
}
}
public class FoodArray {
String[] strArray = { "Pizza", "Steak", "Chips" };
static public String getRandomWord(String[] array) {
Random r = new Random();
int index = r.nextInt(array.length);
return array[index];
}
}
change to
::FoodArray::
String[] strArray = { "Pizza", "Steak", "Chips" };
to
public static String[] strArray = { "Pizza", "Steak", "Chips" };
::main::
FoodArray.getRandomWord(args)
to
FoodArray.getRandomWord(FoodArray.strArray)
but this is stupid as FoodArray already knows about strArray so delete the passing of paramaters to this method and use strArray within FoodArray

How to make code loop with boolean specified at the end of code?

Try to make my code so that I can ask the user if they want to play again, however I'm confused how I'm supposed to go about this.
Scanner in = new Scanner(System.in);
int randomNum = 1 + (int)(Math.random() * 100);
System.out.println(randomNum);
Boolean playAgain = true;
while (playAgain) {
System.out.print("I'm thinking of a number between 1 and 100.\nWhat is it?\nGuess: ");
int guessNum = in.nextInt();
while ((guessNum > randomNum) || (guessNum < randomNum)) {
if (guessNum > randomNum) {
System.out.print("Too High.\nGuess: ");
guessNum = in.nextInt();
} else if (guessNum < randomNum) {
System.out.print("Too Low.\nGuess: ");
guessNum = in.nextInt();
}
}
System.out.println("You got it!\nPlay again? (Y/N) ");
String answer = in.next();
if (answer == "y") {
playAgain = true;
} else {
playAgain = false;
System.out.println("Thanks for playing!");
}
}
You have used == equals Relational Operator which usually used to check string reference not the value actually. So, even if answer contains y then your conditional expression never returns true as a Result.
For Reference : Visit Here For More Info ( '==' vs 'equals()' method)
String answer = in.next();
//problem with this line becuase == operator use to check reference instead of value
if (answer == "y") {
playAgain = true;
} else {
playAgain = false;
System.out.println("Thanks for playing!");
}
So change your code as like below
String answer = in.next();
if (answer.startsWith("y") || answer.startsWith("Y")) { // Now this willl work fine to your code
playAgain = true;
} else {
playAgain = false;
System.out.println("Thanks for playing!");
}
It May help You
do {
System.out.print("I'm thinking of a number between 1 and 100.\nWhat is it?\nGuess: ");
int randomNum = 1 + (int) (Math.random() * 100);
System.out.println(randomNum);
int guessNum = in.nextInt();
do {
if (guessNum > randomNum) {
System.out.print("Too High.\nGuess: ");
guessNum = in.nextInt();
} else if (guessNum < randomNum) {
System.out.print("Too Low.\nGuess: ");
guessNum = in.nextInt();
}
}while ((guessNum > randomNum) || (guessNum < randomNum));
System.out.println("You got it!\nPlay again? (Y/N) ");
answer = in.next();
}while(answer.equals("y"));
If you want to use playAgain var, then use
answer.equals("y")
to compare two strings instead of ==.
otherwise have your full code inside while block or do while. And if user wants to play, then do continue, otherwise do break;
while(true)
{
// your code
String answer = in.next();
if (answer == "y") {
continue;
} else {
System.out.println("Thanks for playing!");
break;
}
}

How can I create an if statement with 3 conditions? (Java)

I just started learning java a week ago. I am taking a class at my school. I am trying to create a quiz and I can't figure out how to print out the score. The quiz has three possibilities 3/3, 2/3, 1/3. The problem I am having is with the if statements near the end of the program.
import java.io.*;
import static java.lang.System.*;
import java.util.Scanner;
class t1_lesson03_template{
public static void main (String str[]) throws IOException {
Scanner scan = new Scanner(System.in);
System.out.println("1. What do you type at the begining of a comment?");
String answer1 = "//";
String userinput1 = scan.nextLine();
if (userinput1.equals(answer1)) {
System.out.println(" Correct!");
}
if (!userinput1.equals(answer1)) {
System.out.println(" Wrong!");
}
String answer2 = ("(int)");
System.out.println("2. What do you type before a double to convert to an int?");
String userinput2 = scan.nextLine();
if (userinput2.equals(answer2)) {
System.out.println(" Correct!");
}
if (!userinput2.equals(answer2)) {
System.out.println(" Wrong!");
}
String answer3 = ("int number = 5;");
System.out.println("3. Create an int called \"number\", and make it equal 5.");
String userinput3 = scan.nextLine();
if (userinput3.equals(answer3)) {
System.out.println(" Correct!");
}
if (!userinput3.equals(answer3)) {
System.out.println(" Wrong!");
}
if (userinput1.equals(answer1) && userinput2.equals(answer2) && userinput3.equals(answer3)) {
System.out.println("3/3 Awesome!");
}
else if (userinput1.equals(answer1) || userinput2.equals(answer2) || userinput3.equals(answer3)) {
System.out.println("2/3 Good job.");
}
else {
System.out.println("1/3 Try again.");
}
}
}
This,
else if (userinput1.equals(answer1) || userinput2.equals(answer2)
|| userinput3.equals(answer3)) {
should be something like
else if ((userinput1.equals(answer1) && userinput2.equals(answer2)) ||
(userinput1.equals(answer1) && userinput3.equals(answer3)) ||
(userinput2.equals(answer2) && userinput3.equals(answer3))) {
but I would prefer a count. And an array to display your different messages. Something like
int count = 0;
if (userinput1.equals(answer1)) {
count++;
}
if (userinput2.equals(answer2)) {
count++;
}
if (userinput3.equals(answer3)) {
count++;
}
String[] result = { "0/3 None", "1/3 Try Again.", "2/3 Good Job.", "3/3 Awesome!" };
System.out.println(result[count]);
Just add braces before each condition in if class and else if such as
if ((userinput1.equals(answer1)) && (userinput2.equals(answer2)) && (userinput3.equals(answer3))) {
System.out.println("3/3 Awesome!");
}
else if ((userinput1.equals(answer1)) || (userinput2.equals(answer2)) || (userinput3.equals(answer3))) {
System.out.println("2/3 Good job.");
}

How to automatically output strings in loops

So I just have a quick little issue
int pickmeup = 0;
while (true)
{
pickmeup = scanner.nextInt();
if (pickmeup == 1)
{System.out.println ("you entered 1");}
if(pickmeup == 2)
{System.out.println ("you entered 2");}
{
break;
}
System.out.println ("Invalid code");
Now when I run this code it all works fine however in regards to the strings but it seems as though the loop doesn't work all that well when I enter '3', as it doesn't return the string 'Invalid code'.
If I were to get rid of the strings after both if statements, then it works perfectly fine. What exactly am I doing wrong? Are there other ways to automatically have strings output?
I believe you want to use a logical or || and an else like,
int pickmeup;
while (true) {
pickmeup = scanner.nextInt();
if (pickmeup == 1 || pickmeup == 2) {
System.out.printf("you entered %d%n", pickmeup);
} else {
System.out.println("Invalid code");
}
}
Alternatively, you could use an else if chain like,
int pickmeup;
while (true) {
pickmeup = scanner.nextInt();
if (pickmeup == 1) {
System.out.println("you entered 1");
} else if (pickmeup == 2) {
System.out.println("you entered 2");
} else {
System.out.println("Invalid code");
}
}
You could start with firstly correcting your code, you can do that in eclipse Source-Format or by pressing CTRL+SHIFT+F
For your example, I corrected as much as I understood, currently it breaks only if else is reached. Break can be modified.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int pickmeup = 0;
while (true){
pickmeup = scanner.nextInt();
if (pickmeup == 1){
System.out.println("one");
}
else if (pickmeup == 2){
System.out.println("two");
}
else{
System.out.println("Invalid code");
break;
}
}

Boolean bug (FibonacciNumbers)

First of all I am not asking anyone to do anything just need a little help to fix this bug with boolean. I put false but the program stops. I got two parts to the program.
First part where i did the calculations:
class FibonacciNumbers {
FibonacciNumbers() {} //default constructor
public int fOf(int n) {
if (n == 0) //the base case
{
return 0;
} else if (n == 1) {
return 1;
} else {
return fOf(n - 1) + fOf(n - 2);
}
}
}
Second where the main method is:
import java.util.*;
public class FibonacciNumbersTesters {
public static void main(String[] args) {
FibonacciNumbers fNumbers = new FibonacciNumbers(); //creates new object
Scanner in = new Scanner(System.in);
String again;
String test;
boolean IsRepeat = true;
boolean isQuit;
try {
isQuit = false;
while (!isQuit) {
System.out.print("Enter the number you want to convert to Fibanocci('q' to quit): ");
int n = in.nextInt();
System.out.print("The Fibanocci number for " + n + " is: ");
n = fNumbers.fOf(n);
System.out.println(n);
System.out.print("Do you want to run again? (Y or N): ");
again = in.next();
if (again.equalsIgnoreCase("N")) {
System.out.println("Thank you! Please terminate the program by entering 'Q' or 'q' OR you can cotinue by entering anything else: ");
String toQuit = in.next();
if ((toQuit.charAt(0) == 'q') || (toQuit.charAt(0) == 'Q')) {
System.out.println("Good-bye!");
isQuit = true;
}
} else {
IsRepeat = true;
}
}
} catch (InputMismatchException ex) {
test = in.nextLine();
if ((test.charAt(0) == 'q') || (test.charAt(0) == 'Q')) {
System.out.println("Good-bye!");
isQuit = true;
} else {
System.out.println("Invalid input!");
System.out.println("Try again! ");
isQuit = false;
}
}
}
}
This part where i put isQuit = false; at the end it just stops. I want it to continue.
Try putting your try catch statement inside of your while loop.

Categories