I wrote this program to calculate the total number of votes that each person got in an election, and to enter multiple districts. When I try to enter another district the program just prints out the votes received from the first district instead of setting up another poll. What is wrong with it and how do I fix it?
import java.util.Scanner;
public class Election{
public static void main (String[] args){
int votesForPolly = 0; // number of votes for Polly in each precinct
int votesForErnest = 0; // number of votes for Ernest in each precinct
int totalPolly = 0; // running total of votes for Polly
int totalErnest = 0; // running total of votes for Ernest
String response = ""; // answer (y or n) to the "more precincts" question
Scanner scan = new Scanner(System.in);
System.out.println ();
System.out.println ("Election Day Vote Counting Program");
System.out.println ();
// Initializations
// Loop to "process" the votes in each precinct
{
System.out.println ("Enter Votes? Enter Y or N");
response=scan.next().toUpperCase();
if (response.equals("Y")){
response="Yes";
System.out.println ("Enter votes for Polly:");
votesForPolly=scan.nextInt();
totalPolly=totalPolly+ votesForPolly;
System.out.println ("Enter votes for Ernest:");
votesForErnest=scan.nextInt();
totalErnest=totalErnest+ votesForErnest;
System.out.println ("Enter another District? Enter Y or N");
response=scan.next().toUpperCase();
}else{
int count = 0;
while (count == 1){
// Print out the results
}
}
System.out.println ("Total votes for Polly is: " + totalPolly);
System.out.println ("Total votes for Ernest is: " + totalErnest);
}
}
}
Your current looping is broken (because you start with count = 0, therefore while (count == 1) is not entered, I would rewrite it as follows
final String msg = "Enter Votes for District %d?"
+ " Enter Y to continue, N to stop.\n";
// Loop to "process" the votes in each precinct
for (int i = 1;; i++) {
System.out.printf(msg, i);
response = scan.next().toUpperCase();
if (response.startsWith("N")) {
break;
}
System.out.println("Enter votes for Polly: ");
votesForPolly = scan.nextInt();
totalPolly += votesForPolly;
System.out.println("Enter votes for Ernest: ");
votesForErnest = scan.nextInt();
totalErnest += votesForErnest;
}
System.out.printf("Total votes for Polly is: %d\n"
+ totalPolly);
System.out.printf("Total votes for Ernest is: %d\n"
+ totalErnest);
You are not looping through the polling section.
Change
if (response.equals("Y")){
to
while (response.equals("Y")){
and remove the else statement.
Related
I'm Adrian and i'm kinda new to programming, would like to learn more and improve. I was asked to do a grade average exercise and i did this , but i'm stuck at making the code so if you type a number instead of a name the code will return from the last mistake the writer did , like it asks for a name and you put "5". In my code gives an error and have to re-run it. Any tips?
import java.util.*;
import java.math.*;
import java.io.*;
class Grades {
public static void main(String[] args) {
int j = 1;
double sum = 0;
double average;
Scanner keyboard = new Scanner(System.in);
System.out.println("Insert Student's Name");
String name = keyboard.next();
System.out.println("Insert Student's Surname");
String surname = keyboard.next();
System.out.println("Student's name: " + name + " " + surname);
System.out.println("How many Grades?");
int nVotes = keyboard.nextInt();
int[] arrayVotes = new int[nVotes];
System.out.println("Now insert all the grades");
for (int i=0; i<arrayVotes.length; i++) {
System.out.println("Insert the grade " + j);
arrayVotes[i] = keyboard.nextInt();
j++;
}
for (int i=0; i<arrayVotes.length; i++) {
sum += arrayVotes[i];
}
average = sum / arrayVotes.length;
System.out.println("Student's grade average is: " + average);
System.out.println("Does he have a good behaviour? Answer with true or false");
boolean behaviourStudent = keyboard.nextBoolean();
average = !behaviourStudent ? Math.floor(average) : Math.ceil(average);
System.out.println("The grade now is: " + average);
keyboard.close();
}
}
At the heart of any solution for this, it requires a loop, and a condition for resetting.
String result = null;
while (result == null) {
//OUT: Prompt for input
String input = keyboard.next();
if (/* input is valid */) {
result = input; //the loop can now end
} else {
//OUT: state the input was invalid somehow
}
//Since this is a loop, it repeats back at the start of the while
}
//When we reach here, result will be a non-null, valid value
I've left determining whether a given input is valid up to your discretions. That said, you may consider learning about methods next, as you can abstract this prompting/verification into a much simpler line of code in doing so (see: the DRY principle)
There are several ways to do it.
But the best way is to use regex to validate the user input.
Have a look at the below code, you can add other validations as well using regex.
import java.util.Scanner;
class Grades {
public static boolean isAlphabetOnly(String str)
{
return (str.matches("^[a-zA-Z]*$"));
}
public static void main(String[] args) {
int j = 1;
double sum = 0;
double average;
Scanner keyboard = new Scanner(System.in);
System.out.println("Insert Student's Name");
String name = keyboard.next();
if(!isAlphabetOnly(name)){
System.out.println("Please enter alfabets only");
return;
}
System.out.println("Insert Student's Surname");
String surname = keyboard.next();
System.out.println("Student's name: " + name + " " + surname);
System.out.println("How many Grades?");
int nVotes = keyboard.nextInt();
int[] arrayVotes = new int[nVotes];
System.out.println("Now insert all the grades");
for (int i=0; i<arrayVotes.length; i++) {
System.out.println("Insert the grade " + j);
arrayVotes[i] = keyboard.nextInt();
j++;
}
for (int i=0; i<arrayVotes.length; i++) {
sum += arrayVotes[i];
}
average = sum / arrayVotes.length;
System.out.println("Student's grade average is: " + average);
System.out.println("Does he have a good behaviour? Answer with true or false");
boolean behaviourStudent = keyboard.nextBoolean();
average = !behaviourStudent ? Math.floor(average) : Math.ceil(average);
System.out.println("The grade now is: " + average);
keyboard.close();
}
}
I'm trying to set up a program where the user(student) inputs how many courses they have left to graduate and and how many classes the intend to take per terms and the program will form this data into an array and print out how many terms they have left. The user is not allowed to take more than 5 courses per term so I want to prompt the user that the number they input is incorrect while also looping that input for that specific student without have to close the console and re-run the program. I've tried placing a while(true){} loop there in order to loop it but i can't seem to get the loop i desire.
I've tried placing the while(true){} loop in multiple spots of the code and can't get the desired result.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[][] students = new int[10][2];
for (int i = 0; i < students.length; i++) {
System.out.println("Enter classes remaining and taking each term for student " + (i + 1) + ": ");
for (int j = 0; j < students[i].length; j++) {
students[i][j] = input.nextInt();
if (students[i][1] > 5)
System.out.println("The number of classes per term for student " + (i + 1) + " is invalid.");
}
}
System.out.println();
for (int i = 0; i < students.length; i++) {
System.out.println("Student " + (i + 1) + " has " + (int) Math.round(students[i][0] / students[i][1]) + " terms left to graduate.");
}
}
I expect the output for the first input to print","The number of class per term for student n is invalid." and repeat the prompt to enter the numbers for that same student n without proceeding to the next student input.
Here is the updated one based on your new comments. You should be good from here, make changes whatever you need.
public class StudentInfo
{
public static int totalStudents = 6;
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int[][] Students = new int[totalStudents][3];
// Student[i][0] will hold the Remaining classes.
// Student[i][1] will hold the Classes per semester and
// Student[i][2] will hold the number of total Semesters to complete all courses.
for (int i = 0; i < totalStudents; i++)
{
System.out.print("\n\nEnter the information for " + (i + 1) + "-th student.");
System.out.print("\n\nEnter the total number of remaining courses: ");
Students[i][0] = input.nextInt();
System.out.print("\nEnter the total number of courses per semester: ");
Students[i][1] = input.nextInt();
while (Students[i][1] > 5)
{
System.out.println("\nStudents are not allowed to take more than 5 classes per semester.");
System.out.print("Enter the total number of courses per semester: ");
Students[i][1] = input.nextInt();
}
int ts = Students[i][0] / Students[i][1];
if (Students[i][0] % Students[i][1] != 0)
ts++;
Students[i][2] = ts;
System.out.println("\nThis student needs a total of " + ts + " semesters to finish all courses.");
}
input.close();
}
}
public static void main(String[] args) {
//scanner library
Scanner input = new Scanner (System.in);
//Initialize array
int[][] students = new int [10][2];
//iterate scanner and condition loop
for(int i=0; i<students.length; i++){
System.out.print("Enter classes remaining and taking each term for student "+ (i+1) +": ");
for (int j=0; j<students[i].length;j++){
students[i][j]= input.nextInt();
}
while(students [i][1] > 5) {
System.out.println("The number of classes per term for student " + (i+1) + " is invalid.");
i--;
break;
}
}
System.out.println();
//Print out results compiled from array
for(int i =0; i<students.length; i++) {
System.out.println("Student "+(i+1)+" has "+ (int) Math.ceil((double)students[i][0]/students[i][1]) + " terms left to graduate.");
}
}
How can I make it so the there will be the same number of questions as the user inputs the number of jobs. For example, lets say you had worked in 5 jobs, I want the program to ask the user to ask,
Your salary for job 1
Job 2
Job 3
Job 4
Job 5, and so on. My code right now is.
import java.util.Scanner;
public class Personal_Info {
public static void main(String[] args) {
Scanner Scanner = new Scanner(System.in);
int Salary1;
int Salary2;
int Salary3;
int TotalJobs;
int Average;
String Name;
int Largest;
int Smallest;
int Sum;
System.out.print("What is your first name?: ");
Name = Scanner.nextLine();
System.out.print("How many jobs have you had?: ");
TotalJobs = Scanner.nextInt();
System.out.print("Enter income from job #1: ");
Salary1 = Scanner.nextInt();
System.out.print("Enter income from job #3: ");
Salary2 = Scanner.nextInt();
System.out.print("Enter income from job #3: ");
Salary3 = Scanner.nextInt();
Sum = Salary1 + Salary2 + Salary3;
Average = Sum / TotalJobs;
Largest = Salary1;
Smallest = Salary1;
if(Salary2 > Largest)
Largest = Salary2;
if(Salary3 > Largest)
Largest = Salary3;
if(Salary2 < Smallest)
Smallest = Salary2;
if (Salary3 < Smallest)
Smallest = Salary3;
System.out.println("Hello " + Name + "You've had " + TotalJobs + " jobs. " + "The highest paying job paid is " + Largest + ". The lowest paying job paid is "+ Smallest + ". The average is " + Average + ".");
but it wouldn't work cause it'll only ask the user three times, job 1, 2, and 3.
If I try,
for (int x = 0; x<TotalJobs; x++){
System.out.print("How many jobs have you had?: ");
number = Scanner.nextInt();
I don't know how to get the highest/smallest/average from that stored value which would be 'number'.
Hope this will help You
class SalaryCalculate{
public static void main(String args[]){
int totalJobs,jobcounter,maxSalary,minSalary,averageSalary=0;;
int[] jobsincome;
String name;
Scanner sc= new Scanner(System.in);
System.out.println("Enter your name");
name=sc.nextLine();
System.out.println("How many jobs you had");
totalJobs= sc.nextInt();
jobsincome= new int[totalJobs];
for(int i=0;i<totalJobs;i++){
jobcounter=i+1;
System.out.println("Enter the income for your job "+jobcounter);
jobsincome[i]=sc.nextInt();
averageSalary=averageSalary+jobsincome[i];
}
jobsincome=average(jobsincome);
maxSalary=jobsincome[totalJobs-1];
minSalary=jobsincome[0];
averageSalary=averageSalary/totalJobs;
System.out.println("Hi "+name+" your min salary is "+minSalary+" max salary is "+maxSalary+" average salary is "+averageSalary);
}
public static int[] average(int jobsincome[]){
int length=jobsincome.length;
for(int i=0;i<length;i++){
for(int j=i+1;j<length;j++){
if(jobsincome[i]>jobsincome[j]){
int temp=jobsincome[j];
jobsincome[j]=jobsincome[i];
jobsincome[i]=temp;
}
}
}
return jobsincome;
}
}
Use an array.
Also only capitalize classes, not variables
System.out.print("How many jobs have you had?: ");
int totalJobs = scanner.nextInt();
int[] salaries = new int[totalJobs];
// Loop here
// System.out.print("Enter income from job #"+x);
// salaries[x] = scanner.nextInt();
With this list, you can get the length directly and use separate loops for the sum, min, max. Or streams
With the sum and length, find an average
use an integer arraylist to keep salaries and loop through inputs
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
ArrayList<Integer> sallaries = new ArrayList<>();
int TotalJobs;
double average;
String name;
int largest;
int smallest;
System.out.print("What is your first name?: ");
name = input.nextLine();
System.out.print("How many jobs have you had?: ");
TotalJobs = input.nextInt();
for (int i= 0; i<TotalJobs ; i++){
System.out.print("Enter income from job #"+(i+1)+" : ");
sallaries.add(input.nextInt());
}
average = sallaries.stream().mapToInt(Integer::intValue).average().orElse(-1);
largest = Collections.max(sallaries);
smallest = Collections.min(sallaries);
System.out.println("Hello " + name + "You've had " + TotalJobs + " jobs. " + "The highest paying job paid is " + largest + ". The lowest paying job paid is "+ smallest + ". The average is " + average + ".");
}
I have two programs:
Score.java set to do the following:
read scores from the keyboard and print their average.
The scores will be numeric and may include a decimal part.
For example a score might be 8.73 or some such. Different contests will have different numbers of judges. It will keep asking for and reading in scores until the user types 'done'. The program will then print the total score, the number of scores and the average score. The program will then prompt the user to see if there are any more contestants. If there are begin prompting for scores again. If there are no more then exit the program." I have it set to stop the program when you enter "N", and set to add future entries to the calculation after entering "Y".
import java.util.Scanner;
// This is the Score program
// Written by me
public class Score
{
public static void main(String args[])
{
Scanner game = new Scanner(System.in);
double num = 0.0;
double sum = 0.0;
int cnt = 0;
while (true)
{
System.out.println("Enter as many non-negative integers as you like ");
System.out.println("one at a time and I will find the average");
System.out.println("Enter done to stop entering numbers");
System.out.print("enter number: ");
String ans = game.next();
while (!ans.equals("done"))
{
num = Double.parseDouble(ans);
sum = sum + num;
cnt = cnt + 1;
System.out.print("enter number: ");
ans = game.next();
}
System.out.println(cnt);
System.out.println(sum);
System.out.println("Total Score " + sum + " count scores " + cnt + " avg score " + sum / cnt);
System.out.println("Enter another contestant (Y/N)?");
String str = game.next();
if (!str.equals("Y"))
break;
}
}
}
While the above process works, I cannot get my second program, Olympic.java, to work properly after typing "Y" to add more scores. Instead, it starts a whole new calculation of average instead of adding to the previous calculations:
import java.util.Scanner;
// This is the Olympic program
// Written by me
public class Olympic
{
public static void main(String args[])
{
Scanner game = new Scanner(System.in);
double num = 0.0;
double sum = 0.0;
int cnt = 0;
double highscore = Double.MAX_VALUE;
double lowscore = Double.MIN_VALUE;
while (true)
{
System.out.println("Enter as many non-negative integers as you like ");
System.out.println("one at a time and I will find the average");
System.out.println("Enter done to stop entering numbers");
System.out.print("enter number: ");
String ans = game.next();
lowscore = game.nextDouble();
highscore = game.nextDouble();
while (!ans.equals("done"))
{
num = Double.parseDouble(ans);
sum = (sum + num) - lowscore - highscore;
cnt = cnt + 1;
System.out.print("enter number: ");
if (num > highscore)
{
highscore = num;
}
if (num < lowscore)
{
lowscore = num;
}
ans = game.next();
}
System.out.println("Throwing out low score " + lowscore + " and high score " + highscore);
System.out.println("Total Score " + sum + " count scores " + cnt + " avg score " + sum / cnt);
System.out.println("Enter another contestant (Y/N)?");
String str = game.next();
if (!str.equals("Y"))
break;
}
}
}
So I did a really quick test
public static void main(String[] args) {
Scanner game = new Scanner(System.in);
while (true) {
System.out.println("Enter another contestant (Y/N)?");
String str = game.next();
if (!str.equalsIgnoreCase("Y")) {
break;
}
}
System.out.println("I'm free");
}
And this will exit fine.
As to your second problem. I think your logic is a little skewed. You could try something like...
Scanner game = new Scanner(System.in);
double num = 0;
double sum = 0;
int cnt = 0;
while (true) {
System.out.println("Enter as many non-negative integers as you like ");
System.out.println("one at a time and I will find the average");
System.out.println("Enter done to stop entering numbers");
double lowscore = Double.MAX_VALUE;
double highscore = 0;
System.out.print("enter number: ");
String ans = game.next();
while (!ans.equals("done")) {
num = Double.parseDouble(ans);
lowscore = Math.min(lowscore, num);
highscore = Math.max(highscore, num);
sum += num;
cnt++;
System.out.print("enter number: ");
if (num > highscore) {
highscore = num;
}
if (num < lowscore) {
lowscore = num;
}
ans = game.next();
}
sum -= lowscore;
sum -= highscore;
System.out.println("Throwing out low score " + lowscore + " and high score " + highscore);
System.out.println("Total Score " + sum + " count scores " + cnt + " avg score " + sum / cnt);
System.out.println("Enter another contestant (Y/N)?");
String str = game.next();
if (!str.equalsIgnoreCase("Y")) {
break;
}
}
This will output...
Enter as many non-negative integers as you like
one at a time and I will find the average
Enter done to stop entering numbers
enter number: 1
enter number: 2
enter number: 3
enter number: 4
enter number: 5
enter number: 6
enter number: 7
enter number: 8
enter number: 9
enter number: 10
enter number: done
Throwing out low score 1.0 and high score 10.0
Total Score 44.0 count scores 10 avg score 4.4
Enter another contestant (Y/N)?
y
Enter as many non-negative integers as you like
one at a time and I will find the average
Enter done to stop entering numbers
enter number: 1
enter number: 12
enter number: 13
enter number: 14
enter number: 15
enter number: 16
enter number: 17
enter number: 18
enter number: 19
enter number: 20
enter number: done
Throwing out low score 1.0 and high score 20.0
Total Score 168.0 count scores 20 avg score 8.4
Enter another contestant (Y/N)?
n
As to your exception. When using Scanner.nextDouble, it will throw an exception if the input is not parsable as a double. You will need to deal with this situation as you see fit...
When I enter input that satisfies everything and doesn't trigger any of my errors, the program just exits after last input like it is skipping over the for or if loop.
Also after System.out.printf("Enter the name of your second species: "); it won't allow for any input, it just skips to the next prompt. I'm not sure why that is. The section above it asking for the first species' info works fine.
import java.util.Scanner;
public class HW2johnson_pp1 {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
System.out.printf("Please enter the species with the higher" +
" population first\n");
System.out.printf("Enter the name of your first species: ");
String Species1 = keyboard.nextLine();
System.out.printf("Enter the species' population: ");
int Pop1 = keyboard.nextInt();
System.out.printf("Enter the species' growth rate: ");
int Growth1 = keyboard.nextInt();
System.out.printf("Enter the name of your second species: ");
String Species2 = keyboard.nextLine();
System.out.printf("Enter the species' population: ");
int Pop2 = keyboard.nextInt();
System.out.printf("Enter the species' growth rate: ");
int Growth2 = keyboard.nextInt();
if (Pop2 > Pop1) {
System.out.printf("The first population must be higher. \n");
System.exit(0);
}
Species input1 = new Species();
input1.name = Species1;
input1.population = Pop1;
input1.growthRate = Growth1;
Species input2 = new Species();
input2.name = Species2;
input2.population = Pop2;
input2.growthRate = Growth2;
if ((input1.predictPopulation(1) - input2.predictPopulation(1)) <=
(input1.predictPopulation(2) - input2.predictPopulation(2))){
System.out.printf(Species2 + " will never out-populate " +
Species1 + "\n");
}
else {
for (int i = 0; input2.predictPopulation(i) <=
input1.predictPopulation(i); i++) {
if (input2.predictPopulation(i) == input1.predictPopulation(i)) {
System.out.printf(" will out-populate \n");
}
}
}
}
}
This for the predictPopulation():
public int predictPopulation(int years)
{
int result = 0;
double populationAmount = population;
int count = years;
while ((count > 0) && (populationAmount > 0))
{
populationAmount = (populationAmount +
(growthRate / 100) * populationAmount);
count--;
}
if (populationAmount > 0)
result = (int)populationAmount;
return result;
}
This is because you never print anything after Species 2 overtakes Species 1, except in the very special case that Species 2 and Species 1 have exactly the same population in some year.
This is because, when you enter Species 1's growth rate, you enter an integer, and then press Enter. keyboard.nextInt() swallows the integer, but leaves the newline on the input-buffer, so the subsequent keyboard.nextLine() thinks there's an empty line there waiting for it.