Jcreator Voting Program - java

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");
}

Related

Input to array stopped by "quit " word

I need to do Football Results Generator. I created 4 arrays with 10 elements each, but I need to include a loop that allows the user to change their mind and stop input by typing "quit" after a certain number of entries. Could you please help - I am new to programming, so it must be dead simple.
import java.util.Scanner;//
public class Football_Results_Generator
{
public static void main(String[] args)
{
Scanner kbd = new Scanner (System.in);
String[] HomeTeam = new String[10];
String[] AwayTeam = new String[10];
int[] HomeScore = new int[10];
int[] AwayScore = new int[10];
int index = 0;
int sum = 0;
int sum1 = 0;
do
{
System.out.print("Enter Home Team Name: ");
HomeTeam[index] = kbd.nextLine();
System.out.print("Enter Away Team Name: ");
AwayTeam[index] = kbd.nextLine();
System.out.print("Enter Home Team Score:");
HomeScore[index] = kbd.nextInt();
System.out.print("Enter Away Team Score: ");
AwayScore[index] = kbd.nextInt();
kbd.nextLine();
} while(index < 10);
index = 0;
System.out.println();
do
{
System.out.println(HomeTeam[index] + " [" + HomeScore[index] + "]" + " | " + AwayTeam[index] + " [" + AwayScore[index] + "] ");
index = index + 1;
} while(index < 10);
kbd.close();
for(index = 0; index < 10; index++)
sum += HomeScore[index];
for(index = 0; index < 10; index++)
sum1 += AwayScore[index];
System.out.println();
System.out.println("Totals");
System.out.println("-------------------------------");
System.out.println("Total number of matches played: " + index);
System.out.println("Total of all home scores: " + sum);
System.out.println("Total of all away scores: " + sum1);
System.out.println("Total number of draws: ");
System.out.println("The highest home score: ");
System.out.println("The highest away score: ");
}
}
allow user to change his mind and stop input by typing quit after 5 tries.
Use a temp variable to capture String input:
String line;
do
{
System.out.print("Enter Home Team Name: ");
line = kbd.nextLine();
if("quit".equalsIgnoreCase(line)){
break;
}
HomeTeam[index] = line;
.....
index = index + 1; //missed
}while(index < 10);
index = 0;
Here, "quit".equalsIgnoreCase(line) will ensure that irrespctive of case of line e.g. "Quit","QUIT","quit",etc will result true
What about integer input to array?? is it same concept ??
Well, you need to handle the exception in case input is neither quit nor int:
line = kbd.nextLine();
if("quit".equalsIgnoreCase(line)){
break;
}
try{
HomeScore[index] = new Integer(line);
} catch(NumberFormatException e){
//Error conversion string to int
}

Do/while loop not returning to the top?

recently started computer programming and I am stuck on a homework assignment. I created a loop but instead of going back to the top, it starts 1 step ahead of where I intended it to. (it's all listed in the comments I made in the coding. I have been trying to figure this out for the past 6 hours so it would greatly appreciated if someone can help me.
import java.util.Scanner;
import java.text.DecimalFormat;
public class Election
{
public static void main (String[] args)
{
DecimalFormat f = new DecimalFormat("##.00");
DecimalFormat n = new DecimalFormat("##");
float votesForPolly;
float votesForErnest;
float totalPolly = 0;
float totalErnest = 0;
String response;
int precinctsforpolly = 0;
int precinctsforernest = 0;
int precinctsties = 0;
Scanner scan = new Scanner(System.in);
System.out.println ();
System.out.println ("Election Day Vote Counting Program");
System.out.println ();
do
{
//point A
System.out.println("Do you wish to enter more votes? Enter y:n");
response = scan.next();
if (response.equals("y"))
{
//point B
System.out.println("Enter votes for Polly:");
votesForPolly = scan.nextInt();
System.out.println("Enter votes for Ernest:");
votesForErnest = scan.nextInt();
totalPolly = totalPolly + votesForPolly;
totalErnest = totalErnest + votesForErnest;
System.out.println("Do you wish to add precincts? Enter y:n");
response = scan.next();
while (response.equals("y"))
{
System.out.println("How many precincts voted for Polly: ");
precinctsforpolly = scan.nextInt();
System.out.println("How many precincts votes for Ernest: ");
precinctsforernest = scan.nextInt();
System.out.println("How many were ties: ");
precinctsties = scan.nextInt();
break;
//not returning to point A, instead it returns to point B
}
if (response.equals("n"))
{
break;
}
if (response.equals("n"))
{
break;
}
}
}
while (response.equals("n"));
System.out.println("Final Tally");
System.out.println("Polly received:\t " + n.format(totalPolly) + " votes\t" + f.format((totalPolly/(totalPolly + totalErnest))*100) + "%\t" + precinctsforpolly + " precincts");
System.out.println("Ernest received: " + n.format(totalErnest) + " votes\t" + f.format((totalErnest/(totalPolly + totalErnest))*100) + "%\t" + precinctsforernest + " precincts");
System.out.println("\t\t\t\t\t" + precinctsties + " precincts tied");
}
}
My guess is that the string response has already been determine to be y at the end of the loop which is why it skips the first step and jumps right back into the loop assuming my answer is already y.
You will just need to strip your code of unnecessary breaks and also handle the 2 responses differently. Your loop should also continue when the response is y, not the other way round.
See edited code below:
import java.util.Scanner;
import java.text.DecimalFormat;
public class Election
{
public static void main (String[] args)
{
DecimalFormat f = new DecimalFormat("##.00");
DecimalFormat n = new DecimalFormat("##");
float votesForPolly;
float votesForErnest;
float totalPolly = 0;
float totalErnest = 0;
String response;
int precinctsforpolly = 0;
int precinctsforernest = 0;
int precinctsties = 0;
Scanner scan = new Scanner(System.in);
System.out.println ();
System.out.println ("Election Day Vote Counting Program");
System.out.println ();
do
{
//point A
System.out.println("Do you wish to enter more votes? Enter y:n");
response = scan.next();
if (response.equals("y"))
{
//point B
System.out.println("Enter votes for Polly:");
votesForPolly = scan.nextInt();
System.out.println("Enter votes for Ernest:");
votesForErnest = scan.nextInt();
totalPolly = totalPolly + votesForPolly;
totalErnest = totalErnest + votesForErnest;
System.out.println("Do you wish to add precincts? Enter y:n");
String response2 = scan.next();//create a new response variable, so the loop doesn't confuse which response to break on
//I removed the inner loop. If you really intended for this to be an inner loop then the while(response2.equals("y")){} should be around the question, not after
if (response2.equals("y"))
{
System.out.println("How many precincts voted for Polly: ");
precinctsforpolly = scan.nextInt();
System.out.println("How many precincts votes for Ernest: ");
precinctsforernest = scan.nextInt();
System.out.println("How many were ties: ");
precinctsties = scan.nextInt();
}
//removed the unnecessary checks for when response in 'n'
}
}
while (response.equals("y"));
System.out.println("Final Tally");
System.out.println("Polly received:\t " + n.format(totalPolly) + " votes\t" + f.format((totalPolly/(totalPolly + totalErnest))*100) + "%\t" + precinctsforpolly + " precincts");
System.out.println("Ernest received: " + n.format(totalErnest) + " votes\t" + f.format((totalErnest/(totalPolly + totalErnest))*100) + "%\t" + precinctsforernest + " precincts");
System.out.println("\t\t\t\t\t" + precinctsties + " precincts tied");
}
}
if (response.equals("n"))
{
break;
}
breaks your while loop.
You might want to loop again if user's response if 'y'.
In that case, use while (response.equals("y"));
Your requirement is to break out if the user enters "n" but loop while the user input is "y", but your code says,
do{
.....
}while (response.equals("n"));
It should be,
while (response.equals("y"));
do {
//point A
System.out.println("Do you wish to enter more votes? Enter y:n");
response = scan.next();
if (response.equals("y"))
{
//point B
#code
if (response.equals("n")) //<--- this 'if' block will break the loop when response equals 'n'
{
break;
}
}
}
while (response.equals("n"));// <----- this means doing loop when response equals "n"
You can see my comment on above block of code, the loop will do one more time only when response equals 'n'. But when response equals 'n', the 'if' block at above of it will break the loop and the while (response.equals("n")) will be not checked.

Skipping a number in a for loop sequence?

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
}
}

My program has no syntax error but I can't get the final avg # right

My program has no syntax error, I can input all the value, but I just can't get the final average number right. Can anyone help me find out the problem?
The following is what I input:
How many employees do you have? 4
How many days was Employee #1 absent? 4
How many days was Employee #2 absent? 2
How many days was Employee #3 absent? 1
How many days was Employee #4 absent? 3
Final answer should be: 2.5
This is the code I use:
import java.util.Scanner;
class Number {
public static void main(String[] args) {
int numEmployee = Number.workers();
int absentSum = Number.totaldays(numEmployee);
double averageAbsent = Number.average(numEmployee, absentSum);
}
public static int workers() {
int number = 0;
Scanner input = new Scanner(System.in);
while (number > 0 || number < 0 || number == 0) {
System.out.println("How many employees do you have?");
number = input.nextInt();
if (number >= 0) {
return number;
} else {
System.out
.println("You can not enter a negative number."
+ " Please enter another number.");
}
}
return number;
}
public static int totaldays(int numEmployee) {
int absentDays = 0;
int absentSum = 0;
for (int employName = 1; employName <= numEmployee; employName++) {
System.out.println("How many days was Employee #" + employName
+ " absent?");
Scanner input = new Scanner(System.in);
absentDays = input.nextInt();
while (absentDays < 0) {
System.out.println("You can not enter a negative number."
+ " Please enter another number.");
System.out.println("How many days was Employee #" + employName
+ " absent?");
absentDays = input.nextInt();
}
absentSum += absentDays;
}
return absentSum;
}
public static double average(int numEmployee, int absentSum) {
double averageAbsent = (double) absentSum / (double) numEmployee;
System.out.println("Your employees averaged " + averageAbsent
+ " days absent.");
return averageAbsent;
}
}
Move absentSum += absentDays; into the loop body in totaldays. If you restrict the visibility of absentSum then the compiler will tell you that you are accessing it out of scope. Something like
public static int totaldays(int numEmployee) {
int absentSum = 0;
for (int employName = 1; employName <= numEmployee; employName++) {
System.out.println("How many days was Employee #" + employName
+ " absent?");
Scanner input = new Scanner(System.in);
int absentDays = input.nextInt();
while (absentDays < 0) {
System.out.println("You can not enter a negative number."
+ " Please enter another number.");
System.out.println("How many days was Employee #" + employName
+ " absent?");
absentDays = input.nextInt();
}
absentSum += absentDays;
}
// absentSum += absentDays;
return absentSum;
}
With the above output (and your provided input) I get (the requested)
2.5

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