I'm working on a dice game in which I want to allow the user to keep some of their rolls, and then reroll others. I store their first 5 rolls in an array called dieArray and then print the contents of this array, each die being numbered, and then ask the user which die he/she wants to keep, looping one at a time.
The idea was to then add the value of the die that the user chose to keep to a new array that I called keepArray.
My current code for this loop is as follows
while(bool != false){
System.out.print("Would you like to keep a die? y/n: ");
char ch = scanner.next().charAt(0);
if(ch == 'n') {
System.out.println("Exiting----------------------------------------------");
bool = false;
}
else{
System.out.print("Which die number would you like to keep?: ");
int keep = scanner.nextInt();
int i = 0;
keepArray[i] = die.dieArray[keep];
i++;
System.out.println("i value is " + i);
}
}
The issue I am having is that my i within the else statement is not being incremented. I feel that I am not understanding the fundamentals of while loops in Java, because as I see it each time the else loop is accessed, which should be every time the user answers "y" when asked if he/she wants to keep a die, my i should be incremented by 1. Clearly it is not.
Your i variable is being recreated on every round. You need to declare int i = 0; above the loop.
Related
I apologize if this question is uber-simplistic, but I'm still in the early stages of learning Java. I have an example program that calls other methods within the class, and I'm not totally following a few of the elements - hoping someone can clarify. It's a simply random number guessing game and it works fine, but I want to better understand some components. Specifically:
There is a boolean variable (validInput) that is declared but never appears to be used anywhere in the methods
There are 2 methods (askForAnotherRound and getGuess) with a 'while' loop that just has 'true' as the variable(?) - i.e. "while (true)."
This code is directly from the example in the book and, again, it works. I just want to better understand those 2 elements above. (I think the validInput variable is not useful as when I 'comment out' that line the code still executes). I'm curious, though, about the "while (true)" element. There is an option to set, in the askForAnotherRound, to set the return value to false (ending the program). Are boolean methods defaulted to 'true' when they are first executed/called?
Again...understand this is probably a super-simple question for most folks on here, but as a newb I just want to understand this as best I can...
Thanks!!!
// Replicates the number guessing game using 4 separate methods.
import java.util.Scanner;
public class GuessingGameMethod2
{
static Scanner sc = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("Let's play a guessing game!");
do
{
playARound();
}while (askForAnotherRound());
System.out.println("Thanks for playing!");
}
public static void playARound()
{
boolean validInput;
int number, guess;
String answer;
//Pick a Random Number
number = getRandomNumber();
//Get a guess
System.out.println("\nI'm thinking of a number between 1 and 10.");
System.out.print("What do you think it is? ");
guess = getGuess();
//Check the guess
if (guess == number)
System.out.println("You're right!");
else
System.out.println("You're wrong! The number was " + number + ".");
}
public static int getRandomNumber()
{
return (int)(Math.random() * 10) + 1;
}
public static int getGuess()
{
while (true)
{
int guess = sc.nextInt();
if (guess < 1 || guess > 10)
{
System.out.print("I said, between 1 and 10. Try again");
}
else
return guess;
}
}
public static boolean askForAnotherRound()
{
while (true)
{
String answer;
System.out.print("\nPlay again? Y or N: ");
answer = sc.next();
if (answer.equalsIgnoreCase("Y"))
return true;
else if (answer.equalsIgnoreCase("N"))
return false;
}
}
}
I don't see boolean validInput being used either. But if it were to be used somewhere it would probably be to check that you guess satisfies 1 <= guess <= 10.
When it comes to askForAnotherRound and getGuess here's what you should know:
while(true) is always executed. One way you can get out of the while loop is if you use the break statement or if the loop is in a function you can return something. The method askForAnotherRound() will always return either true or false. Depending on the returned value of askForAnotherRound() you will either play another round or not. Note that when you have
`do{
...
someActions()
...
}while(booleanValue)`
someActions() will be executed at least once before it checks for the value of booleanValue which, if it turns out false you'll exit out of the do/while loop. Boolean methods do not default to anything, you have to give them a value.
Hope this helps! I'm also in the process of learning Java right now, so good luck!
As I see you're absolutely true about validInput - it isn't used. May be it will be used in the following chapters.
As for askForAnotherRound() - no, boolean methods don't evalute to true, by default. Even more, Java compiler throw an error if it find a method which does not return value and finish it execution in some cases.
while(true) - it's infinite loop, so it will be executed untill some instruction which interrupts loop, in general it's return statement.
askForAnotherRound() do the following:
- asks user if he/she want to play again
- returns true if user input "Y"
- returns false if user input "Y"
- asks again in all other cases(so it doesn't finish execution) and etc.
Hope it'll help
The validInput is indeed worthless.
The infinite loops are required to read from the console to get a valid input. e.g
while (true)
//start infinite loop
{
int guess = sc.nextInt();
if (guess < 1 || guess > 10)
{
//continue the loop the input is not between 1-10
System.out.print("I said, between 1 and 10. Try again");
}
else
//break out of infinite loop, valid int
return guess;
}
If we take this method without the infinite loop, and i recommend trying this, it will simply return the value read even if it was not valid.
For example.
return sc.nextInt();
will allow any int returned, if we returned anything outside of the bounds in the current impl it would loop again until you enter a value between 1-10
The same is also true for ask for next round, its looping until a valid input is given.
I would bet the next exercises will use the validInput var as both these methods loop until a valid input is given.
You are right about validInput. It is not used. And probably missed after some code change. Should be removed.
while(true) - true is not variable but a boolean constant. It will basically make program run for ever in this case unless somebody kills program. Another alternative would have been to use break to exit out of loop on some condition.
New to programming.
Before you comment: I understand that their are more efficient ways to do this, and already have. I just feel that understanding the process here will make me a better programmer.
Following pseudo code I saw in class. I wrote a program that takes a integer and prints every prime number up to and including the integer(userinput).
This is what I came up with:
//Import Scanner.
import java.util.Scanner;
//Create class.
public class QuestionTwoA2
{
public static void main(String[] args)
{
System.out.println("Enter an integer:"); //Ask for user input.
int userInteger; //Create scanner object and collect user input.
Scanner keyboard = new Scanner(System.in);
userInteger = keyboard.nextInt();
boolean primeFlag = true; //Condition required for prime number loop.
int outer; //I localised these variables outside the loop so that I
int inner; //could test output by printing it.
//Checks natural numbers in between 2 and userInteger.
for (outer = 2; outer < userInteger; outer++)
{
for (inner = 2; inner < outer; inner++)
{
if (outer % inner == 0)
{
primeFlag = false;
//System.out.println(outer + " " + inner);
break;
}
}
if (primeFlag) //I think this statement causes a logic problem.
System.out.println(outer);
}
}
}
I have/had print statements in various parts of my code just to visualise what values I am comparing to get a remainder. My current output is (for any integer input):
Enter an integer:
9
2
3
Logically my code looks fine but obviously doesn't work, help explaining what is actually going on would be much appreciated.
You should put "boolean primeFlag = true;" inside the first for and before the second for.
Since second for is for detecting whether the "outer" variable is a prime number or not, so before going into that you should set your flag true which is your assumption at first, and in second loop when you are checking all smaller values to see whether it is actually prime or not and change the flag if not.
I am working on a project in which I must calculate mortgage. It's supposed to have a loan selection menu in which 1) uses default values to calculate the mortgage. 2) will allow the user to enter in custom values. 3) allows the user to exit the program and have the calculated values displayed. I have a for loop to allow the program to run up to 10 times (it can be less though). I'm currently using a do-while loop to exit the program when 3 is the selection. However it's not exiting. I"m not sure what is wrong and am hoping for an explanation and some tweaks I could implement to ensure it does what it's supposed to.
do
{
int selection = 0;
for(int i=0; i<loanArray.length; i++)
{
System.out.println("Please choose from the following choices below: ");
System.out.println("\t1) Promotional Loan (preset loan amount, rate, term)");
System.out.println("\t2) Unique Loan (enter in loan values)");
System.out.println("\t3) Quit (Exit the program)");
System.out.println("Please enter your selection(1-3): ");
selection = s.nextInt();
if(selection ==1)
{
loanArray[i] = new Mortgage();
System.out.println(loanArray[i].toString());
}
else if (selection ==2)
{
loanArray[i].storeLoanAmount();
loanArray[i].storeInterestRate();
loanArray[i].storeTerm();
System.out.println(loanArray[i].toString());
}
else if(selection == 3)
{
programSelection = false;
programRunning = false;
}
}//end of for array loop
}while (programSelection == true); //end of selection while loop
System.out.println("Exit Test"); //print statement to test if selection screen exited
I haven't actually tested this, but I think the problem is exiting the for loop. The quickest way to test that is just to use a break statement with a label.
outerLoop:
do
// ...
else if(selection == 3)
{
break outerLoop;
}
}//end of for array loop
}while (programSelection == true); //end of selection while loop
Break statements with labels are discussed in the Java tutorial.
Add a break; after the programRunning = false;
you have got the correct the logic the reason is the for loop.
while (programSelection == true)
will only be executed after the for loop. Need to be cautious as well because if the loanArray length is 1 you might think the code works well,actually it doesnt.
I'm having problems tyring to keep score in my "guessing" game. I have to use a for loop or while loop. I have it so 10 random numbers are created in a text file called mystery.txt and a file reader reads these numbers from the text file.
Your score starts at 0. If the user guesses the correct number from the text file they get -10 points. If they get the number wrong they add the the absolute value difference of the number they guessed from a number in the file. The lower the score in the end the better.
When I only run my if else statement once, it works correctly. Once I loop it more than once it starts to act up.
I have to use an if else statement and a for or while loop. Thanks!
Edit- Turns out I have to use a for loop not a while loop, I'm completely lost now.
How it should work:
When you run the program a text file gets generated with 10 different numbers (I already have the code for that ready) The user gets asked to enter a number, the number the user enters gets compared to the first file on the text file. If it is the same never they get -10 points to their score. If they get it wrong they get the difference of the number the guessed and the number in the text file added to the score. This is suppose to repeat ten times.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.Random;
import java.lang.Math;
public class lab4Fall15 {
public static void numberGuessingGame() throws IOException {
Scanner myscnr = new Scanner (System.in);
PrintWriter mywriter = new PrintWriter("mysteryNumber.txt");
int randomNumber;
int i = 0;
i=1;
while (i<=10) {
Random randomGen = new Random();
randomNumber= randomGen.nextInt(11);
// then store (write) it in the file
mywriter.println(randomNumber);
i = i + 1;
}
//Decided to use a loop to generate the numbers-------
mywriter.close();
FileReader fr = new FileReader("./mysteryNumber.txt");
BufferedReader textReader = new BufferedReader(fr);
int numberInFile;
// the number in your file is as follows:
numberInFile = Integer.valueOf(textReader.readLine());
int score= 0;
int a = 1;
while (a<=10) {
a=a+1;
System.out.print ("Please enter a number between 0 and 10: ");
int userNumber= myscnr.nextInt();
if (userNumber==numberInFile){
score = score-10;
}
else{
score = score + Math.abs(userNumber-numberInFile);
}
System.out.println ("current score is: "+score);
}
System.out.println ("your score is "+score);
textReader.close();
}
public static void main(String[] args) throws IOException {
// ...
numberGuessingGame();
}
}
if (userNumber==numberInFile){
score = score-10;
}
I don't understand what you going to mean. but I can guess this. your above code not show any error. normally , you check your , above part of code. you take variable 'numberInFile'. sometime , your file reader take this with 'whitespace or String or e.t.c' . first you check this out put .you put manual data to this variable and check out put. if it work fine , you correct that function.
OK, first, let's just go over for loops, since that's what your question was asking about. From the code you provided, it seems that you already understand while loops, and that's good, because in Java, for loops are (usually) just while loops in disguise. In general, if you have this while loop,
int a = 0;
while (a < 10) {
// do stuff with a
a = a + 1; // or ++a or a++
}
You can always rewrite it like this:
for (int a = 0; a < 10; a = a + 1) {
// do stuff with a
}
By convention (and this convention is useful when you study arrays and Collection types) you'll want to index your loops from 0 rather than 1. Since you're just learning, take my word for it for now. Loop from 0 to n-1, not from 1 to n.
With that out of the way, let's tackle why you're getting the wrong answer (which, incidentally, has nothing at all to do with loops). Rewritten as a for loop, the ask-and-score part of your program looks like this.
for (int a = 0; a < 10; ++a) {
System.out.print ("Please enter a number between 0 and 10: ");
int userNumber = myscnr.nextInt();
if (userNumber == numberInFile){
score = score - 10;
} else {
score = score + Math.abs(userNumber - numberInFile);
}
System.out.println ("current score is: "+score);
}
You will note that nowhere in this section do you update the value of numberInFile. That means that every run of this loop is still looking at whatever value that variable had at the beginning of the loop. That value came from this line:
// the number in your file is as follows:
numberInFile = Integer.valueOf(textReader.readLine());
That line is executed exactly once, before the loop runs. If you want to load the next number every time the user guesses a number, you'll need to move it inside the loop. I'll leave that as an exercise to the reader.
You are not actually capturing the number the user is entering. Try this:
int userNumber = Integer.parseInt(KeyIn.readLine());
This is my first question to this site so I apologize and would appreciate feedback if I post something incorrectly! This is a homework question although I don't seem to be able to tag it that way.
Anyways, the code appears to compile fine (using BlueJ) but gets stuck when it enters the first while loop when I run it. I added some output lines to see where the problem occurs and the first System.out when it enters the first while loop never happens... The JVM just continues working until I force it to reset. I believe my initial while loop should run 4 times then exit with the values I have used (5 students, i starts at 2), but it doesn't appear to do anything at all and I'm at a loss as to what I've done wrong.
Summary of what the program is intended to do when completed.
A series of students walk by a row of lockers.
Student 1 opens all the lockers
Student 2 closes every second locker
Student 3 reverses the state of every third locker, etc. for the number of students
I am aware I haven't set the boolean locker flag to flip properly yet and intend to use a variation of !myBool to do so within the second while loop - but first I want to ensure my while loops work at all. Hoping I'm missing something simple due to staring at it for too long!
import java.util.Arrays;
public class Lockers
{
public static void main (String[]args)
{
// Size of lockerArray
int arraySize = 5;
// Set up new lockerArray
boolean[] lockerArray = new boolean[arraySize];
// Variable for number of students in the exercise
int studentNumber = 5;
System.out.println("Student 1 opens all the lockers.\n");// Outputs, good
// Student 1 opens all the lockers
// Boolean values for lockerArray true = OPEN; false = CLOSED
Arrays.fill(lockerArray, true);
System.out.println(Arrays.toString(lockerArray)); // Outputs 5 true, good
// Set the student counter at 2 (Student 1 has already made their pass)
int i = 2;
// Loop until you run out of students
while (i <= studentNumber);
{
System.out.println("Student Number " + i + " is making their pass.\n");// NEVER HAPPENS - have to reset JVM to stop program
// Set up a variable to control the sequence required (i.e., Student 2 every second locker,
// Student 3 every third locker, etc.
int j = i;
while (j <= arraySize);
{
System.out.println("Student is changing the status of locker number " + j + ".\n");
// Reverse the flag at each locker for which the statement is true for this student number
// Need to reduce the variable by 1 as locker 1 would be sitting in lockerArray[0] position
lockerArray[j-1] = false;
// Increment locker number by the value of the student in the sequence
j = j + i;
}
// Increment the student count
i++;
}
// Print the final array status
System.out.println(Arrays.toString(lockerArray));
}
}
Your while loops have semi-colons after them.
while (i <= studentNumber);
This is causing the infinite loop, since your i variable can't change.
You need brackets around your while loop unless it will run infinitely
Try This:
while (i <= studentNumber){
// action
}