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 + ".");
}
Related
I'm trying to print out a baseball players on base percentage. So far, the code is going great. The only issue is that when I'm printing out the OBP for each year, I can't seem to match up the correct year that correlates to the year the user input. Each time it loops in the method printOnBasePercentage() it increments the year by one. Is there a way I can resolve this issue? Thanks.
I've tried adding +startYear++ and that didn't seem to work. It got me closer.
public static void main(String[] args) {
int numYears;
double [] years;
String name;
int startYear;
double oBP;
int hits, walks, sacFlies, hitsByPitch, atBats;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter name of baseball player: ");
name = keyboard.nextLine();
System.out.print("Enter the number of years " + name +" has been playing: ");
numYears = keyboard.nextInt();
years = new double[numYears];
System.out.print("Enter " +name +" first year on the team: ");
startYear = keyboard.nextInt();
for (int index = 0; index < years.length; index++) {
System.out.print("For Year: "+ startYear++);
System.out.print("\nEnter how many hits the player has: ");
hits = keyboard.nextInt();
System.out.print("Enter the number of walks the player has: ");
walks = keyboard.nextInt();
System.out.print("Enter the number of sacrifice flies the player has: ");
sacFlies = keyboard.nextInt();
System.out.print("Enter the number of hits by pitch the player has: ");
hitsByPitch = keyboard.nextInt();
System.out.print("Enter the amount of at bats the player has: ");
atBats = keyboard.nextInt();
years[index] = ((hits + walks + hitsByPitch) / atBats+ walks+ hitsByPitch +sacFlies);
}
printOnBasePercentage(name, startYear, years);
}
public static void printOnBasePercentage(String name, int startYear, double []years){
for (int index = 0; index < years.length; index++){
System.out.println("\n" + name + "'s On Base Percentage");
System.out.printf("For Year: " +startYear + " " + "%.3f", years[index]);
}
}
The problem is you use one changeable variable in the both loops. In the main method you increment startYear variable and after that you pass this changed variable in the printonBasePercentage method. Try to replace this line:
System.out.print("For Year: "+ startYear++);
by:
System.out.print("For Year: "+ startYear + index);
I'm writing a program where at the end I have to display the numbers I entered and the maximum and minimum of those entered numbers. However I'm running into a little problem, here is my code,
import java.util.*;
public class question3controlstructures {
public static void main (String [] args) {
Scanner in = new Scanner (System.in);
int numberEntered;
int numbersinput = 0;
String answer ="";
double sum = 0;
do {
System.out.println("Enter a number");
numberEntered = in.nextInt();
numbersinput ++;
System.out.println("do you want to enter another number?");
answer = in.next();
sum = sum + numberEntered;
} while (answer.equals("yes"));
System.out.println("The sum is: " + sum);
System.out.println("The average is: " + sum/numbersinput);
System.out.println(numberEntered);
}
}
The above comment are absolutely useful. However, here is little code
package com.mars;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Question3controlstructures {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
System.out.print("Enter integers please ");
System.out.println("(EOF or non-integer to terminate): ");
while (scan.hasNextInt()) {
list.add(scan.nextInt());
}
Integer[] nums = list.toArray(new Integer[0]);
int sum = 0;
int i = 0;
for ( ; i < nums.length; i++) {
sum = sum + nums[i];
}
System.out.println("sum..." + sum);
System.out.println("The average is: " + sum / i);
System.out.println(i);
System.out.println("max.. "+Collections.max(list));
System.out.println("min.. "+Collections.min(list));
scan.close();
}
}
As suggent in comments , you need a list to store the multiple numbered entered.
just compare the min and max every time you enter a number
int min = Integer.MAX_VALUE
int max = Integer.MIN_VALUE
int numberEntered;
int numbersinput = 0;
String answer ="";
double sum = 0;
do {
System.out.println("Enter a number");
numberEntered = in.nextInt();
System.out.println("YOU HAVE ENTERED: " + numbersEntered);
if (min > numberEntered) min = numberEntered;
if (max < numberEntered) max = numberEntered;
numbersinput ++;
sum = sum + numberEntered;
System.out.println("do you want to enter another number?");
answer = in.next();
} while (answer.equals("yes"));
System.out.println("The sum is: " + sum);
System.out.println("The average is: " + sum/numbersinput);
System.out.println(numberEntered);
//you can print your min max here.
The IntSummaryStatistics class together with Java 8's Stream API may be less verbose than dealing with min, max, sum and avg calculation manually.
public static void main(String[] args) {
// Get user input.
List<Integer> numbers = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
// No user friendly way to gather user input, improve!
numbers.add(scanner.nextInt());
}
// Transform input to statistics.
IntSummaryStatistics stats = numbers.stream()
.collect(Collectors.summarizingInt(Integer.intValue()));
// Print statistics.
String jointNumbers = numbers.stream()
.collect(Collectors.joining(", "));
System.out.printf("You entered %d numbers: %s\n, stats.getCount(), jointNumbers);
System.out.println("Min: " + stats.getMin());
System.out.println("Max: " + stats.getMax());
System.out.println("Sum: " + stats.getMax());
System.out.println("Avg: " + stats.getAverage());
}
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.
I'm using array and loop, at the first input the user must enter the number of subjects and use the number to be the size of the array. Then on the loop, the program will accept "grades" on each subject.
I need to add those grades.
Please help.
import java.util.Scanner;
public class CaseStudy1 {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
int numsub, grade, sum, ave;
System.out.print("\nEnter number of subjects: ");
numsub = inp.nextInt();
int num[]=new int [numsub];
int y=0;
for(int x=0;x<numsub;x++) {
y=y+1;
System.out.print("\nEnter Grade in Subject [" + y + "] : ");
grade = inp.nextInt();
num[x]=grade;
}
}
}
you alreday got a variable for sum, just add this
sum+=grade;
into your for-loop after
num[x] = grade;
Include another variable called gradsum initialize with 0. Then add grade to gradsum while getting the grade values.
int gradsum = 0;
int y=0;
for(int x=0;x<numsub;x++) {
y=y+1;
System.out.print("\nEnter Grade in Subject [" + y + "] : ");
grade = inp.nextInt();
num[x]=grade;
gradsum +=grade;
}
System.out.print(" Total of the Grade : "+gradsum );
System.out.print(" Average : " + gradsum / numsub );
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...