How to add together elements of an Array List - java

So I'm trying to make a cash register program that takes in an array of integer prices and then adds them together to get the total sale price. Here's the snippet of my code that's important
do
{
System.out.print("Enter the integer price: $ ");
int i = in.nextInt();
Prices.add(i);
System.out.println();
}
while(in.hasNextInt());
for(int i=0; i<Prices.size(); i++)
{
int Total = Prices.get(i) + Prices.get(i+1);
}
System.out.println(Total);
My error says "Total cannot be resolved to a variable" and earlier it didn't like when i tried to make the increment in the loop i+2 instead of i++. Can someone help I have no idea how to add together these variables
Is this the right track?
for(int i=0; i<Prices.size(); i++)
{
int Total = 0;
int Total = Total + Prices.get(i);
}

No need of an array or list.
int total = 0;
do
{
System.out.print("Enter the integer price: $ ");
int i = in.nextInt();
total += i;
System.out.println();
}
System.out.println(total);

You're doing 2 things wrong here:
int Total = Prices.get(i) + Prices.get(i+1);
You're declaring Total inside the for loop. Do that outside with a default value of 0. Then you are adding the values of the current iteration and the next iteration. You just want to do Total = Total + Prices.get(i); or Total += Prices.get(i);.
Preferably, you can do it all as you get the values. There's no need for the additional list Prices:
int total = 0;
do
{
System.out.print("Enter the integer price: $ ");
int i = in.nextInt();
total += i;
//prices.add(i);//if you still want to keep the list
System.out.println();
}
while(in.hasNextInt());
System.out.println(total);

You have declared Total in a different scope than you are trying to use it. Additionally the logic in your loop is flawed for summing the prices. Try this:
int Total = 0;
for(int i=0; i<Prices.size(); i++)
{
Total = Total + Prices.get(i);
}
System.out.println(Total);

Related

Subtracting all elements in single array Java

Hi I'm having trouble subtracting one array element to the next element to get the correct answer. The value of the array are given by the user.
Example:
If the user wants to input 3 numbers which are 10, 8, 1
10-8-1 = 1
int numberOT = 0;
int total =0;
System.out.println("Enter Number of times: ");
numberOT =in.nextInt();
int number[] = new int [numberOT];
for(int i = 0; i<numberOT; i++)
{
System.out.println("Enter Number: ");
number[i] = in.nextInt();
}
for(int t =0; t<number.length-1; t++)
{
total = number[t] - number[t+1];
}
System.out.println("total: " + total);
Change the 2nd loop to this:
total = number[0];
for (int i=1; i<number.length; i++) {
total -= number[i];
}
You want to subtract the remaining array items from the first one. Therefore total in the beginning should be equal to the first item and in the loop subtract each consequent (start from the index 1) item from the total.
Remember the number of items in the array must be equal to or larger than 2.
this line is totally wrong : total = number[t] - number[t+1]; as in the last loop
total = number[1] - number[2] which will be equivalent to total = 8 - 1 = 7 which is totally wrong because you have to accumulate the total variable .
so as mentioned above the full correct answer code is :
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int numberOT = 0;
int total =0;
System.out.println("Enter Number of times: ");
numberOT =in.nextInt();
int number[] = new int [numberOT];
for(int i = 0; i<numberOT; i++)
{
System.out.println("Enter Number: ");
number[i] = in.nextInt();
}
total = number[0];
for (int i=1; i<number.length; i++) {
total = total - number[i];
}
System.out.println("total: " + total);
}
}
and here is image of the output:
[][1]
Here is a one liner (computation wise) using streams. Take the first element, stream the array skipping the first element and subtract the sum of the remaining.
int[] arr = { 10, 8, 3, 1 };
int sum = arr[0] - IntStream.of(arr).skip(1).sum();
System.out.println(sum);
But no matter how you do it, you have the potential for int overflow or underflow depending on the size of your values and the length of the array.

For loop print sum of values from array only once, keeps repeating

I am aiming to create a method which prints the total cost of all employees that are added to an array.
Salary is added to the array using:
**Scanner sal = new Scanner(System.in);
System.out.println("Enter annual employee salary $");
int salary = sal.nextInt();
salaryArray[index] = salary;
index++;**
I then use the following to get the sum:
public static void cost()
{
int sum = 0;
for (int i = 0; i < salaryArray.length; ++i)
{
System.out.println(sum += salaryArray[i]);
}
}
The problem is it prints out the result multiple times, I would like it to print only once, giving only one result. Further changes seem to break my code when I try to fix it.
For each salary added you print the current sum.
You want to print the sum after the loop. So do that
As improvement, you could use a more meaningful name for the method as method names should generally start by an infinitive verb.
You could also use an enhanced for as the index variable is only used to iterate every element. The enhanced for provides it in a cleaner way.
public static void displayCost() {
int sum = 0;
for (int salary : salaryArray){
sum += salary;
}
System.out.println(sum);
}
public static void cost()
{
int sum = 0;
for (int i = 0; i < salaryArray.length; ++i)
{
sum += salaryArray[i];
}
System.out.println(sum);
}
Just show sum variable once .
You are printing the result in a for loop, of course it would print multiple times. why not try this;
for(int i = 0; i < salaryArray.length; i++){
sum += salaryArray[i];//getting the value of the sum first
}
System.out.println(sum);

return an integer that has been st inside a for loop

I have to create a method in JAVA where a user define a number, and the method search inside an array how many time this number exists, like this:
int[] age = {21, 23, 21, 29, 18};
If the user enters: 21
The output should be:
21 exist 2 times
I made this code:
public static int numAgeReader(int[] ageToSearch)
{
Scanner scan = new Scanner(System.in);
int n = 0;
int counter=0;
System.out.println("Please enter an age:");
n = scan.nextInt();
//Searching the ages Array to see how many persons have this age
for(int i=0; i<ageToSearch.length; i++)
{
if(n==ageToSearch[i])
counter += counter; //counter = counter + 1
}
return counter;
}
And of course I called it in the main function:
System.out.println(numAgeReader(ages));
Where ages is the array that I previously filled it.
The result is always: 0
EDIT
This method should return an average of an array:
public static double average(int[] ageArray)
{
//double aver=0.0;
int sum = 0;
//Calculating the sum of the age array
for (int i=0; i<ageArray.length; i++)
{
sum = sum + ageArray[i];
}
//Calculating the average:
return(sum/ageArray.length);
//return aver;
}
The result should be sometimes like 25.33 or 18.91, but the returned value is always like this: 25.0 or 19.0 or 89.0
Change
counter += counter;
to
counter++;
Since counter is set to 0 at the beginning, counter += counter; has no effect on the counter variable, hence you'll always get 0 as the return value.
You made a mistake here:
counter += counter;
You probably meant:
counter++;
When you are writing counter += counter you are actually adding 0 to itself every time.
You need to write
counter++ or counter += 1
Try to use this:
counter++;
Instead of counter += counter;

assign different number for array index in Java

I'm trying to assign a different number to the indexes of my array without modifying the array. for example on my code it prints Salesperson 0, Salesperson 1, etc as it gets the index ID of the array in my code. what i'm trying to achieve is that the information of Salesperson 1 be assigned to the index 0 on my array so that it doesn't display as Salesperson 0 on my output.
here is my code.
import java.util.Scanner;
import java.text.NumberFormat;
public class Sales {
public static void main(String[]args)
{
NumberFormat money = NumberFormat.getCurrencyInstance();
//part where program asks how many persons to compute
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number of Salesperson: ");
int SALESPEOPLE = scan.nextInt();
//part where variables are declared
int[] sales = new int[SALESPEOPLE];
int sum;
float ave;
int max_sales=0;
int max_person=0;
int min_sales=0;
int min_person=0;
//part where values for sales are asked and entered
for (int i=0; i<sales.length; i++)
{
System.out.print("Enter sales for salesperson "+i+": ");
sales[i]=scan.nextInt();
//part where sales are compared to find the minimum and maximum sales
if (i == 0)
{
min_sales = sales[i];
max_sales = sales[i];
}
if (sales[i] > max_sales)
{
max_sales = sales[i];
max_person = i;
}
if (sales[i] < min_sales)
{
min_sales=sales[i];
min_person=i;
}
}
System.out.println("\nSalesperson Sales");
System.out.println("----------- --------");
sum=0;
ave=0;
//part where the sales are displayed
for (int i=0; i<sales.length; i++)
{
System.out.println(" "+i+" "+money.format(sales[i]));
sum += sales[i];
ave = sum/SALESPEOPLE;
}
System.out.println("\nTotal sales "+money.format(sum));
System.out.println("Average sales "+money.format(ave));
System.out.println("Salesperson "+min_person+" had the highest sale with "+money.format(min_sales));
System.out.println("Salesperson "+max_person+" had the highest sale with "+money.format(max_sales));
}
}
If I understand correctly, just change what you are printing
System.out.print("Enter sales for salesperson "+(i+1)+": ");
Also, this line
System.out.println(" "+(i+1)+" "+money.format(sales[i]));
Also you duplicate the highest sales string in your output at the end
Other than that, I don't see any problems with your code
You can't change the indexes of an array. But if you want to change the output in a way that you print salesperson0 when you access the 1 index of your array you can just do what Thomas said.
save the array values in another array, swap them
define a rule for the indexes... maybe you could create a function for the array which returns value at index x if you provide index y....

Java - Calculating mean of grades stored in array + printing grades below mean

Beginner Java programmer here. I am trying to make a program that asks the user how many grades they would like to enter. Then, I want to store the grades the user entered into an array. Finally, I want to find the mean of the grades entered and print out a list of every grade below the mean. As of now, my code calculates the mean of the grades that the user enters but I cannot figure out how to print the grades below the mean. I believe the problem lies in my last for loop but I cannot figure out how to fix it. Also, did I implement the array correctly? Thanks to every who took the time to help me!
public static void grades() {
int q = 0;
double grades = 0;
double total = 0;
Scanner in = new Scanner(System.in);
// user input how many grades user would like to enter
System.out.println("How many grades would you like to enter? ");
q = in.nextInt();
// user enters # of grades they requested to enter
for (int counter = 0; counter < q; counter++) {
System.out.println("Enter your grades: ");
grades = in.nextInt();
// This creates an array that stores the grades the user entered
double[] scores = new double[] {grades};
// adds up all elements (grades)
for (int k = 0; k < scores.length; k++) {
total += scores[k]; //sums up entered grades
}
}
total = total / q; //calcs mean
//loops prints grades less than mean
for (grades = 0; grades < total; grades++){
System.out.println(grades);
}
}
public static void grades(){
Scanner in = new Scanner(System.in);
System.out.println("How many grades would you like to enter? "); //user input how many grades user would like to enter
int q = in.nextInt();
double[] grades = new double[q];
double sum = 0;
for (int counter = 0; counter < q; counter++){ //user enters # of grades they requested to enter
System.out.println("Enter your grades: ");
double grade = in.nextInt();
grades[counter] = grade;
sum += grade;
}
double mean = sum / q;
System.out.println("Mean: " + mean);
for (int i = 0; i < q; i++){ //loops prints grades less than mean
if (grades[i] < mean) {
System.out.println(grades[i]);
}
}
}
Your last loop makes no sense
You should be counting through ALL the items in the array and then doing an IF to test if it's below the mean and then printing it if it is below the mean
You have made the loop iterate from 0 up to the mean.. that just makes no sense it's like saying the mean score among a group of students was 30% now print all the grades from student0 to student30 That makes no sense to do that. You should be interested in student 31 and student 32.. dont' stop at student number 30. student1 might have a grade above the mean and student 40 may have a grade below the mean. you're mixing up the student number(the index of the location in the array) with the grade.
ADDED
You are actually doing even worse than that..because grades isn't even an array it is a variable with one number in it. You have an array that increments a variable and prints the variable like printing 1,2,3,4,5
You're meant to do a loop i=1 to n, and print array[i]
You are doing a loop i=1 to n and you are printing i
You should figure out what an array is all about rather than worrying about calculating a mean. Make your own simpler exercises testing what you do/don't understand rather than something out of a book or something the teacher gave you. And use your explorations to understand this exercise your teacher/book gave you.
Your code had some issues. First off your array was being initialized with every iteration for a new grade being entered, which would result in one index since the previous inputs were overriding it. The array scores should be initialized outside the for loop.
Also, your for loop for printing out the grades wasn't correct. You needed to iterate over the scores array and print out each individual value.
The code below works and demonstrates where you went wrong:
public static void grades() {
int q = 0;
double grades = 0;
double total = 0;
Scanner in = new Scanner(System.in);
// user input how many grades user would like to enter
System.out.println("How many grades would you like to enter? ");
q = in.nextInt();
double[] scores = new double[q];//initialize here
// user enters # of grades they requested to enter
for (int i = 0; i < scores.length; i++) {
System.out.println("Enter your grades: ");
grades = in.nextInt();
// This creates an array that stores the grades the user entered
scores[i] = grades;//append values to each index
// adds up all elements (grades)
total += scores[i]; //sums up entered grades
}
total = total / q; //calcs mean
System.out.println("Mean: " + total);
//iterate through the scores array with filled values
for (int i = 0; i < scores.length; i++) {
System.out.println("Grade #" + i + ": " + scores[i]);
}
}
what might be the problem of that .. the total and average is wrong.
import java.io.*;
class overloading2
{
String name;
int year;
String section;
String subject[];
double grade[];
double average;
public void enrolSubjects()throws Exception
{
DataInputStream mat=new DataInputStream(System.in);
try
{
System.out.println("Enter 3 subject:");
subject=new String[3];
for(int sub=0;sub<3;sub++)
{
subject[2]=(mat.readLine());
}
}
catch(IOException ioe)
{
}
}
public double enterGrades(double grade1,double grade2,double grade3)
{
DataInputStream math=new DataInputStream(System.in);
try
{
System.out.println("Enter 3 grades:");
grade=new double[3];
for(int x=0; x<3; x++)
{
grade[2]=Double.parseDouble(math.readLine());
}
}
catch(IOException ioe)
{
}
return enterGrades();
}
double enterGrades()
{
double total=0.0;
for(int x=0; x<3; x++)
{
total+=grade[2];
average=total/3;
}
return average;
}
public static void main(String []args)throws Exception
{
overloading2 ostud1=new overloading2();
double a=0.0,b=0.0,c=0.0;
ostud1.enrolSubjects();
ostud1.enterGrades(a,b,c);
System.out.println("average grade is "+ostud1.enterGrades());
}
}

Categories