Java program appears stuck once while loop is entered - java

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
}

Related

Java and Arrays

I am a beginner programmer and i understand this pseudocode will have many errors, and that is why i came here to ask for help! I know i'm not passing anything i just can't seem to wrap my head around how to get them there. I'm also not sure if while gather input i'm using alter and prompt correctly. In the display function, the spacing is necessary for when it will be displayed. Corrections and explanations are greatly appreciated. Any help would be amazing as i cannot wrap my head around how to formulate this. (NOTE: this is for java)
Instructions for exercise:
Last year, a local college implemented rooftop gardens as a way to promote energy efficiency and save money. Write a program that will allow the user to enter the energy bills from January to June prior to going green. Next, allow the user to enter the energy bills from January to June after going green. The program should calculate the energy difference and display the 6 months’ worth of data, along with the savings.
Hint:
Create 4 global arrays of size 6 each. The first array (notGreenCost) will store the first 6 months of energy costs, the second array (goneGreenCost) will store the 6 months after going green, and the third array (savings) will store the difference. Also, create an array (months) that stores the month names
The pseudocode so far:
//Add statements to declare the global array variables
Declare Real notGreenCost[6]
Declare Real goneGreenCost[6]
Declare Real savings[6]
Declare Real months[6]
Module main()
//Declare local variables
Declare String endProgram = “no”
Call initMonths()
While endProgram == “no”
//Module calls
Call getNotGreen()
Call getGoneGreen()
Call energySaved()
Call displayInfo()
Display “Do you want to end the program (enter yes or no):”
Input endProgram
While endProgram<>”no” AND endProgram<>”yes”
Display “Please enter a value of yes or no: ”
Input endProgram
End While
End While
End Module
Module initMonths()
months = “January”, “February”, “March”, “April”, “May”, “June”
End Module
Module getNotGreen()
//Add statements to retrieve 6 months of info and save to the array
Set counter = 0
For counter < 6
Display “Enter NOT GREEN energy costs for”, months[counter]
Input notGreenCosts[counter]
Set counter = counter + 1
End For
End Module
Module getGoneGreen()
//Add statements to retrieve 6 months of info and save to the array
Set counter = 0
For counter < 6
Input goneGreenCosts[counter]
Set counter = counter + 1
End For
End Module
Module energySaved()
//Add statements to calculate 6 months of savings and save to the array
Set counter = 0
While counter < 6
Set savings[counter] = notGreenCost[counter] – goneGreenCost[counter]
Set counter = counter + 1
End While
End Module
Module displayInfo()
//Add statements to display results as shown above
Set counter = 0
While counter < 6
Display “Information for”, months[counter]
Display “Savings $”, savings[counter]
Display “Not Green Costs $”, notGreenCost[counter]
Display “Gone Green Costs $”, goneGreenCost[counter]
End While
End Module
Perhaps this is what you are looking for
import java.util.Scanner;
class A{
public static int []PriorGreen = new int[6];
public static int []AfterGreen = new int[6];
public static String []month = {"Jan","Feb","Mar","April","May","June"};
static void PriorG()
{
System.out.println(" Enter Cost for Prior Green Month's Below !!!");
Scanner in = new Scanner(System.in);
for(int i=0;i<6;i++){
System.out.println(" Please enter cost for "+month[i]);
PriorGreen[i]=in.nextInt();
}
}
static void AfterG()
{
System.out.println(" Enter Cost for After Green Month's Below !!!");
Scanner in = new Scanner(System.in);
for(int i=0;i<6;i++){
System.out.println(" Please enter cost for "+month[i]);
AfterGreen[i]=in.nextInt();
}
}
static void energySaved()
{
for(int i=0;i<6;i++){
System.out.println(" Energy saved in "+month[i]+" is "+(PriorGreen[i]-AfterGreen[i]));
}
}
static void display()
{
System.out.println("Prior Green "+"After Green "+ "Savings");
for(int i=0;i<6;i++){
System.out.println(PriorGreen[i]+" "+AfterGreen[i]+" "+(PriorGreen[i]-AfterGreen[i]));
}
}
public static void main(String []args)
{
PriorG();
AfterG();
energySaved();
display();
}
}
I see only one small oversight in your pseudocode. In your displayInfo you forgot to increment your counter. You should add Set counter = counter + 1 inside the while loop.
One other thing I notice is that you have a loop that runs the core logic until the user responds "no":
While endProgram == “no” which is not in your requirements. I don't think it's a bad thing necessarily but it would depend on your instructor and whether they would mark you down for that.
I suggest you start writing your Java code and update your post if you run into problems for which you can't find a solution.

While loop doesn't continue even though condition still holds true

I was tasked to create a simulation of a Bank. So far the progress I've made are generating random Client objects, making 4 objects of Teller, putting the Client objects into a circular queue and putting a Client into an empty Teller if there are any.
The problem I have now is that the while loop I made does no continue even though the set condition is still true, it can only execute 5 times. The program still runs though.
This is the code I have so far(assume all variables are declared):
public void run() {
int counter = 1;
populateTellers(windowArray);
while (counter < 10) {
newClient = generateClient();
System.out.println(newClient.toString() + " arrived at :" + counter);
System.out.println();
clientQueue.enqueue(newClient);
clientList.add(newClient);
System.out.println("The Queue now contains " + clientQueue.numberOfOccupiedCells() + " Client(s):");
for (int x = 0; x < clientList.size(); x++) {
System.out.println(clientList.get(x).toString());
}
System.out.println();
arrayIndex = getATeller(windowArray);
if (arrayIndex != -1) {
clientList.remove(0);
clientQueue.dequeue();
windowArray[arrayIndex].setClient(newClient);
windowArray[arrayIndex].setServiceTime(newClient.getDuration());
System.out.println(windowArray[arrayIndex].getName() + " now serves " + newClient.toString());
} else {
for (int x = 0; x < clientList.size(); x++) {
if (windowArrray[arrayIndex].getServiceTime() == counter) {
windowArray[arrayIndex].setClient(new Client());
System.out.println(windowArray[arrayIndex].getName() + " ends service for " + newClient.toString());
}
}
}
counter++;
}
}
The one thing that I can't get head around is that when I remove the code from aI = getATeller(wA); 'till the closing bracket of the if statement below it the program would work. I've tried putting the block into a method, changing the positions of the codes inside if(){} and else{} and changing the condition to if(aI==1), still I got no improvements. Any idea on what I'm doing wrong?
EDIT: So I've been able to narrow it down to a line of code which is windowArray[arrayIndex].setServiceTime(newClient.getDuration());, whenever I assign a value to a Teller's service time the problem would occur, I've checked my Teller class and there was no error there. Any ideas how I can solve this.
Why is it only executing 5 times? According to the code, counter is used as the used to check if it should continue looping for not. The only instance where counter is changed is at last line: counter++.
I can guess that you did a System.out.print on the counter, and it ends up to 5, and it magically stops. Most likely it's throwing an exception, which is not caught, and is lost in the void.
Edit: If this piece of code is being run on another thread, then maybe it's hanging up on some function. Do as told here
Try to find where your loop was turning to infinite loop,
Try writing printing statements, wherever necessary, just to find the flow of execution.
Then printout your variable values, too check whether they were as expected, keep on narrowing your scope as you find error occurred in certain scope, then you will find the culprit, if it is leading you to some other function, then thoroughly check that particular function.

Need help Spotting A logic error in my program (prime numbers) / understanding output

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.

Incrementing a variable within a loop in Java

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.

Java- Saving score in a game

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());

Categories

Resources