Skipping a number in a for loop sequence? - java

so I have another homework question. First, I'll list the instructions and then I'll list my code and hopefully someone can help me/guide me in the right direction.
DIRECTIONS:
Write a program that calculates the occupancy rate for a hotel. The program should start by asking the user how many floors the hotel has. A for loop should then iterate once for each floor. In each iteration of the for loop, the program should ask the user for the number of rooms of the floor and how many of them are occupied. After all of the iterations are complete the program should display how many rooms the hotel has, how many of them are occupied, and the percentage of rooms that are occupied.
It is traditional that many hotels do not have a 13th floor. The for loop in >this program should skip the entire thirteenth loop iteration.
Input validation (remember to use a loop never ever an "if"): Do not accept a value of less than one for the number of floors. Do not accept a value of less than 10 for the number of rooms on a floor.
MY CODE:
import java.util.Scanner;
import java.text.DecimalFormat;
public class Homework7Hotel
{
public static void main (String[] args)
{
Scanner keyboard = new Scanner (System.in);
DecimalFormat formatter = new DecimalFormat("%#,##0.00");
int numFloors = 0;
int numRooms = 0;
int totalRooms = 0;
int numOccupied = 0;
int totalOccupied = 0;
int percentOccupied = 0;
System.out.println("Please enter the number of floors in the hotel: ");
numFloors = keyboard.nextInt();
while (numFloors <1)
{
System.out.println("You have entered an invalid number of floors. ");
System.out.println("Please enter the number of floors in the hotel: ");
numFloors = keyboard.nextInt();
}
for (int counter = 1; counter <=numFloors; counter++)
{
System.out.println("Please enter the number of rooms on floor #: " + counter);
numRooms=keyboard.nextInt();
totalRooms += numRooms;
while (numRooms <10)
{
System.out.println("You have entered an invalid number of rooms. ");
System.out.println("Please enter the number of rooms on floor #: " + counter);
numRooms = keyboard.nextInt();
}
System.out.println("Please enter the number of occupied rooms on floor #: " + counter);
numOccupied = keyboard.nextInt();
totalOccupied += numOccupied;
// *not sure of how to do this* percentOccupied = totalOccupied/totalRooms;
}
System.out.println("The hotel has a total of " + totalRooms + " rooms.");
System.out.println(totalOccupied + " of the rooms are occupied.");
System.out.println (percentOccupied + "% of the rooms are occupied.");
}
}
So, the issue I am having is:
1) As per the instructions, how would I skip the 13th floor entirely in the loop?
Any help would be greatly appreciated! Thank you!

You could use a continue keyword in a forloop like.
for(int i = 0;i <20;i++){
if(i == 13){
continue;
}
//Do rest of your steps
}
If you donot want to use continue use
for(int i = 0;i <20;i++){
if(i != 13){
//Do rest of your steps
}
//This should also work it will not do anything when loop is at its 13th iteration.
}
Using continue though is better.

public static void main (String[] args)
{
Scanner keyboard = new Scanner (System.in);
DecimalFormat formatter = new DecimalFormat("%#,##0.00");
int numFloors = 0;
int numRooms = 0;
int totalRooms = 0;
int numOccupied = 0;
int totalOccupied = 0;
int percentOccupied = 0;
System.out.println("Please enter the number of floors in the hotel: ");
numFloors = keyboard.nextInt();
while (numFloors <1)
{
System.out.println("You have entered an invalid number of floors. ");
System.out.println("Please enter the number of floors in the hotel: ");
numFloors = keyboard.nextInt();
}
for (int counter = 1; counter <=numFloors; counter++)
{
System.out.println("Please enter the number of rooms on floor #: " + counter);
numRooms=keyboard.nextInt();
//REMOVE totalRooms += numRooms; from here
while (numRooms <10)
{
System.out.println("You have entered an invalid number of rooms. ");
System.out.println("Please enter the number of rooms on floor #: " + counter);
numRooms = keyboard.nextInt();
}
totalRooms += numRooms; //ADD it here
System.out.println("Please enter the number of occupied rooms on floor #: " + counter);
numOccupied = keyboard.nextInt();
totalOccupied += numOccupied;
// *not sure of how to do this* percentOccupied = totalOccupied/totalRooms;
}
System.out.println("The hotel has a total of " + totalRooms + " rooms.");
System.out.println(totalOccupied + " of the rooms are occupied.");
System.out.println (percentOccupied + "% of the rooms are occupied.");
}

Without continue, you can try if() else block to do the work.
for(int i = 0; i < 20; i++)
{
if(i == 13)
{
// Do the stuff for 13th floor if any
}
else
{
// Do the stuff for floors other than 13
}
}

Related

Using do-while loop to send an error message when input is out of bounds

Here I am using a do while loop to execute a program that allows the user to score student scores in an array and then print them. I am struggling with implementing a system that sends an error message when the user inputs a number below 0 or above 100 and then lets the user try again.
import java.util.Scanner;
public class storeScore {
public static void main(String [] args) {
Scanner input = new Scanner (System.in);
int scores [] = new int [7];
int numberOfStudents = 7;
//User input all scores. For loop works by asking for user input until it reaches the number as input in numberOfStudents.
do
{
for(int i = 0; i<numberOfStudents; i++) {
scores[i] = input.nextInt();
if (i == 0) {
System.out.print("Enter the score for the 1st student: ");
}
else if (i == 1) {
System.out.print("Enter the score for the 2nd student: ");
}
else if (i == 2) {
System.out.print("Enter the score for the 3rd student: ");
}
else if (i >= 3) {
System.out.print("Enter the score for the " + (i+1) + "th student: ");
}
}
//Error output if input is incorrect
}
while (scores[i] < 0 || scores[i] > 100) {
System.out.println("Input out of bounds. Score can only be between 0 and 100");
}
//Printing all scores.
System.out.println("Thank you for your input. Your entered scores are: ");
for (int i=0; i<numberOfStudents; i++)
{
System.out.print(scores[i] + ", ");
}
input.close();
}
}
You have your error message printing in a while loop without any way of breaking out of that loop.
Try capturing your user's input as an int variable first that you can check to see if it's valid before assigning it to scores[].
for(int i = 0; i<numberOfStudents; i++) {
String message;
if (i == 0) {
message = "Enter the score for the 1st student: ";
}
else if (i == 1) {
message = "Enter the score for the 2nd student: ";
}
else if (i == 2) {
message = "Enter the score for the 3rd student: ";
}
else if (i >= 3) {
message = "Enter the score for the " + (i + 1) + " student: ";
}
System.out.println(message);
int score = input.nextInt();
//Now check if the input value is valid
while (score < 0 || score > 100) {
System.out.println("Input out of bounds. Score can only be between 0 and 100");
System.out.println(message);
score = input.nextInt();
}
score[i] = score;
}
Now, the loop will print the message for student i, then take in the score. If the score is invalid, the while loop will print out the error message, and take input again. If the input is valid this time, the while loop breaks and assigns the new score to student i, otherwise it reprints the error message and takes input again.

Jcreator Voting Program

My teacher wants us to make a program that counts the total number of votes for two candidates from a variable number of precincts. So the user inputs the candidates’ names as strings and is then prompted to enter the number of precincts prior to entering the votes for each precinct. What I am having trouble with is that I have to use an array to keep each precinct's vote total. Then after all of that is done I have to keep a running total of the votes for each candidate after each precinct is completed and who is currently leading and by how much. I have already begun my program but I am honestly just lost as to where to go from here, and I know that what I have in my arrays so far is not correct.
import java.util.*;
public class Voting
{
public static void main (String [] args)
{
Scanner scan = new Scanner(System.in);
int rerun;
int rerun2;
while (rerun == 1)
{
System.out.print("Name of candidate 1: ");
candidate1 = scan.next();
System.out.print("Name of candidate 2: ");
candidate2 = scan.next();
System.out.print("\nPlease enter amount of precincts: ");
presincts = scan.nextInt();
System.out.print("\n Please enter amount of votes for candidate 1: ");
votes1 = scan.nextInt();
System.out.print("\n Please enter amount of votes for candidate 2: ");
votes2 = scan.nextInt();
while (rerun2 == 1 && precincts >= 0 && votes1 >= 0 && votes2 >= 0)
{
int[] votes1 = new int[precincts];
for(int i = 0; i < votes1.length; i++)
{
votes1[i] = int [i];
System.out.println ("\n" + votes1);
}
int[] votes2 = new int[precincts];
for(int i = 0; i < votes2.length; i++)
{
votes2[i] = int [i];
System.out.println ("\n" + votes2);
}
}
}
}
}
I don't know what the function of rerun is so I've left it out of this answer.
First thing you're going to want to do is initialize your variables at the start of your class:
String candidate1;
String candidate2;
int precincts;
int vote1;
int vote2;
int total1;
int total2;
int[] votes1;
int[] votes2;
Note you had a typo in precincts
Then you need to get the name of the candidates and the number of precincts (you've done this correctly already):
Scanner scan = new Scanner(System.in);
System.out.print("Name of candidate 1: ");
candidate1 = scan.next();
System.out.print("Name of candidate 2: ");
candidate2 = scan.next();
System.out.print("\nPlease enter amount of precincts: ");
precincts = scan.nextInt();
Then you need to iterate through the number of precincts, and get the number of votes for each candidate from each precinct. You can do this by initializing an empty array which will keep the votes stored (eg, the votes for the first candidate in precinct 1 will be stored in votes1[0]). Additionally, the easiest way to keep a running total is to use a separate variable total1 and total2:
total1 = 0;
total2 = 0;
votes1 = new int[precincts];
votes2 = new int[precincts];
for (int i = 0; i < precincts; i++) {
System.out.print("\nPlease enter amount of votes for candidate 1 in precinct " + (i + 1) + ": ");
vote1 = scan.nextInt();
votes1[i] = vote1;
total1 = total1 + vote1;
System.out.print("\nPlease enter amount of votes for candidate 2 in precinct " + (i + 1) + ": ");
vote2 = scan.nextInt();
votes2[i] = vote2;
total2 = total2 + vote2;
}
From inside the for loop you can do things like print the current total votes for a candidate:
System.out.println(candidate1 + " has " + total1 + " votes in total");
And print out who is the current leader and by how many votes:
if (total1 > total2) {
System.out.println(candidate1 + " is winning by " + (total1-total2) + " votes");
} else {
System.out.println(candidate2 + " is winning by " + (total2-total1) + " votes");
}

Java scanner - allowing a certain number of ints

Really struggling to find the answer to this.
I'm creating a game where it asks how many players there are and the max number of players the user can enter is 3 (either 1, 2 or 3). Is this creating a for loop or can I just enter a parameter in the scanner function?
Code below:
System.out.println(" How many players are there? ");
int numberOfPlayers = scan.nextInt();
Player[] players = new Player[numberOfPlayers]; //this is where the players scores are stored
int currentPlayer = 0; //because arrays start at 0: +1 is added
for (int i = 0; i < numberOfPlayers; i++) {
System.out.println("What is player " + (i + 1) + " called?");
String playerName = scan.next();
players[i] = new Player(playerName);
You can use Scanner's nextLine() which reads the newline instead of next() as shown below:
System.out.println(" How many players are there? ");
int numberOfPlayers = Integer.parseInt(scan.nextLine());
Player[] players = new Player[numberOfPlayers];
for (int i = 0; i < numberOfPlayers; i++) {
System.out.println("What is player " + (i + 1) + " called?");
String playerName = scan.nextLine();
players[i] = new Player(playerName);
}
I suggest to use Integer.parseInt(scan.nextLine()) with a loop for example :
int numberOfPlayers = 0;
boolean correct = false;
do {
try {
System.out.println(" How many players are there? ");
numberOfPlayers = Integer.parseInt(scan.nextLine());
if (numberOfPlayers >= 1 && numberOfPlayers <= 3) {
correct = true;
}
} catch (NumberFormatException e) {
}
} while (!correct);
So if the user enter incorrect number or a number > 3 or < 1 it will ask the user to enter the number again until the the user enter the correct number 1,2,3

While loop with iteration

I am trying to create a while loop where the user has a total of three tries to enter a valid number. I'm not understanding how the system recognizes that 3 invalid attempts have been made before displaying the message.
Classes, variables, and scanner objects are made. After the three attempts, I want to say "No more tries". I already have the program written to use the user's input for quantity if its valid. This is just if they input three invalid attempts.
Updated code:
int quantity = 0;
// Get user's desired amount of lemonade cups
System.out.print("Hello " + name + ". How many cups of lemonade can I get you? ");
quantity = keyboard.nextInt(); // Store amount of cups wanted
int attempts = 0;
int maxAttempts = 3;
double subTotal = quantity * lemonadeCost;
double totalTax = subTotal * 0.08;
double totalPrice = subTotal + totalTax;
while (attempts < maxAttempts) {
if (quantity < 1 || quantity >= 20) {
System.out.println("That is an invalid amount, please try again");
quantity = keyboard.nextInt(); }
else {
System.out.println("Subtotal: " + defaultFormat.format(subTotal));
System.out.println("Tax: " + defaultFormat.format(totalTax));
System.out.println("Total: " + defaultFormat.format(totalPrice));
}
attempts++;
if (attempts >= 3) {
System.out.print ("No lemonade for you");
break;
}
// Ask for user's payment method
Scanner method = new Scanner(System.in);
System.out.println("How would you like to pay? Enter 'm' for money, 'c' for credit or 'g' for gold. ");
String payment = method.nextLine();
dxdy is correct about the braces required for making the while() loop function.
Once the while loop has ended (either quantity is between 1 and 20, or attempts > maxAttempts), you just need to have an if statement like the following:
if (attempts > maxAttempts) {
System.out.println("No more tries);
return -1; // or something else to break out of your code
}
and then continue on with the rest of your code working with the quantity variable.
You seem to be missing the opening and closing brackets for the loop. As it is, your code reads
while (quantity < 1 || quantity >= 20 && attempts <= maxAttempts)
System.out.println("That is an invalid amount, please try again");
// these below are not part of the loop
quantity = keyboard.nextInt();
attempts++;
Instead you should do
while (quantity < 1 || quantity >= 20 && attempts <= maxAttempts){
System.out.println("That is an invalid amount, please try again");
quantity = keyboard.nextInt();
attempts++;
}
try this code:
//start with 1 since the user will attempt it at least one time.
int attempts = 1;
int maxAttempts = 3;
int quantity=0;
Scanner keyboard = new Scanner(System.in);
//LESS THAN OR EQUAL TO 3...
while(attempts<=maxAttempts){
System.out.print("Enter amount: ");
quantity = keyboard.nextInt();
//check if valid
if(quantity < 1 || quantity >= 20){
//check if it's 1st and 2nd trial.
if(attempts<maxAttempts){
System.out.println("That is an invalid amount, please try again");
}else{
//third trial and still invalid
System.out.print("No more tries");
}
}else{
//user entered a valid amount so let's break the loops.
System.out.println("The amount is valid. Value of amount: "+ quantity);
break;
}
//increment attempts
attempts++;
}
//never forget to close the scanner
keyboard.close();
}
}
Though I could have turned this into methods if it's allowed
EDIT: As you updated the question, so it was necessary to update the answer too. Here it is what you actually want.
public static void main(String[] args) {
// Get user's desired amount of lemonade cups
String name = "Jimmy Nguyen";
Scanner keyboard = new Scanner(System.in);
int quantity;// Store amount of cups wanted
int lemonadeCost = 4; // Suppose
int attempts = 0;
int maxAttempts = 3;
System.out.print("Hello " + name + ". How many cups of lemonade can I get you? ");
while (attempts < maxAttempts) {
quantity = keyboard.nextInt();
if (quantity < 1 || quantity >= 20) {
System.out.println("That is an invalid amount, please try again\n");
++attempts;
} else {
double subTotal = quantity * lemonadeCost;
double totalTax = subTotal * 0.08;
double totalPrice = subTotal + totalTax;
System.out.println("Subtotal: " + subTotal);
System.out.println("Tax: " + totalTax);
System.out.println("Total: " + totalPrice);
// Ask for user's payment method
System.out.println("How would you like to pay? Enter 'm' for money, 'c' for credit or 'g' for gold. ");
keyboard.nextLine();
String payment = keyboard.nextLine();
break;
}
if (attempts >= 3) {
System.out.print("No lemonade for you");
break;
}
}
}

Java - adding value in a while loop

this one just is hurting my brain. http://programmingbydoing.com/a/adding-values-in-a-loop.html
Write a program that gets several integers from the user. Sum up all the integers they give you. Stop looping when they enter a 0. Display the total at the end.
what ive got so far:
Scanner keyboard = new Scanner(System.in);
System.out.println("i will add");
System.out.print("number: ");
int guess = keyboard.nextInt();
System.out.print("number: ");
int guess2 = keyboard.nextInt();
while(guess != 0 && guess2 != 0)
{
int sum = guess + guess2;
System.out.println("the total so far is " + sum);
System.out.print("number: ");
guess = keyboard.nextInt();
System.out.print("number: ");
guess2 = keyboard.nextInt();
System.out.println("the total so far is " + sum);
}
//System.out.println("the total so far is " + (guess + guess2));
}
Declare the int sum variable outside of the while loop and only have one guess = keyboard.nextInt() inside the loop. Add the user's guess to the sum in the loop as well.
Then after the loop output the user's sum.
I.e.:
int sum;
while(guess != 0)
{
guess = keyboard.nextInt();
sum += guess;
}
System.out.println("Total: " + sum");
Edit: also remove the guess2 variable, as you will no longer need it.
The code will be as below :
public static void main(String[] args) throws Exception {
Scanner keyboard = new Scanner(System.in);
int input = 0;
int total = 0;
System.out.println("Start entering the number");
while((input=keyboard.nextInt()) != 0)
{
total = input + total;
}
System.out.println("The program exist because 0 is entered and sum is "+total);
}
Programming by Doing :)
int x = 0;
int sum = 0;
System.out.println("I will add up the numbers you give me.");
System.out.print("Number: ");
x = keyboard.nextInt();
while (x != 0) {
sum = x + sum;
System.out.println("The total so far is " + sum + ".");
System.out.print("Number: ");
x = keyboard.nextInt();
}
System.out.println("\nThe total is " + sum + ".");
import java.util.Scanner;
public class AddingInLoop {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int number, total = 0;
System.out.print("Enter a number\n> ");
number = keyboard.nextInt();
total += number;
while (number != 0) {
System.out.print("Enter another number\n> ");
number = keyboard.nextInt();
total += number;
}
System.out.println("The total is " + total + ".");
}
}
You first prompt the user to enter a number. Then you store that number into total (total += number OR total = total + number). Then, if the number entered wasn't 0, the while loop executes. Every time the user enters a nonzero number, that number is stored in total ( the value in total is getting bigger) and the while loops asks for another number. If and when a user enters 0, the while loop breaks and the program displays the value inside total. :D I myself am a beginner and had a bit of an issue with the logic before figuring it out. Happy coding!

Categories