Individually sum random numbers not in an array? - java

This is part of a school assignment which I've already turned in, I was graded down in one portion because the total sum of the random numbers was supposed to be adding the individual numbers together, not each line.
So if the lines read:
1 2 3
4 5 6
The total should be 21, not 579 as my program is doing now. I've really been struggling trying to figure this out. I tried generating a different random number object for each integer, for a total of three of them but that completely screwed up my output.
We're learning arrays next week, and after researching online I could do this easily with an array, but the assignment was to be done without arrays. How can I sum each entry individually? Thanks for any help!
Here is my code:
import java.util.Random;
import java.util.Scanner;
public class lottery {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int gameType, gameTimes;
int randomNums, lotNum, sum = 0;
System.out.println("\t\t Welcome to\n \t\tJAVA LOTTERY!\n\n\n");
System.out.print(" Would you like to play with 3, 4, or 5 numbers? ");
gameType = input.nextInt();
System.out.println("\n\n Now think about a number with " + gameType + " digits and remember it!\n\n\n");
System.out.print(" How many games should we play? ");
gameTimes = input.nextInt();
System.out.println("\n\n We're all done! We played " + gameTimes + " games!\n\n" +
" The numbers randomly selected were: ");
for(int i = 0; i < gameTimes; i++)
{
lotNum = 0;
for(int j = 0; j < gameType; j++)
{
randomNums = (new Random()).nextInt(10);
lotNum = (lotNum * 10) + randomNums;
System.out.print(" " + randomNums);
}//end nested for loop
System.out.println();
sum += lotNum;
}//end for loop
System.out.println("\n\nThe total of all of the numbers was " + sum );
input.close();
}//end main method
}//end lottery class

Change
lotNum = (lotNum * 10) + randomNums;
to
lotNum += randomNums;

Related

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);
}
}

Trying to take average each time something is added

package gradeAvg;
import java.util.Scanner;
//Grade Average calculater
public class GradeAvg {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.print("Please Enter the first grade being added to the average:");
double average = input.nextInt();
System.out.print("The average is now: " + average + " Please enter the second grade being averaged:");
average += input.nextInt() ;
System.out.print("The average is now: " + average + " Please enter the third grade being averaged:");
average += input.nextInt() / 2;
System.out.print("The average is now: " + average + " Please enter the fourth grade being averaged:");
average += input.nextInt() / 2;
System.out.print("The average is now: " + average + " Please enter the fifth grade being averaged:");
average += input.nextInt() / 2;
input.close();
System.out.print(average);
}
}
Hey guys, I'm really new to java, and pretty terrible at math, I'm supposed to be making a program that allows the user to input a value, have it averaged out, print it out, and then allow the input of another value, have it averaged, and print, and continue. Am i going wrong when I divide by 2 at the end of each input or what?
Average is the sum of all the numbers divided by the number of numbers in the sum.
What you are doing here is not average. You are adding the half of every new number to the total sum. I don't what you are doing here.
Just to make things more understandable, let's make a sum and a counter:
public class GradeAvg {
public static void main(String[] args) {
int sum;
int counter;
// ...
}
}
Each time you ask for a number, you increment the counter and add the new number to sum:
int newNumber;
// ask for input
newNumber = input.nextInt()
sum += newNumber;
counter++;
You can then output the average like this:
System.out.println("The average is: " + (double)sum / counter);
That's wrong. each number you add weight 50% against the other numbers.
you need to keep track of the count (number of elements) and the sum and each time divide the sum by the number of elements.
so each time you add a number the function should be:
(OLD_AVERAGE*OLD_COUNT+NEW_NUMBER)/(OLD_COUNT+1)
or just use SUM and COUNT and each time AVERAGE=SUM/COUNT.
inc. count by 1 every new number.
inc sum by the number entered.
complete working solution... hope it helps...
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double sum = 0;
int count = 1;
double average = 0;
System.out.print("Please Enter the " + count + " grade being added to the average:");
for (; count <= 5;) {
sum = sum + input.nextInt();
average = sum / count;
System.out.println("The average is now: " + average);
count++;
if (count <= 5)
System.out.println("Please enter the " + count + " grade being averaged:");
}
input.close();
}

append int values in an emty array java

I wrote a programm to print out all the prime number up to a limit. Then put those prime numbers into an ArrayList, convert this ArrayList into an array, finally print the numbers out with their index.
Note: I couldnt print out an ArrayList with a for loop, it's possible with an array only, hence the conversion.
My question is:
Is there anyway to do it without pushing the numbers into an ArrayList first, instead put them right away into an emty array of a length < given limit.
Thanks for you help!
was browsing SO in the last 2 days and couldnt find anything
import java.util.Scanner;
import java.util.ArrayList;
public class test {
public static void main(String[] args){
//get input till which prime number to be printed
System.out.print("Enter the number till which prime number to be printed: ");
int limit = new Scanner(System.in).nextInt();
System.out.print("\n");
ArrayList<Integer> myArray = new ArrayList<Integer>();
//printing primer numbers till the limit ( 1 to 10)
System.out.println("Printing prime number from 1 to " + limit + "\n");
for(int number=2; number <= limit; number++){
if(isPrime.numberPrime(number)){
myArray.add(number);
}
}
System.out.println(myArray + "\n");
//Convert ArrayList into an Array
int[] newArray = new int[myArray.size()];
for(int i = 0; i < myArray.size(); i++) {
newArray[i] = myArray.get(i);
}
System.out.println("There were " + myArray.size() + " prime numbers");
System.out.println("Index\tValue");
for(int counter = 0; counter<newArray.length; counter++){
System.out.println(counter+1 + "\t" + newArray[counter]);
}
}
here is the result:
Enter the number till which prime number to be printed: 10
Printing prime number from 1 to 10
[2, 3, 5, 7]
There were 4 prime numbers
Index Value
1 2
2 3
3 5
4 7
No need to do this
//Convert ArrayList into an Array
int[] newArray = new int[myArray.size()];
for(int i = 0; i < myArray.size(); i++) {
newArray[i] = myArray.get(i);
}
System.out.println("There were " + myArray.size() + " prime numbers");
System.out.println("Index\tValue");
for(int counter = 0; counter<newArray.length; counter++){
System.out.println(counter+1 + "\t" + newArray[counter]);
}
In place of this, simply write
System.out.println("There were " + myArray.size() + " prime numbers");
System.out.println("Index\tValue");
for(int i=0;i<myArray.size();i++)
System.out.println(i+1 + "\t" + myArray.get(i));

Trying to get my matrix printed not the heap address

The code seems to run except what I am getting is not a matrix of a specified (by the user) size but what I think is a heap address
Here's what it returns when the user inputs 2 for the size and then 4 numbers:
Enter matrix size:
2
Enter a 2 by 2 matrix row by row: 2 3 4 5
The row-sort matrix is...[[D#3c954549BUILD SUCCESSFUL (total time: 8 seconds)
here is the code....thank you in advance.
import java.util.Scanner;
public class Exercise7_26M {
public static void main (String[]args)
{
//Prompt user for input of matrix size
System.out.println("Enter matrix size: ");
Scanner input = new Scanner(System.in);
int size = input.nextInt();
double[][] m = new double [size][size];
//prompt user for input of array
System.out.print("Enter a " + size + " by " + size + " matrix row by row: ");
for (int row = 0; row < 2; row++)
for (int column = 0; column < 2; column++)
m[row][column] = input.nextDouble();
System.out.print("The row-sort matrix is..." + m);
}
Java arrays do not override toString() so you are getting the default implementation from Object. Instead, you can use Arrays.deepToString(Object[]) like
System.out.println("The row-sort matrix is..." + Arrays.deepToString(m));

Java sum of numbers error

This code seems to run well, but am getting error message regarding calculating the sum of the integers entered.
The point of the exercise is to input a series of numbers, and after the value -1 is entered, calculate the sum of the numbers, how many numbers were entered, the mean value, and the number of odd and even numbers.
The output I get suggests the program is running fine, but still get an eror message.
With input 1 17 2 18 17 -1 should print "sum: 55" expected:<55> but was: <0>
Apologies in advance if my Java syntax is a bit inelegant. I'm fairly new at this! Code below.
import java.util.Scanner;
public class LoopsEndingRemembering {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Type numbers: ");
int n;
double sum = 0.0;
int i = 0;
double average = 0.0;
int odd = 0;
int even = 0;
while (true) {
n = Integer.parseInt(reader.nextLine());
if (n != -1) {
System.out.print("Type numbers: ");
sum += n;
i++;
average = sum / i;
if (n % 2 == 0) {
even++;
} else {
odd++;
}
} else {
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
System.out.println("How many numbers: " + i);
System.out.println("Average: " + average);
System.out.println("Even numbers: " + even);
System.out.println("Odd numbers: " + odd);
break;
}
}
}
}
You're printing 55.0. It seems you're getting this program tested by another program which you don't have access to the source code of.
Issue 1
You probably want to print 55 specifically.
Instead of:
double sum = 0.0;
Do:
int sum = 0;
Issue 2
Use int over double. Cast to double for the average value.
Then instead of this:
average = sum / i;
Do something like:
average = (double)sum / i;
Issue 3
Also, it seems the error message wants you to print as sum: 55.
So change this:
System.out.println("The sum is " + sum);
To:
System.out.println("sum: " + sum);

Categories

Resources