Random Number Guesser - Cannot Input [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I'm attempting a java challenge in which I guess a random number and the program tells me if it is correct.
However, the program stops at the while loop and tells me I can only input when the program is running:
public class javaChallenge1
{
// Instance variables
int number = 0;
int guess = 0;
boolean gameFinished = false;
// Core variables
Scanner keyboard = new Scanner(System.in);
Random rand = new Random();
public void sampleMethod()
{
number = rand.nextInt(100);
System.out.println("Guess the number generated.");
while (gameFinished = false)
{
guess = keyboard.nextInt();
keyboard.nextLine();
if (guess == number) {
System.out.println("Congrats! You have guessed the number correctly.");
gameFinished = true;
} else {
System.out.println("Bad luck. Try again.");
}
keyboard.nextLine();
}
}
}

The error is on this line:
while(gameFinished = false)
You DO NOT check if the value is false but instead you assign the value false to your variable.
You should write == instead of = to compare values instead of assigning it
while(gameFinished == false)

If you want to compare gameFinished against false, use the == operator:
while (gameFinished == false)
The following will change the value of gameFinished to false, then check if it is true. So the loop stops.
while (gameFinished = false)

In while loop you should put the condition but you assigned the value. so please replace
gameFinished = false
to
gameFinished == false

Related

While statement isn't excuting inside if statement? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am trying to make it print out a range of specified numbers. So if they select option 1 and put in 1 and 15, I want it to print out 1 to 15. Once it gets to the while statement though it just prints nothing.
import java.util.Scanner;
public class Lab4 {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.print("Please choose your choice from the following menu");
System.out.print("\n1) Print through all integer numbers between two given integers");
System.out.print("\n2) Display a right triangular pattern of stars");
System.out.println("\n3) Quit");
int userInput = in.nextInt();
if (userInput == 1) {
System.out.print("Enter the start number: ");
int firstInteger = in.nextInt();
System.out.print("Enter the second number: ");
int secondInteger = in.nextInt();
while (firstInteger < secondInteger);
System.out.print(firstInteger);
firstInteger++;
} else if (userInput == 2) {
System.out.print("Enter the height: ");
int triangleHeight = in.nextInt();
} else if (userInput == 3);{
System.exit(userInput);
}
in.close();
}
}
You should change :
while (firstInteger < secondInteger);
System.out.print(firstInteger);
firstInteger++;
to
while (firstInteger < secondInteger) {
System.out.print(firstInteger);
firstInteger++;
}
while (firstInteger < secondInteger);
This will be treated as two executable lines of instructions,
which is similar like
while (firstInteger < secondInteger)
;
Try to remove the ; after while statement

Can do-while loops only run with boolean variables? Java [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am having some trouble with this small segment. Can do-while loops only run using boolean variables? I am trying to ask the "user" to enter "0" or "1" so that the program will either loop or end.
Error message:
Chapter4Practice.java:23: error: incompatible types: int cannot be
converted to boolean
} while (choice = 1);
^ 1 error
My code:
import java.util.Scanner;
public class Chapter4Practice
{
public static void main(String[] args)
{
int choice, num1, num2;
String input;
Scanner sc = new Scanner(System.in);
do {
System.out.print("Enter a number: ");
num1 = sc.nextInt();
System.out.print("Enter another number: ");
num2 = sc.nextInt();
System.out.println("The sum is " + (num1 + num2));
System.out.println("Do you want to do this again?");
System.out.println("(1 = yes, 0 = no)");
sc.nextLine();
choice = sc.nextInt();
} while (choice = 1);
} //End Main
} //End Class
Short answer: Yes, you can have simple or complex statements inside your do-while but at the end it will have to evaluate to either true or false
Also your statement should be == ( single = means assign, where == is evaluate)

Multiple Choice and True/False Quiz using loops [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm trying to build a quiz for a user that has to have 5 multiple choice questions and 5 true/false questions. I must do this using loops (while loops). I've come to the point where I set up a separate method asking the user the questions and error checking for the true/false or multiple choice questions. I now have to somehow give the user a point if they answer each question correctly. Then in the end, I must give the user the the total amount of points they won. Then I have to ask if they want to play again in the end, if they say yes I have to go back to the first question and restart the game and if they say no the program has to close. Here is where I got to on my main method. I started putting a while loop for the first answer (correct answer being 3) and making a point variable but I'm not sure where to go from there and how to connect everything. I hope what I did so far is correct. Thanks!
UserInteraction input = new UserInteraction();
Questions ask = new Questions();
int answer1 = 0, answer2 = 0, answer3 = 0, answer4 = 0, answer5 = 0;
int a1 = ask.Question1(answer1);
int point;
while (a1==3)
{point = 1;
}
int a2 = ask.Question2(answer2);
int a3 = ask.Question3(answer3);
int a4 = ask.Question4(answer4);
int a5 = ask.Question5(answer5);
boolean answer6=false, answer7=false, answer8=false, answer9=false, answer10=false;
String a6 = ask.Question6(answer6);
String a7 = ask.Question7(answer7);
String a8 = ask.Question8(answer8);
String a9 = ask.Question9(answer9);
String a10 = ask.Question10(answer10);
For the Questions methods, I'll put two blank examples on here.
{public int Question1 (int answer1)
{String message = "";
int smallestValue = 1;
int largestValue = 4;
System.out.println("Q1) What is...?");
System.out.println("1: ....");
System.out.println("2: ......");
System.out.println("3: ......");
System.out.println("4: ......");
System.out.print("Enter the number");
Scanner input = new Scanner(System.in);
UserInteraction input2 = new UserInteraction();
answer1 = input2.getIntValueFromUserBetween(message, smallestValue, largestValue);
return answer1;
}
public String Question6(boolean answer10)
{String message = "";
System.out.println("(Q10) ....(true/false)");
System.out.print("Enter your answer here: ");
Scanner input = new Scanner(System.in);
UserInteraction input2 = new UserInteraction();
answer10 = input2.confirm(message);
return "" + answer10;
}
}
Sorry if I misunderstand your question, but I don't understand why you're using a loop here.
while (a1==3)
Your program is either going to get stuck here or never use it. What I mean is that if the user answers the question correctly (i.e 3), they will be stuck in the while loop until you set a1 != 3.
What I think is a better solution is using selection. For example:
if (a1 == 3) {
point += 1; // point = point + 1
// Or whatever functionality you need here
}
Edit: If you really must use a loop, then having a Boolean flag would be the way to go. For example:
Boolean flag = false;
if (a1 == 3) {
flag = true;
while (flag) {
point += 1; //point = point + 1
// Make sure that you set flag equals to false at the end of the loop though, otherwise it will infinitely loop
// Include any other functionality needed
flag = false;
}
}
Is this similar to what your looking for?
int correct;
public void quiz() { // this is so you can restart quiz easily
String[] answers = String[5];
//add answers to array, set them to variables/constant first then index
String[] questions = String[5];
// add questions to array
for(int i = 0; i <= questions.length; i++) { // stops after all questions have been asked, make sure its "<="
System.out.println(questions[i]); // prints question 1 first loop then 2 and so on
// read input from user
if(input == answers[i]) { // you may have to convert input to correct type
correct += 1;
}
}
}
System.out.println("You got " + correct + " correct answers");
System.out.println("Would you like to play again?");
if(input == yes) {
quiz(); //starts quiz again // starts quiz method again
P.S. sorry if I've misunderstood the question
To ask different questions you can just change the String variables then call quiz() to ask those questions. nice and simple :)

Not able to take user input when using while loop [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have this code bellow which is supposed to take a user input and store it in an array, and I was just wondering why it is not allowing me to input any numbers.
Should the input part be inside the if statement? Also what is the best way to make it work properly?
import java.util.*;
public class fun_with_loops {
static Scanner scan = new Scanner(System.in);
public static void main (String[] args) throws java.io.IOException
{
int[] numbers = new int[10];
int numberSize = 0;
System.out.print("Enter a few numbers please\n");
while (numbers.length < 10)
{
int input = scan.nextInt();
if (input != 0)
{
numbers[numberSize] = input;
numberSize++;
}
else
{
break;
}
}
}
}
Problem
The following expression on loop's control is always evaluated as false:
while (numbers.length < 10)
since array's length is in fact equals 10 as when declared.
Solution
In order to program work as expected you have to use numberSize variable as control:
while (numberSize < 10)
since it grows based on number of inputs.
As Am_I_Helpful stated, you are using a while loop on a value that will not change. I am not sure if the use while is needed in this case. Since you want to loop a specific amount of times you might want to use a for loop. If the amount of times will depend on the size of your array, you could still replace the "10" by your array length (numbers.length).
for (int i; i< 10; i++)
{
int input = scan.nextInt();
if (input != 0)
{
numbers[numberSize] = input;
numberSize++;
}
else
{
break;
}
}
Hoping it helped!
Dan
a short and sweet summary of when to use each loop:
http://mathbits.com/MathBits/CompSci/looping/whichloop.htm
but of course it always depends of your goal while coding so it's sometimes hard to say which is best if you are not the one coding.
Because the array is initialized to size 10, the length will always be 10. A counter variable needs to be used. Here is the code:
static Scanner scan = new Scanner(System.in);
public static void main (String[] args) throws java.io.IOException
{
int[] numbers = new int[10];
System.out.print("Enter a few numbers please\n");
int count = 0;
while (count < 10)
{
int input = scan.nextInt();
if (input != 0)
{
numbers[count] = input;
count++;
}
else
{
break;
}
}
The length property returns the size of the array, not the number of elements that are present in the array. You need to keep track of number of elements in the array on your own.
for(int eleCount = 0; eleCount < 10; eleCount++)
{
int input = scan.nextInt();
if (input != 0)
{
numbers[eleCount] = input;
}
else
{
break;
}
}

Java Program Loop won't Execute and Prompt User? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
Okay so I am only part of the way through my array inventory program, but my while loop that is supposed to prompt a user to re-enter a number when they have entered an invalid one will not execute. When an invalid number is entered the program just ends...I have tried a couple methods and neither are working. this is where i am at now, any ideas??
thanks much!
public class InventorySystem {
public static void main(String[] args) {
String[] newItemInfo = new String[1000];
String[] itemDescription = new String[1000];
int[] itemPrice = new int[1000];
int choice;
boolean isValid;
int itemChoice;
Scanner inputDevice = new Scanner(System.in);
System.out.println("*****Raider Inventory System*****");
System.out.println("1. Enter a new item");
System.out.println("2. View Item Information");
System.out.println("3. View a list of all items");
System.out.println("9. End Program\n");
System.out.println("Please enter your selection: ");
choice = inputDevice.nextInt();
if (choice == 1 || choice == 2 || choice == 3 || choice == 9) {
isValid = true;
} else {
isValid = false;
}
** while (isValid = false) {
System.out.println("Invalid entry, please enter either 1, 2, 3, or 9 for menu options.");
** }
for (int x = 0; x < 1000; ++x) {
if (choice == 1) {
System.out.println("Please enter the name if the item: ");
newItemInfo[x] = inputDevice.nextLine();
System.out.println("Please enter the item description: ");
itemDescription[x] = inputDevice.nextLine();
System.out.println("Please enter item price: ");
itemPrice[x] = inputDevice.nextInt();
}
}
if (choice == 2) {
System.out.println("***Show item Description***");
System.out.println("0. ");
System.out.println("please enter the item number ot view details: ");
itemChoice = inputDevice.nextInt();
}
if (choice == 3) {
System.out.println("****Item List Report****");
}
if (choice == 9) {
System.exit(0);
}
}
}
In your line
while(isValid = false)
the = doesn’t do what you think it does. In Java, a single = means assign the expression on the right side to the variable on the left side. It does not mean to compare the two sides.
So you should rather write this:
while (isValid == false)
Note the double ==. This code works, but you can write it even more beautifully:
while (!isValid)
The ! means not.
Don't do while (isValid = false). You're setting it to false!
Instead do
while (!isValid) {
}
Also, don't do while (isValid == false) -- that's ugly code.
Next, change isValid inside the loop.
while (!isValid) {
// get input from user in here
// test input and check if is valid. If so, set isValid = true;
// something must set isValid to true in here, else it will
// loop forever
}
Otherwise you'll be stuck in an infinite loop. The lesson to be learned here is to mentally walk through your code as if you were running it in your brain. This way you catch logic errors like what you've got.

Categories