Why deos my "While" loop keep going on? - java

My loop never stops, I can't seem to understand what is wrong. I'm doing
a project for my class and I'm new to loops so kind of confused. Please tell me how
to resolve this issue.
import java.util.Scanner;
public class FracCalc {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in); {
boolean Quit = true;
System.out.println("Welcome to FracCalc");
System.out.println("Type expressions with fractions, and I will evaluate them");
String answer = scan.nextLine();
while (Quit = true) {
if (answer.equals("Quit")){
System.out.println("Thanks forr running FracCalc!");
break;
} else {
System.out.println("I can only process 'Quit' for now");
}
}
}
}
}

Quit = true will assign true to Quit, and return true. Thus, you're doing while (true), a canonical infinite loop. And even if you were testing Quit == true (note double equality sign), you never assign it to false, as Izcd remarks. You could break out with your if, but answer is only assigned once, outside the loop.

Put String answer = scan.nextLine(); inside the loop.
Try the following:
import java.util.Scanner;
public class FracCalc {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to FracCalc");
System.out.println("Type expressions with fractions, and I will evaluate them");
String answer = scan.nextLine();
do {
if (answer.equals("Quit")) {
System.out.println("Thanks forr running FracCalc!");
break;
} else {
System.out.println("I can only process 'Quit' for now");
}
answer = scan.nextLine();
} while (true);
}
}

Related

How to make a loop run until the console prints a certain statement within that loop?

I am trying to achieve a certain result or output before terminating the loop.
Here is my code:
import java.util.Scanner;
public class learnjava {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("How old are you?");
int age = scanner.nextInt();
scanner.nextLine();
System.out.println("Do you prefer cats or dogs?");
String animal = scanner.nextLine();
if (age > 10 || animal.equals("cats"))
{System.out.println("welcome!");}
else {System.out.println("No access");}
scanner.close();
}
}
Ideally I want to create a loop that makes my code run until system prints out welcome, so that I can avoid restarting the program. I want to provide the user another chance at inputting right answers once the first input fails without running again, hence the console should ask again "how old are you?"
You can use a do while loop for this use case. The actual validation logic can be put within the loop and the loop will be terminated only if the condition is invalid.
So in you case, the loop will check the condition age < 10 || !animal.equals("cat"). So the loop will run till the age exceeds 10 or the animal is "cat". As this is an exit check loop, it will exit only after printing "Welcome" to the console.
The code is as follows,
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String animal;
int age;
do{
System.out.println("How old are you?");
age = scanner.nextInt();
scanner.nextLine();
System.out.println("Do you prefer cats or dogs?");
animal = scanner.nextLine();
if (age > 10 || animal.equals("cats"))
{
System.out.println("welcome!");
}
else {
System.out.println("No access");
}
}while(age < 10 || !animal.equals("cat"));
scanner.close();
}
}
You use loops in java for repeated task. while loop is one of them
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
if (askUser(scanner)) {
System.out.println("welcome!");
break;
} else {
System.out.println("No access");
}
}
scanner.close();
}
private static boolean askUser(Scanner scanner) {
System.out.println("How old are you?");
int age = scanner.nextInt();
scanner.nextLine();
System.out.println("Do you prefer cats or dogs?");
String animal = scanner.nextLine();
return (age > 10 || animal.equals("cats"));
}
How about wrapping the logic in a while loop with a boolean variable to indicate the isFinished status:
import java.util.Scanner;
public class learnjava {
private static final String WELCOME = "welcome!";
private static final String ACCESS_DENIED_TRY_AGAIN = "No access";
public static void main(String[] args) {
boolean isFinished = false;
Scanner scanner = new Scanner(System.in);
while (!isFinished) {
System.out.println("How old are you?");
int age = scanner.nextInt();
System.out.println("Do you prefer cats or dogs?");
String animal = scanner.nextLine();
if (age > 10 || animal.equals("cats")) {
System.out.println(WELCOME);
isFinished = true;
} else {
System.out.println(ACCESS_DENIED_TRY_AGAIN);
}
}
scanner.close();
}
}

How to restart the main method?

public class Main {
public static void main(String[] args) {
System.out.println("Please enter a math value.");
Scanner sayiyaz = new Scanner(System.in);
if(sayiyaz.hasNextInt()) {
int sayi1 = sayiyaz.nextInt();
}
else {
System.out.println("I wish u could know what is a math value .");
}
}
}
In the else block of code i want to restart the "main" method from the beginning and ask the same question.
But how to do that ?
You can call it if you want to (like Sudhakar sugested) but i assume that you just want to request the input until you get something that fits your needs in that case you have a better solution
public static void main(String[] args) {
boolean done = false;
Integer sayi1 = null;
do {
System.out.println("Please enter a math value.");
Scanner sayiyaz = new Scanner(System.in);
if (sayiyaz.hasNextInt()) {
sayi1 = sayiyaz.nextInt();
done = true;
} else {
System.out.println("Input is wrong ");
}
} while (!done);
System.out.println("Here is youre input " + sayi1);
}
The answer is that you don't want to restart main. This is the entry point used by the Java Virtual machine to start your application. The simplest way to do what you want is to use a loop, so something like:
while (true) {
System.out.println("Please enter a math value");
// The rest of your code.
if (finished)
break;
}

Multi-word scanner input in java?

So I'm trying to use if-else statement dependant upon the user's input. It works when the user's input is only one word, however, multiple word inputs go unrecognized and triggers the else statement. How can i resolve this?
import java.util.Scanner;
public class MyFirstJavaClass {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner myScanner = new Scanner(System.in);
String answer;
System.out.println("Catch the tiger or run away?");
answer = myScanner.next();
if (answer.equals("Catch the tiger" )) {
System.out.println("You've been mauled by a tiger! What were you thinking?");
answer = myScanner.next();
} else {
System.out.println("run away");
}
}
}
Replace:
answer = myScanner.next();
With:
answer = myScanner.nextLine();
next will only read in the next value until it reaches a space or newline. You want to read in the full line before making the comparison
try this :
Scanner scanner = new Scanner(System.in);
int choice = 0;
while (scanner.hasNext()){
if (scanner.hasNextInt()){
choice = scanner.nextInt();
break;
} else {
scanner.next(); // Just discard this, not interested...
}
}
Reference :
Flush/Clear System.in (stdin) before reading
Try this
import java.util.Scanner;
public class MyFirstJavaClass {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner myScanner = new Scanner(System.in);
System.out.println("Catch the tiger or run away?");
if (myScanner.hasNext("Catch the tiger")) {
System.out.println("You've been mauled by a tiger! What were you thinking?");
} else {
System.out.println("run away");
}
}
}

Issue with user input and .equals() in Java

I'm fairly new to java coding but the error is that if I type in the correct answer or the incorrect answer, it still says both Correct and Incorrect.
import java.util.Scanner;
public class MathTest {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
System.out.println("What is 5 times 4? ");
String question;
question = user_input.next();
if (question.equals(20));
System.out.println("Correct!");
if (!"20".equals(question));
System.out.println("Incorrect!");
}
}
Remove the semi-colons from the end of your if statements. It's treated as an empty line.
Or even use explicit curly braces, like if(foo) { bar(); }.
Your conditional if's are a little wrong, this should do it: (untested)
import java.util.Scanner;
public class MathTest {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
System.out.println("What is 5 times 4? ");
String question;
question = user_input.next();
if (question.equals("20"))
System.out.println("Correct!");
if (!"20".equals(question))
System.out.println("Incorrect!");
}
}
In your original code, you had ; at the end of the if's. Which informs the compiler that it's the end of the line. Hence why both "Correct!" and "Incorrect!" were being displayed. AS they weren't part of the conditional statement.
Hope this helps! :)
Find your solutions Brother.......
Tip: for String use "20" instead of 20
public class Solution {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
System.out.println("What is 5 times 4? ");
String question;
question = user_input.next();
if (question.equals("20")){
System.out.println("Correct!");
}else{
System.out.println("Incorrect!");
}
}
}
Semicolon ends the if statement, so the statements below each if will always execute. In addition this: if (question.equals(20)) should be if (question.equals("20")) as the user input is String and you want to compare Strings.
The code should read as follows:
public class MathTest {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
System.out.println("What is 5 times 4? ");
String question;
question = user_input.next();
if (question.equals("20")) {
System.out.println("Correct!");
}
if (!"20".equals(question)) {
System.out.println("Incorrect!");
}
}
}
It is worth mentioning that the Scanner has other methods to read user input, e.g. you can read Integer instead of String like this: Integer answer = answer = user_input.nextInt(); And then you just compare Integers like:
if (answer == 20) {
System.out.println("Correct!");
} else {
System.out.println("Incorrect!");
}
That is because you have a semicolon after the if. Remove it, and preferably put curly braces around the println statements to show which statements belong to the if. Right now, you have written
if (...); a;
Which is equivalent to
if (...)
{
}
a;
While what you meant is
if (...)
{
a;
}
Make it simple
Scanner user_input = new Scanner(System.in);
System.out.println("What is 5 times 4? ");
System.out.println(user_input.next().equals("20") ? "Correct" : "Incorrect");

How to repeat/loop/return to a class

Im a beginner with java and i am following tutorials by Thenewboston on youtube. I wanted to go to a bit more advanced (in my opinion... but not really) things. So heres the code. I want to make it so that it repeats to the beginning so i can enter another number without restarting the program. I believe i have to use the return command but i am not sure where and how to. Thank you!
import java.util.Scanner;
class apples {
public static void main(String args[]) {
Scanner alex = new Scanner(System.in);
Double test;
test = alex.nextDouble();
if (test == 9) {
System.out.println("eat");
} else {
System.out.println("do not eat");
}
}
}
import java.util.Scanner;
class apples{
public static void main(String args[]){
Scanner alex = new Scanner(System.in);
Double test;
while(true) {
test = alex.nextDouble();
if (test == 9){
System.out.println("eat");
}else{
System.out.println("do not eat");
}
}
}
}
like in C or C++ you could use a while statement , askin after the execution is the user want go to exit or not
while (answer){
// ...code...
}
also you could use do..while
do{
// ...code...
}while(condition)
Wrap your code around while loop and use break to come out of loop if your condition is true.
while((alex.hasNext()))
{
test = alex.nextDouble();
if (test == 9){
System.out.println("eat");
break;
}else{
System.out.println("do not eat");
}
}
Something like this:
Double test;
Scanner alex = new Scanner(System.in);
while (alex.hasNextDouble()) {
test = alex.nextDouble();
if (test == 9){
System.out.println("eat");
continue;
}else{
System.out.println("do not eat");
break;
}
}
Note: Assuming all inputs are double, otherwise this program may fail.
This is not perfect example too, because even though you don't say continue while loop iterates. It may be good example for break.

Categories

Resources