Java Array, int reset to 0? - java

Working on a project where the user input determines the size of an array. Afterwards the user inputs values and receives the sum. Finally the program shows the user the percentage of each value to the total. For example if the array size is 4 and a[0] = 2, a[1] = 1, a[2] = 1, and a[3] = 2 it will show "2, which is 33.333% of the sum" "1, which is 16.666% of the sum" etc. The problem I have is that after the array and sum are determined and I try to find the percentage I get 0. Is the sum reset to 0 since it's a different for loop?
import java.util.Scanner;
public class CountIntegersPerLine
{
public static void main(String[] args)
{
int elements;
int arraySize;
int sum = 0;
int percentage;
System.out.println("How many numbers will you enter?");
Scanner keyboard = new Scanner(System.in);
//Length of array is determined by user input
arraySize = keyboard.nextInt();
int[] array = new int[arraySize];
System.out.println("Enter 4 integers, one per line");
for (elements = 0; elements < arraySize; elements++)
{
//Gather user input for elements and add the total value with each iteration
array[elements] = keyboard.nextInt();
sum = sum + array[elements];
}
System.out.println("The sum is " + sum);
System.out.println("The numbers are:");
for (elements = 0; elements < arraySize; elements++)
{
//Display the percent that each value contributes to the total
percentage = array[elements] / sum;
System.out.println(array[elements] + ", which is " + percentage + " of the sum.");
}
System.out.println();
}
}

Integer division will result in a zero value when the numerator is less than the denominator. You should declare percentage as a float or a double.
int percentage;
...
...
...
percentage = array[elements] / sum;
and you will need to cast the division operation in your case to preserve the value:
percentage = (double)array[elements] / sum;

Try declaring the sum variable as a double (or float):
double sum = 0.0;
Why? because in this line:
percentage = array[elements] / sum;
... You're performing a division between two integers, and all the decimals will be lost. You can verify that this is indeed the case, for example try this:
System.out.println(1/3); // it'll print 0 on the console
The solution to this problem is to have either one of the division's operands as a decimal number, by declaring as such their types (as I did above) or by performing a cast. Alternatively, this would work without changing sum's type:
percentage = array[elements] / ((double)sum);

Related

Why doesn't the scanner class recognize the other numbers?

public class Hello {
public static void main(String [] args){
int number, count = 0, sum = 0;
int Largest= 0, largestEvenNumber = 0;
Scanner console = new Scanner(System.in);
number = console.nextInt(); // read an integer entered by a user
if (number > Largest) { // Condition for computing the largest number
Largest = number;
}
if (number < 0) { // Condition for computing the number of negative integers in the sequence
count = count + 1;
}
if (number % 2 == 0) { // Condition for computing the largest even integer in the sequence
if (largestEvenNumber < number) {
largestEvenNumber = number;
}
}
if (number % 3 == 0) { // Condition for computing the sum of numbers divisible by 3
sum += number;
}
System.out.println("\nThe largest integer is " + Largest);
System.out.println("The number of negative integers in the sequence is " + count);
System.out.println("The largest even integer in the sequence is " + largestEvenNumber);
System.out.printf("The sum of numbers divisible by 3 is %d", sum);
}
}
I would like to get the expected output given below. But, the Scanner class is reading only the first number. How do I correct this without creating multiple objects?
Output:
2
-1
-5
-3
9
8
0
The largest integer is 2
The number of negative integers in the sequence is 0
The largest even integer in the sequence is 2
The sum of numbers divisible by 3 is 0
Process finished with exit code 0
expected Output:
The largest integer is 9
The number of negative integers in the sequence is 3
The largest even integer in the sequence is 8
The sum of numbers divisible by 3 is 6
Thank you!
You only call console.nextInt() once, so only one number is read. If you want to call you need to loop over calls to console.hasNext(). Since you're using System.in. E.g.:
while (console.hasNextInt()) {
number = console.nextInt();
// calculations
}
You are only reading input once. I don't see a loop in your code, so number = console.nextInt(); only runs once. What you should do is put it inside a loop, exit the loop when you have all the numbers (how you check that can be done in multiple ways), and while you're inside the loop put whatever input you receive into an array or another data structure. After you're done collecting input, do your checks over all the numbers on your data structure.
1- You must first receive the data from the user and then calculate it and generate the output. You can do this using the arrays and after finishing put your data, calculate on them.
for example :
private static final int DATA_SIZE = 5;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Integer> data = new ArrayList<>();
// put data in array
while (data.size() == DATA_SIZE){
data.add(scanner.nextInt());
}
// calculate data from array ...
}
2- When you call a field like nextInt() Scanner class , it is done only once, then you put it in a loop to be repeated several times ...
Of course, I have other suggestions for doing this
For example, you can use the array available in the main method (with knowledge, of course)
OR
First ask the user for the amount of data you have, then take it and then calculate
OR....
If you want to type all number at once ,you should set a terminal number. when you input all you number,you shoud add the terminal number to indicate input is over.
For example:
public static void main(String [] args){
int number, count = 0, sum = 0;
int Largest= 0, largestEvenNumber = 0;
Scanner console = new Scanner(System.in);
int endNumber = -1; //set the terminal number
do {
number = console.nextInt(); // read an integer entered by a user
if (number > Largest) { // Condition for computing the largest number
Largest = number;
}
if (number < 0) { // Condition for computing the number of negative integers in the sequence
count = count + 1;
}
if (number % 2 == 0) { // Condition for computing the largest even integer in the sequence
if (largestEvenNumber < number) {
largestEvenNumber = number;
}
}
if (number % 3 == 0) { // Condition for computing the sum of numbers divisible by 3
sum += number;
}
}while (number!=endNumber);
System.out.println("\nThe largest integer is " + Largest);
System.out.println("The number of negative integers in the sequence is " + count);
System.out.println("The largest even integer in the sequence is " + largestEvenNumber);
System.out.printf("The sum of numbers divisible by 3 is %d", sum);
}
The line if code is only being executed once. Thus, the Scanner is only taking in the first in put. Use a while loop to take in multiple inputs.

How to fix getting an average from user input

The instructions are the following:
Write a method called inputThenPrintSumAndAverage that does not have any parameters.
The method should not return anything (void) and it needs to keep reading int numbers from the keyboard.
When the user enters something that is not an int then it needs to print a message in the format "SUM = XX AVG = YY". XX represents the sum of all entered numbers of type int.
YY represents the calculated average of all numbers of type long.
I've coded the following method but I keep getting the incorrect average. What can I change to get the correct average?
public static void inputThenPrintSumAndAverage(){
Scanner scanner = new Scanner(System.in);
int sum = 0, counter = 0;
long average = 0L;
while(true) {
boolean number = scanner.hasNextInt();
if(!number)
{
counter++;
break;
}
else {
int digit = scanner.nextInt();
sum += digit;
counter++;
}
}
average = sum / counter;
System.out.println("SUM = " + sum + " AVG = " + average);
}
The following should do:
if(!number)
break;
Your average is wrong because you are incrementing "counter" more than you should.
Of course in the end you are going to have to add one more if statement to make sure you are not attempting to divide by counter if the counter is zero. In that case, an average is undefined.
Also, as others have pointed out in the comments, it is entirely unclear to us what you mean when you say "I keep getting the incorrect average", and we generally frown upon questions worded so vaguely. But if by any chance a "correct average" for you means an average with decimals, then you should use a double instead of a long for your average, and you should cast your counter to double before dividing, so as to force a double division instead of a long division.
Use scanner.hasNextInt() to read util a non-integer value is supplied as input:
public static void inputThenPrintSumAndAverage() {
Scanner scanner = new Scanner(System.in);
int number, sum = 0, counter = 0;
long average = 0L;
while (scanner.hasNextInt()) {
number = scanner.nextInt();
sum += number;
counter++;
}
if(counter != 0){
average = sum / counter;
}
System.out.println("SUM = " + sum + " AVG = " + average);
}
Note that you should check the value of counter to avoid a division by zero.
If you want the average to be in decimals, change the type of average to double: double average; and cast the division to double: average = (double) sum / counter;.

Reading in a number.txt file and finding averages

currently working on an assignment and I need to read in a file of numbers and display the total amount of numbers, total even numbers, total odd numbers, and the averages of all three. I am currently struggling to find the average of the even numbers and the odd numbers. I have to display the average of the even number and the average of the odd numbers. I found the total average by using parseInt to convert the string of numbers i read in to ints so i could calculate the average but when i tried to do the same for even and odd numbers i couldnt get it to work
here is my current code:
public class Homework1 {
public static void main(String[] args) throws IOException {
// reads file in
File num = new File("numbers.txt");
Scanner inputFile = new Scanner(num);
// creates rounding object
DecimalFormat rounding = new DecimalFormat("#.##");
// neccesary variables
int count = 0;
double numbers =0;
int evenNum =0;
int oddNum =0;
double avg;
double evenAvg;
double oddAvg;
double sum = 0.0;
double evenSum = 0.0;
double oddSum = 0.0;
// reads in numbers file until last line is read
while(inputFile.hasNext())
{
String nums = inputFile.nextLine();
// converts string to ints so numbers can be added
sum += Integer.parseInt(nums);
// converts string to ints to so odd/even nums can be distinguished
numbers = Integer.parseInt(nums);
// updates total number count
count++;
// separates evens from odds
if(numbers % 2 == 0)
{
evenNum++;
evenSum += Integer.parseInt(nums);
}
else
oddNum++;
evenSum += Integer.parseInt(nums);
}
// calculates total num average
avg = sum/count;
// evenAvg =
// oddAvg =
// output of credentials and results
System.out.println("There are " +count+ " numbers in the file"+"\n");
System.out.println("There are " +evenNum+ " even numbers"+"\n");
System.out.println("There are " +oddNum+ " odd numbers"+"\n");
System.out.println("The total average value is " +rounding.format(avg)+"\n");
System.out.println("The odd number average is " +rounding.format(evenAvg)+"\n");
System.out.println("The even number average is " +rounding.format(oddAvg)+"\n");
}
Output:
There are 982 numbers in the file
There are 474 even numbers
There are 508 odd numbers
The total average value is 50362.43
okay so I corrected the if/else statements and added the brackets and this fixed the problem i was having
oddNum++;
oddSum += Integer.parseInt(nums);

Count numbers in a "for loop" and give back average, min, max value in java

A user should input a number "x", and then the count of "x" numbers, e.g. input = 3, then 3 random numbers like 3, 5, 7.
Afterwards the program should give an output of the average, min and max value of this "x" numbers. So it has to read the numbers, but i don't know how it can be done.
It should be done without arrays and with a for loop.
I didn't find a possible solution here, but maybe I didn't do the right search.
So here is what i got so far:
import java.util.Scanner;
public class Statistic
{
public static void main (String[] args)
{
// Variables
Scanner input = new Scanner(System.in);
int number1;
int numbers;
double averageValue;
// Input
System.out.println("\n\n####################################################################");
System.out.print("\n Pls enter a number: ");
number1 = input.nextInt();
System.out.print(" Pls enter " + number1 +" numbers: ");
numbers = input.nextInt();
for (int count = 0; count < number1; count ++) {
System.out.println(numbers); //Just for me to see which numbers are read by the programm
}
averageValue = numbers / number1;
// Output
System.out.println("\n Biggest number: " + Math.max(numbers));
System.out.println("\n Smallest number: " + Math.min(numbers));
System.out.print("\n Average value: " + averageValue);
}
}
But it only prints out and calculates with the first number of the "numbers"-input. Further I am not sure how to use the "Math.max" for a random count of numbers.
The problem is here:
System.out.print(" Bitte geben Sie " + number1 +" Zahlen ein: ");
numbers = input.nextInt();
nextInt() only saves one int. Every subsequent number you are entering gets lost, of course.
What you need to do is to move this statement inside the for loop for your idea to work.
Also, you can't use min and max here. min and max compare two numbers and return the greater of the two. For your purpose, you'd need to check inside the loop which the greatest and smallest number is and then output it accordingly.
You will need 6 variables: min = 0, max = 0, avg, sum = 0, count, num.
(avg variable is optional)
Program flow will be:
input how many numbers you want to enter -> store in variable count
use some loop to loop count number of times and in each iteration store
users value in variable num.
Increment sum by number user entered. sum += num;
check if entered number is less than current min. If true store min as that number.
Same as min do for max variable.
When loop exit you will have min, max, sum and count variables stored. To calculate avg devide sum with count and there you go. avg = sum / count.
First your code is logically in correct. when u have to take min and max values with average u need to store the inserted elements or process each input(for time complexity this would be the best approach).
Below I have modified your code where i m using enter code hereJava Collections List to store the inputs, sort them and get the data.
After sorting first will me min and last will be max.
Math.min and Math.max only works for comparing 2 numbers not an undefined list.
Again i would say the best solution would be if u check for the number is min or max at input time.
As you are new to java you can try that out your self.
import java.util.*;
public class ZahlenStatistik
{
public static void main (String[] args)
{
// Variables
Scanner input = new Scanner(System.in);
int number1;
List<Integer> numbers = new ArrayList<Integer>(); // change it to list
double averageValue;
int sum= 0;
// Input
System.out.println("\n\n####################################################################");
System.out.print("\n Bitte geben Sie eine Zahl ein: ");
number1 = input.nextInt();
System.out.print(" Bitte geben Sie " + number1 +" Zahlen ein: ");
//Define the number of times loop goes
for (int count = 0; count < number1; count ++)
{
numbers.add(input.nextInt());
}
for(Integer number:numbers)
{
sum = sum + number;
}
averageValue = sum / number1;
Collections.sort(numbers);
// Output
System.out.println("\n Die größte Zahl ist: " + numbers.get(numbers.size()-1));
System.out.println("\n Die kleinste Zahl ist: " + numbers.get(0));
System.out.print("\n Der averageValue betr\u00e4gt: " + averageValue);
}
}
Some errors that I can see
System.out.print(" Pls enter " + number1 +" numbers: ");
numbers = input.nextInt();
You need here a loop and array to read and store all elements.
To get average value you need first to sum all elements in array and then to divide by length of array.
To find min and max values in array you cannot use Math.min() and Math.max() methods because these methods get two parameters and return min/max value.
Your code should be something like this
Notes
If you cannot use Java 8 you must replace Arrays.stream(numbers).max().getAsInt(); and Arrays.stream(numbers).min().getAsInt(); with helper methods which find max/min values in an array.
If you can use Java 8 you can calculate sum int sum = Arrays.stream(numbers).reduce(0, (x, y) -> x + y); instead in for loop.
.
public class Statistic {
public static void main(String[] args) {
// Variables
Scanner input = new Scanner(System.in);
// Input
System.out.println("\n\n####################################################################");
System.out.print("\n Pls enter a number: ");
int number1 = input.nextInt();
System.out.println(" Pls enter " + number1 + " numbers: ");
int[] numbers = new int[number1];
for (int i = 0; i < number1; i++) {
System.out.println("Enter next number");
numbers[i] = input.nextInt();
}
// Find min and max values
int max = Arrays.stream(numbers).max().getAsInt();
int min = Arrays.stream(numbers).min().getAsInt();
System.out.println("\n Biggest number: " + max);
System.out.println("\n Smallest number: " + min);
// Get average value
int sum = 0;
for (int num : numbers) {
sum = sum + num;
}
double averageValue = (double) sum / number1;
System.out.print("\n Average value: " + averageValue);
}
}
import java.util.Scanner;
public class SumOf2
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Enter 2 integer values");
int m = s.nextInt();
int n = s.nextInt();
int sum=0;
int count=0;
for(int i=m ; i<=n ; i++)
{
if(count < n)
{
sum=sum+i;
count++;
}
}
System.out.println("Sum of two numbers is: "+sum);
System.out.println("Count between 2 numbers is : "+count);
}
}

Incorrect variable value for during average calculation for num 1 to 100

public class SumandAverage {
public static void main(String[] args) {
int sum=0;
double average;
int lowerBound = 1;
int upperBound = 100;
while(lowerBound<=upperBound) {
sum = sum+lowerBound;
lowerBound++;
}
System.out.println("The Sum is "+sum);
average=sum/upperBound;
System.out.println("The average is " + average);
}
}
the result i get is "The Sum is 5050 The average is 50.0"..why is my upperBound changing to 101 and resulting in incorrect average value of 50.0 instead of 50.5 when i am not even changing it at all? must be something silly, but i am not able to spot.
You are dividing ints, so the result is int. Divide doubles instead :
average=(double)sum/upperBound;
5050/100 = 50, since int division can only produce an int. After you assign it to a double variable, you get 50.0.
int sum=0;
double average;
int lowerBound = 1;
int upperBound = 100;
while(lowerBound<=upperBound) {
sum = sum+lowerBound;
lowerBound++;
}
System.out.println("The Sum is "+sum);
average=(double)sum/upperBound; //change
System.out.println("The average is " + average);
ie change only average=(double)sum/upperBound; .In your case you are getting int results because sum and upperBound are int.Other option is you can also change the datatypes of these variable to get the desired output.
Demo

Categories

Resources