+ 2

Java While Loop Number Guessing Program

Please Find my error if my answer is right,there is no error.If my answer is wrong, it says Exception in thread "main" java etc... I don't understand what it says please help me 😭 import java.util.Scanner; public class Program { // Can u guess a number public static void main(String[] args) { int a = 0, answer = 7; Scanner sc = new Scanner(System.in); while (a != answer){ a=sc.nextInt(); System.out.println("Enter Number"+ a); if (a==answer) System.out.println("You are Right"); else{ System.out.println("You are Wrong"); if(a<answer) System.out.println("Too Low"); else System.out.println("Too High"); } } } }

19th Jul 2023, 5:03 PM
Kaung Myo Htet
Kaung Myo Htet - avatar
7 odpowiedzi
+ 3
Kaung Myo Htet add a return at or near the bottom like this // approximately line 26 <- return ; } } } // still line 29 <- After I did this in your code the error stopped and worked correctly telling me the answer was either too low or too high
20th Jul 2023, 2:32 AM
BroFar
BroFar - avatar
+ 5
/* By putting return ; you can not run loop repeatedly, you can enter value single time only.. so there is no need to use loop then. Like this : */ import java.util.Scanner; public class Program { // Can u guess a number public static void main(String[] args) { int a = 0, answer = 7; Scanner sc = new Scanner(System.in); a=sc.nextInt(); System.out.println("Enter Number"+ a); if (a==answer) System.out.println("You are Right"); else{ System.out.println("You are Wrong"); if(a<answer) System.out.println("Too Low"); else System.out.println("Too High"); } } }
20th Jul 2023, 3:34 AM
Jayakrishna 🇮🇳
+ 4
Put your code in a script on sololearn playground and link it. DO NOT paste the code into the description.
19th Jul 2023, 5:16 PM
Lisa
Lisa - avatar
+ 3
Save code as java file then from 3 dots graph like same as top left corner symbol in this thread, select share option or copy to clip board then paste link here. Your code have no error but it asks input values until a!=answer is false so until you enter 7 , the loop runs. If you don't enter any value then you see error "Exception in thread.... " If you entering single value then don't use while loop.. Hope it helps...
19th Jul 2023, 6:01 PM
Jayakrishna 🇮🇳
+ 3
It works🥹 tysm
20th Jul 2023, 2:40 AM
Kaung Myo Htet
Kaung Myo Htet - avatar
20th Jul 2023, 12:17 AM
Kaung Myo Htet
Kaung Myo Htet - avatar
0
Please tell me how to put my code 🥹
19th Jul 2023, 5:39 PM
Kaung Myo Htet
Kaung Myo Htet - avatar