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!
Related
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");
}
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
}
}
import java.util.Scanner;
public class CashRegisterSimulation {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int total = 0 , num;
/*
* Create a program that will ask the user to enter a series of amounts.
* Assume that the user is allowed to enter positive numbers only. If the
* user entered a value of 0, the program will stop asking for numbers and
* should display the sum of the inputs given. Use DO WHILE Loops.
*/
do
{
System.out.print("Enter amount : ");
num = console.nextInt();
if(num <= 0)
{
System.out.println("STOP");
total = total + num;
System.out.println("The total amount is : " + total);
}
} while (num > 0);
}
}
How do I make my program add all the inputs the user entered after entering 0 or negative number?!
You want to add to the sum in each iteration for which num > 0:
do
{
System.out.print("Enter amount : ");
num = console.nextInt();
if(num > 0)
{
total = total + num;
}
} while (num > 0);
System.out.println("STOP");
System.out.println("The total amount is : " + total);
Move your total = total + num; inside an if condition and else print stop and the total. That should print the total if input is <=0.
do
{
System.out.print("Enter amount : ");
num = console.nextInt();
if(num>0)
total = total + num;
else
{
System.out.println("STOP");
System.out.println("The total amount is : " + total);
}
} while (num > 0);
This program's objective is to calculate the n-th Fibonacci number. How do I allow the user to continue entering numbers until they choose to quit? Thanks.
public class FibonacciNUmbers
{
public static int calcFibNum(int x)
{
if (x == 0)
return 0;
else if (x == 1)
return 1;
else
return calcFibNum(x-1) + calcFibNum(x-2);
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("What number would you like to find the Fibonacci number for?");
int x = in.nextInt();
System.out.println("The Fibonacci number of " + x + " is " + calcFibNum(x));
System.out.println("Would you like to find the Fibonaci number of another number?");
String answer = in.next();
if (answer.equalsIgnoreCase("Y"));
{
System.out.println("What number would you like to find the Fibonacci number for?");
x = in.nextInt();
System.out.println("The Fibonacci number for " + x + " is " + calcFibNum(x));
}
else
{
System.out.println();
}
}
}
By the way your code prints all the Fibonacci numbers up to n and not the nth number.Below is just an example of how to keep entering input from Scanner. Use that to build upon what you want to do:
int num = 0;
while (in.hasNextInt()) {
num = in.nextInt();
}
Happy coding!
//start your while loop here
while (true)
{
System.out.println("Would you like to find the Fibonacci number of another number?");
String answer = in.next();
if (answer.equalsIgnoreCase("Y"));
{
System.out.println("What number would you like to find the Fibonacci number for?");
x = in.nextInt();
System.out.println("The Fibonacci number for " + x + " is " + calcFibNum(x));
}
else
{
System.out.println("Thanks for playing");
break; // ends the while loop.
}
}
For loops are used when you can count things or have a set of things. While loops are used when you're not sure how long it might go on for, or if you want it to continue until some event occurs (user pressing a certain letter for example)
Slight variation of the above that is probly a bit more elegant:
String answer = "Y";
//start your while loop here
while (answer.equals("Y")) {
System.out.println("Would you like to find the Fibonacci number of another number?");
answer = in.next(); //declare your variable answer outside the loop so you can use it in the evaluation of how many times to do the loop.
if (answer.equalsIgnoreCase("Y"));
{
System.out.println("What number would you like to find the Fibonacci number for?");
x = in.nextInt();
System.out.println("The Fibonacci number for " + x + " is " + calcFibNum(x));
}
else
{
System.out.println("Thanks for playing");
// no need to break out.
}
}
I'm trying to create this rather simple program for my java class. Everything is working, except for when I tried to have an input loop. I've never done that before, and it's ignoring every other input. Here is the problem prompt:
B. Ch. 4 – Average - Write a program that will read an unspecified number of integer grades and find the summary total and average. Print grades, total and average. The last record will be the trailer record of -1. Also output the final letter grade per syllabus grading scale.
And here is the code:
import java.util.Scanner;
public class Average
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
float counter = 0;
float accum = 0;
float addAccum = 0;
float tempLoop = 0;
System.out.println("Please Enter Grade, Enter -1 to Finish: ");
while (tempLoop != -1)
{
addAccum = in.nextFloat();
counter++;
accum = addAccum + accum;
tempLoop = in.nextFloat();
}
float avgGrade = accum / counter;
if(avgGrade >= 90)
{
System.out.println("\nYour Grade is: " + "A");
}else if(avgGrade >=80)
{
System.out.println("\nYour Grade is: " + "B");
}else if(avgGrade >=70)
{
System.out.println("\nYour Grade is: " + "C");
}else if(avgGrade >=60)
{
System.out.println("\nYour Grade is: " + "D");
}else
{
System.out.println("\nYour Grade is: " + "F");
}
System.out.println("\nGrade Total: " + accum);
System.out.println("\nCounter Num :" + counter); // for testing only
System.out.println("\nAverage Grade: " + avgGrade);
}
}
This is the console input/output:
Please Enter Grade, Enter -1 to Finish:
100
100
100
100
100
100
-1
-1
Your Grade is: C
Grade Total: 299.0
Counter Num :4.0
Average Grade: 74.75
You have in.nextFloat() twice in your while loop.
Change your logic to look for -1 first and then process the input.
Something like :
tempLoop = in.nextFloat();
while(tempLoop != -1){
sum += tempLoop;
tempLoop = in.nextFloat();
}
Hope this helps.
What you're doing is reading twice;
while (tempLoop != -1)
{
addAccum = in.nextFloat(); // Once Here
counter++;
accum = addAccum + accum;
tempLoop = in.nextFloat(); // Again Here
}
Thus only half of the data is being processed;
You'll need to read the first value before entering the loop, and then only read once at the end before checking that the new value is not -1
To avoid reading twice and reading inside the loop, or add ugly break statements, i would do it like this:
while ((addAccum = in.nextFloat()) != -1) {
counter++;
accum = addAccum + accum;
}