Home > Enterprise >  The amount of items in the store Java
The amount of items in the store Java

Time:05-31

I'm learning programming in Java, and I found one interesting example and solved it 80%. But there is this part that I don’t know exactly how to solve. I should enter an array indefinitely until I write "0" and then that array should break that array and add the sum of the numbers (but it is necessary that the decimals of the numbers are not limited, and the final sum at the end that is printed is rounded to 2 decimals .)
At the same time, I want to delete this part "Enter the number of purchased items: " where he asks how many items I will have, but only to enter without that part and stop collecting the sum.

import java.util.Arrays;
import java.util.Scanner;
public class SumOfElementsOfAnArray {
   public static void main(String args[]){
      System.out.println("Enter the number of purchased items: "); // I want to enter a array without this part
      Scanner s = new Scanner(System.in);
      int size = s.nextInt();
      int myArray[] = new int [size];
      double sum = 0;
      System.out.println("Enter item prices (each separately) :  ");

      for(int i=0; i<size; i  ){
         myArray[i] = s.nextInt();
         sum = sum   myArray[i];
      }
 
      System.out.println("The total bill amount is:"  sum   "$");
   }
}

CodePudding user response:

Use doble and System.out printf, excample:

      double myArray[] = new double [size];
      double sum = 0;
      System.out.println("Enter item prices (each separately) :  ");

      for(int i=0; i<size; i  ){
         myArray[i] = s.nextDouble();
         sum = sum   myArray[i];
      }
      
      System.out.printf("The total bill amount is:%.2f$",sum);
  • Related