how do i add 3 salaries using array index? - java

I need help getting total amount for salary using printf statement
numbers/salary i need to add to get total salary;
salary 1: 120000.00
salary 2: 200500.00
salary 3: 175000.50 total
payroll amount is $495501.49
I need help getting total and the code to get the total payroll amount
This is my code:
import java.util.Scanner;
public class LabSeven {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] playerName = new String[3];
Double []dollarSalary= new Double[3];
double sum= 0;
for(int i=0; i<3 ; i++){
System.out.print("Enter player name: ");
playerName[i]=input.next();
System.out.print("Enter Salary: ");
dollarSalary[i]=input.nextDouble();
}
double total= sum + dollarSalary;
System.out.printf("Total payroll amount is: %7.2f\n", sum);
for(int i=0; i<=3; i++) {
System.out.printf(" %s %7.2f\n", playerName[i], dollarSalary[i]);
}
input.close();
}
}

After this line:
dollarSalary[i]=input.nextDouble();
Add this line:
sum += dollarSalary[i];
This way you will be accumulating the sum in the sum variable.
And, delete this line, as you cannot add an array to a double value, this statement made no sense:
double total= sum + dollarSalary;
Finally, you have one more bug, here:
for(int i=0; i<=3; i++) {
The problem is that i will take values 0, 1, 2, 3, but the size of the arrays is 3, so the only valid values are 0, 1, 2. Change the condition to < instead of <=:
for(int i=0; i<3; i++) {
Extra tips
Don't use a Double[]. A double[] is enough for your purpose here
Don't write the number 3 repeatedly. Define a constant, for example private static final PLAYERS_NUMand use this everywhere instead. That way if you want to change the number of players later, you can do it in one place instead of 4
Format your code nicely. Use an IDE like IntelliJ or Eclipse, and use their auto-format features
Putting it together
With the above suggestions applied, your program becomes:
public class LabSeven {
private static final int PLAYERS_NUM = 3;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] playerName = new String[PLAYERS_NUM];
double[] dollarSalary = new double[PLAYERS_NUM];
double totalSalary = 0;
for (int i = 0; i < PLAYERS_NUM; i++) {
System.out.print("Enter player name: ");
playerName[i] = input.next();
System.out.print("Enter Salary: ");
double salary = input.nextDouble();
dollarSalary[i] = salary;
totalSalary += salary;
}
System.out.printf("Total payroll amount is: %7.2f\n", totalSalary);
for (int i = 0; i < PLAYERS_NUM; i++) {
System.out.printf(" %s %7.2f\n", playerName[i], dollarSalary[i]);
}
input.close();
}
}

Use this line in your for-loop and remove your total variable you don't need this.
sum += input.nextDouble();
or
sum += dollarSalary[i];
You can't add an array to a variable like you're doing.

Do something like this to add the salaries from your array. In your for after you add an individual salary to your dollarSalary add it to your sum variable as well.
for(int i=0; i<3 ; i++){
System.out.print("Enter player name: ");
playerName[i]=input.next();
System.out.print("Enter Salary: ");
dollarSalary[i]=input.nextDouble();
sum += dollarSalary[i]
//sum += input.nextDouble(); This expects another input from the user. We should not be doing this.
}
//double total= sum + dollarSalary; You dont need this line anymore
System.out.printf("Total payroll amount is: %7.2f\n", sum);

Related

My arraylist size is a zero even though I've added items to the it

So I tried looking up this error (Exception in thread "main" java.lang.ArithmeticException: / by zero)
and figured that my arraylist size in the code below is zero. I can't understand why it is zero or how to solve it. Does it have to do something with the capacity of the array? I can't seem to figure out what's wrong with my code.
Btw, this code is for computing the average of all the elements in an arraylist and letting the user know what the average is.
I'm still a beginner at Java so I apologize if this may seem silly. Any help is appreciated!
import java.util.*;
public class ClassStuff {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList <Integer> myArray = new ArrayList <Integer> ();
int userInput = 0;
String userConf = "";
while ((!userConf.equalsIgnoreCase("y"))) {
System.out.println("Please enter a number: ");
userInput = scan.nextInt();
for (int i = 1; i <= myArray.size(); i++) {
userInput = scan.nextInt();
myArray.add(userInput);
}
scan.nextLine();
System.out.println("Are you done entering numbers? (y/n): ");
userConf = scan.nextLine();
}
int result = computeAvg(myArray);
System.out.println("Average is: " + result);
}
public static int computeAvg(List <Integer> myArray) {
int sum = 0;
int avg = 0;
for (int i = 0; i < myArray.size(); i++) {
sum = sum + myArray.get(i);
}
return avg = sum/myArray.size();
}
}
I'm assuming the lines:
System.out.println("Please enter a number: ");
userInput = scan.nextInt();
gets the amount of elements you want to add to the arraylist, which we later add to the list through the for loop. In that case keep it in another variable called list_length, since userInput constantly changes in the for loop.
System.out.println("Please enter a number: ");
list_length = scan.nextInt();
Then change the for loop after this input to something like:
for(int i = 1; i <= list_length; i++) {
userInput = scan.nextInt();
myArray.add(userInput);
}
This is because you changed the end of the for loop to myArray.size(), but remember that it was already 0, so the for loop ends since 1 >= 0. What you probably wanted to do was to add list_length amount of numbers into the arraylist
I found your problem.
The problem was your for loop because somehow the arrayList didn't catch any of the elements during the loop.
I also made some adjustment for the method so it counts the average correct.
Here's an example
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList <Integer> myArray = new ArrayList<>();
int userInput = 0;
String userConf = "";
while ((!userConf.equalsIgnoreCase("y"))) {
System.out.println("Please enter a number: ");
userInput = scan.nextInt();
myArray.add(userInput);
scan.nextLine();
System.out.println("Are you done entering numbers? (y/n): ");
userConf = scan.nextLine();
}
System.out.println(myArray);
double result = computeAvg(myArray);
System.out.println("Average is: " + result);
}
public static double computeAvg(List <Integer> myArray) {
double sum = 0;
double avg = 0;
for (int i = 0; i < myArray.size(); i++) {
sum = sum + myArray.get(i);
}
avg = sum / myArray.size();
return avg;
}
Output
myList = [4,5]
average = (4 + 5) / 2 (myArray.size())= 4.5
Hope it was useful!

Some problems with my array

my lecturer give me these question:
1. Write a program that does the following:
a. Get the number of students from user (n)
b. Ask user to enter n grades of n students, store them in an array.
c. Print out the max, the min, and the average of those n grades.
Note: write 3 methods to return the max/min/average element of an array
and use them in this program.
I try to do it, but the output of my program doesn't like what I'd expected.
Here is my code:
package javaapplication2;
import java.util.*;
public class JavaApplication2 {
public static double max(double[]x) {
int i = 0;
int max=0;
for (i=0; i < x.length; i++) {
if (max < x[i]) {
max = i;
}
}
return max;
}
public static double min(double[]y) {
double min = max(y);
for (int i =0; i < y.length; i++) {
if (y[i] < min) {
min = y[i];
}
}return min;
}
public static void main(String[] args) {
String name ="";
String choice;
int times =0;
double score;
Scanner input = new Scanner(System.in);
System.out.println("Enter student's name: ");
name = input.nextLine();
while (name != "exit") {
double grades [] = new double [5000];
System.out.println("Enter student's score: ");
score = Double.parseDouble(input.nextLine());
grades[times] = score;
times += 1;
System.out.println("The max grade is: " + max(grades));
System.out.println("The min grades is: " + min(grades));
System.out.println("Enter student's name: ");
name = input.nextLine();
}
}
}
And here is my output:
Enter student's name:
k
Enter student's score:30
The max grade is: 0.0
The min grades is: 0.0
Enter student's name:
Yah, I dont know why my max grade and min grade is 0.0. Anyone, please help me, thank you !!!
Your problem comes from the grade array s being reassigned each loop
public static void main(String[] args) {
String name ="";
String choice;
int times =0;
double score;
Scanner input = new Scanner(System.in);
System.out.println("Enter student's name: ");
name = input.nextLine();
while (name != "exit") {
//you set the grades array each loop to a new empty array
double grades [] = new double [5000]; //<--- Move this one out
System.out.println("Enter student's score: ");
score = Double.parseDouble(input.nextLine());
grades[times] = score;
times += 1;
System.out.println("The max grade is: " + max(grades));
System.out.println("The min grades is: " + min(grades));
System.out.println("Enter student's name: ");
name = input.nextLine();
}
}
Move it out and then try to get the methods done :)
Edit:
You also have a little error in the max method in regard of the value.
public static double max(double[]x) {
int i = 0;
int max=0;
for (i=0; i < x.length; i++) {
if (max < x[i]) {
max = i; //<-- Not max = i but max = x[i] :)
}
}
return max;
}
In the function where you are calculating max, you should use:
if (max < x[i]) {
max = x[i];
}
As you want to return the element and not it's index. Also you would want to declare your array named grades before the while loop or else it would create a new array on every iteration.
And for improving the code performance:
1. you can in your max/min functions, exit the loop as soon as you encounter a value=0. In your current code the loop iterates 5000 times even if there is a single entry.
2. in your min function instead of doing double min = max(y); you should use double min = Double.MAX_VALUE;. It will prevent the unnecessary calling of the max function.

Java average program with any number of inputs

What I'm trying to make is an averaging program that takes any number of inputs. So far I need to have the user specify how many numbers they want to average, and if they don't give that many numbers the program crashes. Is there any way that I could just have them put as many numbers as they want and afterwards the array length is set?
Here is the code I am using right now:
import java.util.*;
public class Average_any
{
public static void main (String[] args) {
Scanner scan = new Scanner (System.in);
System.out.println ("How many numbers do you want to enter?");
final int ARRAY_LENGTH = scan.nextInt();
System.out.println ("Please type the numbers you want to find the average of, "
+ "and then type \"Done\".");
System.out.println ("Warning: Only type the exact amount of numbers that you specified.");
// If user doesn't enter same number, results in crash
double[] numbers = new double [ARRAY_LENGTH];
do {
for (int i = 0; i < numbers.length; i++) {
while (!scan.hasNextInt()) {
System.out.println("That's not a number!");
scan.next(); //Need this to enter another input
}
numbers[i] = scan.nextInt();
}
} while (!scan.hasNext("Done"));
double total = 0;
for (int i = 0; i < numbers.length; i++) {
total += numbers[i];
}
double average = total/ARRAY_LENGTH;
System.out.println ("Your average is: " + average);
}
}
(Just in case anyone is wondering, no this is not a school assignment, I was just wondering because we did a simpler version in school)
Take the array out of the equation altogether
Scanner scan = new Scanner (System.in);
double total = 0;
int count = 0;
while (scan.hasNextDouble()) {
total += scan.nextDouble();
count ++;
}
double average = total / count;

Build a java app that asks the user to input a series of grades between 0-100

Im extremely new at Java programming and my professor asked us to write a program that can:
Show each grade by the letter. (Ex: A, B, C, D, F)
Show the Minimum & Average grade of the class
Show the number of people who passed the exam (70+ is passing)
I have been trying to use arrays and if else statements to solve this but Im not making much progress. Can you guys please help me out?
I know I'm not good at coding, but here is something I am trying.
I also would like to incorporate if else statements in my code to make things simpler.
Thank you so much in advance.
import java.util.Scanner;
public class HelloWorld
{
public static void main (String[] args)
{
double[] grades = new double[10];
int sum
Scanner scan = new Scanner (System.in);
System.out.println ("Number of students: " + grades.length);
for (int index = 0; index < grades.length; index++)
{
System.out.print ("Enter number " + (index+1) + ": ");
grades[index] = scan.nextDouble();
}
}
}
Finding the minimum value is done by using a for loop just like your current one and using:
min = Math.min(min, grades[index]);
The average can be found just by finding the sum inside the loop:
sum += grades[index];
And then divide by the number of values.
The number of grades 70+ can be found with an if statement inside the loop:
if (grades[index] >= 70) {
numPassing++;
}
Each of these operations can also be done using DoubleStream from Java 8:
double min = Arrays.stream(grades).min().orElse(0.0);
double avg = Arrays.stream(grades).average().orElse(0.0);
long numPassing = Arrays.stream(grades).filter(grade -> grade >= 70).count();
Okay I modified the code a bit, plus I didn't used any functionalities provided in java so that you can understand the flow control and logic as being a newbie to java.
import java.util.Scanner;
public class HelloWorld
{
public static void main (String[] args)
{
double[] marks = new double[10];
char[] grades=new char[10];
int[] numGradeStudent={0,0,0,0,0};
int min=0,avg=0,minIndex=0;
Scanner scan = new Scanner (System.in);
System.out.println ("Number of students: " + grades.length);
for (int index = 0; index < grades.length; index++)
{
//Taking marks then applying grades and counting no. of students
System.out.print ("Enter number " + (index+1) + ": ");
marks[index] = scan.nextDouble();
if(marks[index]>90)
grades[index]='A';
if(marks[index]>75 && marks[index]<=90)
grades[index]='B';
if(marks[index]>65 && marks[index]<=75)
grades[index]='C';
if(marks[index]>55 && marks[index]<=64)
grades[index]='D';
else
grades[index]='E';
//Setting up graded students down from here
if(grades[index]=='A')
numGradeStudent[0]++;
if(grades[index]=='B')
numGradeStudent[1]++;
if(grades[index]=='C')
numGradeStudent[2]++;
if(grades[index]=='D')
numGradeStudent[3]++;
if(grades[index]=='E')
numGradeStudent[4]++;
}
min=numGradeStudent[0];
for(int i=0;i<5;i++){
if(numGradeStudent[i]<min){
min=numGradeStudent[i];
minIndex=i;
}
}
System.out.println("Min grade of class is:"+ grades[minIndex]);
for(int i=0;i<10;i++){
if(marks[i]>70)
System.out.println("Student "+(i+1)+" passed.");
}
}
}

double array won't print

I did some more work on this program, but now I am stuck because the string array prints, but i cant for the life of me get the double array to print. Any help would be appreciated!
import java.util.ArrayList;
import java.util.Arrays;
import java.lang.Double;
import java.util.Scanner;
public class inventoryTracker
{
private static Scanner sc;
private static double itemCost;
public static void main(String[] args)
{
System.out.println("Welcome to the Inventory tracker"
+ "\nThis program will accept the names and costs for 10 stocked items."
+ "\nThe program will then output a table with the names, costs and,"
+ "\nprices of the items."
+ "\nPrices are calculated with a 30 percent markup on cost.");
sc = new Scanner(System.in);
String[] product = new String[10];
Double[] itemCost = new Double[10];
for (int i = 0; i < itemCost.length; i++ ){
System.out.print("Enter the item cost :");
itemCost [i]= sc.nextDouble();
}
for (int i = 0; i < product.length; i++){
System.out.print("Enter the product name :");
product[i] = sc.next();
}
System.out.println(Arrays.toString(product));
}
}
That's because you are assigning a string to a string array in your two for loops.
product= sc.toString();
should be
product[i] = sc.toString();
and the same goes for itemCost.
That's because you are assigning a string to a string array in your two for loops. Also you are doing sc.toString() that is not correct.
product= sc.toString();
and
itemCost= sc.nextDouble();
should be changed to
product[i] = sc.nextLine();
and
itemCost[i] = sc.nextDouble();
and the same goes for itemCost.
You need to use index to set a value like:
product[index] = value;
Also you are using sc.toString() to get string from user. It wont work you need to use next() method to get string from user.
Loop should be like:
for (int i = 0; i < product.length; i++){
System.out.print("Enter the product name :");
product[i] = sc.next();
}
for (int i = 0; i < itemCost.length; i++ ){
System.out.print("Enter the item cost :");
itemCost [i]= sc.nextDouble();
}

Categories