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 + "$");
}
}
Example with BigDecimal:
BigDecimal myArray[] = new BigDecimal [size];
BigDecimal sum = new BigDecimal(0);
System.out.println("Enter item prices (each separately) : ");
for(int i=0; i<size; i++){
myArray[i] = s.nextBigDecimal();
sum = sum.add(myArray[i]);
}
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
I'm very new at Java, and somehow my code is not giving me the average, but it doesnt throw me errors, so I dont know where it's wrong.
System.out.println("Please enter the amount of students: ");
Scanner sc = new Scanner(System.in);
int len = sc.nextInt();
int students[] = new int[len];
for (int i = 0; i < students.length; i++) {
System.out.println("Enter the scores from the first examen of the student " + (i + 1) + " ");
students[i] = sc.nextInt();
}
System.out.println("The scores of the students are:" + Arrays.toString(students));
float scores[] = new float[len];
int sumScores = 0;
int count = 0;
for (int i = 0; i < scores.length; i++) {
scores[i] = sc.nextInt();
sumScores += scores[count];
int average = sumScores / len;
System.out.println("The average of all the scores are: " + average);
There are a couples things that don't make sense here. I think we can agree the average is equal to the sum of all elements divided by the number of elements.
In your for loop, you are iterating through the loop and using count as the index, instead of i, which is redundant already, but you also never increment count. So it's also incorrect. So, just use i - that's part of the reason we do a for loop this way instead of for element : list.
// this
sumScores += scores[count]; // this is essentially scores[0] over and over
// should become this
sumScores += scores[i];
Next, move your "summarizing" prints outside of the loops. You don't want to print this every time.
Next tip: call sc.nextLine() after every call to sc.nextInt(), because nextInt() does not consume the newline character.
I was going to give you a working block of code - however it's not clear to me if you want to have one exam per student, or multiple exams, and an average of averages or something. If you're casting to a float I assume you want decimal places - so maybe look up how to do that type conversion without losing precision and decide where the best place to make that cast is. Cheers.
If arrays and loops confuse you, you could also give functional programming a try.
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the amount of students: ");
int len = sc.nextInt();
double average = IntStream.generate(() -> {
System.out.println("Enter the scores from the first examen of the student");
return sc.nextInt();
}).limit(len).average().orElse(0.0);
System.out.println("The average of all the scores are: " + average);
I'm trying to create a program which allows the user to addition as many pairs of numbers as they would like, by first taking user input to ask them how many sums they would like to complete (additions of 2 numbers), thereafter creating 2 arrays of whatever size the user has input, and then asking the user to input each pair of numbers on a single line that they would like to addition and storing the first value in one array and the second value in a second array from each input. This is where I am stuck, I don't know how I can take the user input as two int values on each line and store them in the respective indexes of each array to be added later. Please take a look at my code below:
import java.util.Scanner;
public class SumsInLoop {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the amount of sums you would like to calculate: ");
int n = sc.nextInt();
int a[] = new int[n];
int b[] = new int[n];
String[] input = new String[2];
System.out.println("Please enter the values you would like to sum as pairs of two numbers: ");
for (int i = 0; i < a.length; i++) {
input = sc.nextLine().split(" ");
int[] intinput = Arrays.asList(input).stream().mapToInt(Integer::parseInt).toArray();
a = intinput[0];
b = intinput[1];
}
}
I think you need to change 2 lines this way:
a[i] = intinput[0];
b[i] = intinput[1];
You're using nextLine() method, which is useful for string input, but it's not the best solution for integer or other primitive data.
In addition, this line of code is wrong :
a = intinput[0];
because you're storing an integer value as integer array.
You must store that value inside a[i] in order to respect the variables type.
I'd do it this way:
public class SumsInLoop {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the amount of sums you would like to calculate: ");
int n = sc.nextInt();
int a[] = new int[n];
int b[] = new int[n];
for (int i = 0; i < a.length; i++) {
System.out.println("Please enter the values you would like to sum as pairs of two numbers: ");
// Read pair and store it inside i-th position of a and b arrays
System.out.println("Enter first number: ");
a[i] = sc.nextInt();
System.out.println("Enter second number: ");
b[i] = sc.nextInt();
}
// Close scanner
sc.close();
// Prints every sum
for(int i = 0; i < a.length; i++){
System.out.println(i + "-th sum is: " + (a[i] + b[i]));
}
}
}
Here you read every pair with nextInt() which is specific for integer data.
Every time you store items in i-th position of arrays, so finally you can sum a[i] and b[i].
Result example:
Enter the amount of sums you would like to calculate:
4
Please enter the values you would like to sum as pairs of two numbers:
Enter first number:
2
Enter second number:
1
Please enter the values you would like to sum as pairs of two numbers:
Enter first number:
3
Enter second number:
4
Please enter the values you would like to sum as pairs of two numbers:
Enter first number:
5
Enter second number:
6
Please enter the values you would like to sum as pairs of two numbers:
Enter first number:
7
Enter second number:
8
0-th sum is: 3
1-th sum is: 7
2-th sum is: 11
3-th sum is: 15
Just read pairs with nextInt() method of scanner, it's use all space symbols like separator (not only end of line):
public class SumsInLoop {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the amount of sums you would like to calculate: ");
int n = sc.nextInt();
int a[] = new int[n];
int b[] = new int[n];
System.out.println("Please enter the values you would like to sum as pairs of two numbers: ");
for (int i = 0; i < a.length; i++) {
a[i] = sc.nextInt();
b[i] = sc.nextInt();
}
}
}
This is one of my very first java projects and I'm trying to make a mini calculator and right now I'm working on addition.
What I want it to do is like it will ask the user how many numbers they want to add and then after you type all the numbers, and the java code has to get all the numbers that inputted.
Here's the addition part that doesn't work so far:
private static void Addition() { //I already added the Scanner plugin
System.out.println("How many numbers would you like to add?");
Scanner adds = new Scanner(System.in);
int addsput = adds.nextInt();
Scanner numa = new Scanner(System.in);
for(int addloop=1; addloop>addsput; addloop++) {
int numaput = adds.nextInt();
//somehow I want to get all the numbers
}
//Here I want to add all the numbers they typed
}
So I hope you get the idea. Any help would be great, because I've been searching for about an hour to get this figured out. Thanks.
You have two options, either read the values into an array, or find the sum as you read the values.
You only need one Scanner object, and your for loop had some issues:
private static void addition() {
Scanner input = new Scanner(System.in);
System.out.println("How many numbers would you like to add?");
int amountNumbers = input.nextInt();
int sum = 0;
for (int counter = 0; counter < amountNumbers; counter++) {
sum += input.nextInt();
}
System.out.println("Sum: " + sum);
}
Using an array:
private static void addition() {
Scanner input = new Scanner(System.in);
System.out.println("How many numbers would you like to add?");
int[] numbers = new int[input.nextInt()];
for (int index = 0; index < numbers.length; index++) {
numbers[index] = input.nextInt();
}
int sum = 0;
for (int index = 0; index < numbers.length; index++) {
sum += numbers[index];
}
System.out.println("Sum: " + sum);
}
Here is a more advanced way to do it using IntStream from Java 8:
private static void addition() {
Scanner input = new Scanner(System.in);
System.out.println("How many numbers would you like to add?");
int amountNumbers = input.nextInt();
int sum = IntStream.generate(input::nextInt)
.limit(amountNumbers)
.sum();
System.out.println("Sum: " + sum);
}
Here are a few things I would recommend changing:
You only need 1 scanner. And as for adding to a sum, if you make the variable before the loop, you can just add to the sum in the same line you take input.
You also had the < sign mixed up with a > sign. You want the loop to go until the variable addloop has been incremented the amount of times the user wants to input a number to add. Therefore, the loop should continue until it reaches the number the user entered, rather than the other way around.
System.out.println("How many numbers would you like to add?");
Scanner adds = new Scanner(System.in);
int addsput = adds.nextInt();
int sum = 0;
for(int i = 0; i < addsput; i++){
sum += adds.nextInt();
}
System.out.println(sum);
I was watching a lesson online about arrays. It taught me the 'basics' of array lists: how to create an array list. So I was wondering, how would one go about creating an array list from the users' input (JOptionPane), extract the numbers out of it, add them up and divide by the total amount of numbers in the array list (long story short, calculate the average of the array)?
Here's my, somewhat of an approach:
import java.util.Arrays;
import javax.swing.JOptionPane;
public class JOptionPaneTesting {
public static void main(String[] args){
int grades = Integer.parseInt(JOptionPane.showInputDialog("What are your grades of this month?"));
int arrayList[] = {Integer.valueOf(grades)};
int arraysum;
arraysum = arrayListGetFirstIndex + arrayListGetSecondIndex + ...; //Extracts all of the indices and adds them up?
int calculation;
calculation = arraysum / arrayListAmmountOfNumbersInTheList; //An example of how it go about working
}
}
As far as i understand the question, you are trying to get input from user. The input is the grades. Then you wanted to add up the grades and calculate the average of the grades.
public static double calculateAvg(List<Double>inputGrades){
List<Double> grades = new ArrayList<Double>(inputGrades);
double totalScore = 0.0;
double avgScore = 0.0;
if(grades !=null && grades.size()>0){
for(Double grade : grades){
totalScore = totalScore + grade;
}
avgScore = totalScore / grades.size();
}
return avgScore;
}
Taking user input and adding it to the list
List<Double> gradesList= new ArrayList<Double>();
gradesList.add(25.5);
gradesList.add(29.5);
gradesList.add(30.5);
gradesList.add(35.5);
System.out.println(calculateAvg(gradesList));
This would be a suitable solution too:
String[] input = JOptionPane.showInputDialog("What are your grades of this month?").split(" ");
double[] grades = new double[input.length];
double average = 0.0;
for (int i = 0; i < input.length; i++) {
// Note that this is assuming valid input
grades[i] = Double.parseDouble(input[i]);
average+=grades[i];
}
average /= grades.length;
So you could type in multiple "grades" seperated by a whitespace.
first create a list
List<Integer> list = new ArrayList<Integer>();`
then list.add(grade);
you need iterate whole above line if you want add more than one grades.
then list.get(index) get you specific (index) grade.
to calculate arraySum use :
for(int i = 0; i < list.size() ; i++)
arraysum += list.get(i); // and others are same.
I hope this helps you!
I am having a little trouble figuring out what to do when it comes down to this project (generally the same for all my projects). I just want to know if I'm headed in the right direction also, I am not sure how to store the float number in the int double array. Thanks
Question & SampleOutput
Write a Java program that prompts the user to enter an integer. Use the integer as the size for a new double array. Use a for loop to prompt the user to enter a floating point number for each element in the
array, and store the number in the array. Use a second for loop to, calculate the average of all of the numbers and print it.
Your output should look something like the following:
How many numbers will you enter: 5
Enter a decimal value: 21.2
Enter a decimal value: 3.7
Enter a decimal value: 10.5
Enter a decimal value: 2.6
Enter a decimal value: 101.123
The average is 27.824599999999997
My current code:
import java.util.*;
public class Loops {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print(" How many numbers will you enter: ");
int numberOfTimes = input.nextInt();
int[][] Array = new int[numberOfTimes][];
for(int i = 0; i < Array.length; i--)
{
System.out.print("Enter a decimal value: ");
float value = input.nextInt();
Array[i][
{
}
}
}
}
PS: My apologies for bad formatting. New to Stack.
Sir,
The major mistake you're committing is considering double as two. 'Double' is also a data type just like integers and float. So you need only a one dimensional array to store the values which are of type 'double'.
Secondly, i would suggest you to try to completing the code yourself once. If you're having issues in compiling it or getting wrong output, feel free to post the code online.
The desired result could have been achieved with only one 'for' loop, but I've provided the code 2 'for' loops only for the clarity.
Here's the code-
import java.util.Scanner;
public class AverageNumber {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many numbers will you enter: ");
int numberOfTimes = input.nextInt();
double AverageMean = 0;
double[] Array = new double[numberOfTimes];
// Doing the first loop as suggested
for(int i = 0; i < numberOfTimes; i++)
{
System.out.print("Enter a decimal value: ");
Array[i] = input.nextDouble();
}
// Doing the second loop as suggested
for(int i = 0; i < numberOfTimes; i++)
{
AverageMean = AverageMean + Array[i];
}
System.out.println("The average is " + AverageMean/5);
}
}
And the desired output will be-
How many numbers will you enter: 5
Enter a decimal value: 21.2
Enter a decimal value: 3.7
Enter a decimal value: 10.5
Enter a decimal value: 2.6
Enter a decimal value: 101.123
The average is 27.824599999999997
Hope it helps..
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print(" How many numbers will you enter: ");
int numberOfTimes = input.nextInt();
float[] input = new int[numberOfTimes];
for(int i = 0; i < numberOfTimes; i++) {
System.out.print("Enter a decimal value: ");
float value = input.nextInt();
Array[i] = value;
}
}
1) You need a double array instead of a two dimensional int array to store double.
2) Use input.nextDouble(); to take a double input.
3) for(int i = 0; i < Array.length; i--) will cause i to decrease negative which will next create ArrayIndexOutofBound exception at Array[i].
4) There are some other errors, better try the following code.
Try this:
import java.util.*;
public class Loops {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print(" How many numbers will you enter: ");
int numberOfTimes = input.nextInt();
double[] Array = new double[numberOfTimes];
double sum = 0;
double average = 0;
for (int i = 0; i < numberOfTimes; i++) {
System.out.print("Enter a decimal value: ");
double value = input.nextDouble();
Array[i] = value;
sum += value;
}
average = sum / numberOfTimes;
System.out.print("The average is: " + average);
}
}
Output:
How many numbers will you enter: 5
Enter a decimal value: 21.7
Enter a decimal value: 3.7
Enter a decimal value: 10.5
Enter a decimal value: 2.6
Enter a decimal value: 101.123
The average is: 27.924599999999998