Sum of ten random numbers - java

So far, my code looks like this:
import java.util.Random;
public class StatsCalculator
{
public static void main(String[] args)
{
Random r = new Random();
System.out.println("The ten random values are: ");
for(int i=0; i<10; i++)
{
int randomint = r.nextInt(10);
System.out.print(" ," + randomint);
}
int randomint[];
int sum=0;
for(int i : randomint)
{
sum += i;
System.out.println("Sum = " + sum);
}
}
}
When I run this code, there's an error message come up that say's the following: "variable randomint might not have been initialized, for (int i : randomint)

Try this:
int sum=0;
for(int i=0; i<10; i++)
{
int randomint = r.nextInt(10);
System.out.print(" ," + randomint);
sum = sum + randomint ;
}
System.out.println("Sum = " + sum);

Place all the randoms within an array and then sum them:
Random r = new Random();
System.out.println("The ten random values are: ");
int[] values = new int[10];
for(int i = 0; i < 10; i++) {
int randomint = r.nextInt(10);
values[i] = randomint;
System.out.print(" ," + randomint);
}
int sum = 0;
for(int i : values) {
sum += i;
}
System.out.println("Sum = " + sum);

Your array randomInt is defined as an array but elements are never added to it, then you try iterate through it and there's nothing there.
Initialise it
int[] randomInt = new int[size];
then create elements in it. It looks like you should move this to before the first array and add all the random int you create.

The error is telling you everything: "variable randomint might not have been initialized, for (int i : randomint)"
In your head, you should hear this dialog:
Hmm, why is it telling me randomint might not have been initialised? Have I initialised it?
I better check this randomint...oh, here it is:
int randomint[];
How do I initialise it...the docs...the docs...THE DOCS!
Here it is:
One way to create an array is with the new operator. The next statement in the ArrayDemo program allocates an array with enough memory for 10 integer elements and assigns the array to the anArray variable.
// create an array of integers
int[] anArray = new int[10];
If this statement is missing, then the compiler prints an error like the following, and compilation fails:
ArrayDemo.java:4: Variable anArray may not have been initialised.
Fine, let's add this:
int randomint[] = new int[10];
compile...run...
errr, why is the sum 0 if I can see random numbers?
(reads the docs again)
Right, need to store those random ints in my array, phew, one more change:
Random r = new Random();
System.out.println("The ten random values are: ");
int randomint[] = new int[10];
for(int i=0; i<10; i++)
{
randomint[i] = r.nextInt(10);
System.out.print(" ," + randomint[i]);
}
int sum=0;
for(int i : randomint)
{
sum += i;
System.out.println("Sum = " + sum);
}
Uff, next time someone asks similar question on SO, I might be able help them. First thing I'll say is to read the docs :)

Related

How to return the array repeated three time in a single array?

I'm pretty sure I've done most of the code correctly but I'm returning the wrong thing? I've tried using copyOf() but still had the same issue. It looks like I'm returning the object of an array rather than the elements? I need the method treble to return the original array repeated in order, three times in one array. So [1,2,3,] should look like [1,2,3,1,2,3,1,2,3] when trebled.
Any help would be much appreciated.
import java.util.Scanner;
import java.util.Arrays;
public class ArrayExercises
{
public static void main(String[] args)
{
final int SIZE = 5;
int[] array = new int[SIZE];
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < array.length; i++)
{
System.out.print("Please enter whole number " + (i + 1) + ": ");
int input = scanner.nextInt(); // get input from the user
array[i] = input; // store the value in the array
}
printArray("Input array:", array);
// call method sum and print out the result
int sum = sum(array);
System.out.println("The sum of elements is " + sum);
// call method repeat and print out the result
int[] trebled = repeat(array);
System.out.println("The repeated array is " + trebled);
}
public static void printArray(String msg, int[] array)
{
System.out.println(msg + " " + Arrays.toString(array));
}
public static int sum(int[] array)
{
int s = 0;
for (int i = 0; i < array.length; i++)
s += array[i];
return s;
}
public static int[] repeat(int[] array) //this is the part I'm having trouble with
{
int len = array.length;
int[] multiplied = new int[len*3];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < len; j++)
{
multiplied[i * len + j] = array[j];
}
}
return multiplied;}
}
Try using:
System.out.println("The repeated array is " + Arrays.toString(trebled));
to print your array instead of printing using the array variable name, because otherwise that will print the address of the array rather than the content.
your method is ok, the issue is how you print it because as mentioned in the comments you do not use your printArray() method in this case.
So try changing this line :
System.out.println("The repeated array is " + trebled);
to :
printArray("The repeated array is " , trebled);

Java adding issue

I have an issue with my java program displaying every number it is adding, what can I do so that it only displays the total. I am guessing since I have "element" in the last part of the code it showing every single addition: Here is what I have written:
import java.util.Scanner;
public class SomeClass {
public static void main(String[]args){
int ans = 0;
int num;
Scanner keyboard = new Scanner(System.in);
System.out.println("How many integers do you have? (Max 20)");
int x= keyboard.nextInt();
int [] element = new int[x];
for(int subscript = 0; subscript < element.length; subscript++){
System.out.println("Enter element for subscript " + (subscript));
element[subscript] = keyboard.nextInt();
}
System.out.println("Here are all of those numbers");
for(int subscript = 0; subscript < element.length; subscript++){
num = element[subscript];
System.out.println(num);
}
for (int i = 0; i < element.length; i++){
ans += element[i];
System.out.println("The sum of these numbers is " + ans);
}
}
}
//previous lines of code
for (int i = 0; i < element.length; i++){
ans += element[i];
}
System.out.println("The sum of these numbers is " + ans);
//code follows
Because You print out the 'num' as many as length of element. You have to delete that line if your intention is to show only the summed ans which is result of sumation. If you wanna show inputs then its fine
Also
Take this sentence out of the for loop
System.out.println("The sum of these numbers is " + ans);
Everytime for loops working, that line works too. So make it works once after you add all the numbers with for loop.

About saving and printing distinct numbers in an array

before you help me this is a homework assignment, i have most of all of it done but there is one thing that i cant figure out, 0 doesn't get detected at all. This means if i input 0-9 into the array it will tell me there is only 9 distinct numbers when really there should be 10 and it will print out all the numbers but 0. Can anyone see the problem and please explain it to me becuase i need to understand it.
package javaproject.pkg2;
import java.util.Scanner;
public class JavaProject2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numArray = new int[10];
int d = 0;
System.out.println("Enter Ten Numbers: ");
for(int i = 0; i < numArray.length; i++){
int num = input.nextInt();
if(inArray(numArray,num,numArray.length)){
numArray[i] = num;
d++;
}
}
System.out.println("The number of distinct numbers is " + d);
System.out.print("The distinct numbers are: ");
for(int i = 0; i < d; i++){
System.out.print(numArray[i] + " ");
}
}
public static boolean inArray(int[] array, int searchval, int numvals){
for (int i =0; i < numvals; i++){
if (searchval == array[i]) return false;
}
return true;
}
}
You can use a set to identify distinct values:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Set<Integer> distinctNumbers = new LinkedHashSet<>();
System.out.println("Enter ten Numbers: ");
for (int i = 0; i < 10; i++) {
int number = input.nextInt();
distinctNumbers.add(number);
}
System.out.println("The number of distinct numbers is " + distinctNumbers.size());
System.out.print("The distinct numbers are: ");
for (Integer number : distinctNumbers){
System.out.print(number + " ");
}
}
If a value already exists in a set, it can't be added again. Arrays are not the best fit for your problem, since they must be initialized with a fixed size and you don't know how many distinct values the user will inform.
Take a look at numArray after int[] numArray = new int[10]; - it is initialized with zeros.

ArrayList and java.lang.OutOfMemoryError

I am trying to make program that create an ArrayList of initial size of 1 and populate it with random numbers. Next, the ArrayList is cleared and the size of ArrayList is increased by 1 and again filled with random numbers. I want my program to repeat those steps until the ArrayList size will be equal to number specified by user.
So the output will be for example like:
1
3,8
6,3,7
...
n
I have produced so far:
public static void main (String args[]){
ArrayList<Integer> al = new ArrayList<Integer>();
Random rand = new Random();
int val=1;
int ii =1;
while(val<400){
for (int j = 0; j<ii;)
{
ii++;
val++;
pick = rand.nextInt(100);
al.add(pick);
}
System.out.println("Contents of al: " + al);
al.clear();
System.out.print("Array has been cleared: " + al);
}
Any ideas how to make it work?
You never increment j.
You are incrementing ii and val inside the for loop where as I think you actually want to do it in the while loop. Try the example below.
ArrayList<Integer> al = new ArrayList<Integer>();
Random rand = new Random();
int val=1;
int ii =0;
while(val < 400){
for (int j = 0; j<ii; j++) {
int pick = rand.nextInt(100);
al.add(pick);
}
ii++;
val++;
System.out.println("Contents of al: " + al);
al.clear();
System.out.print("Array has been cleared: " + al);
}
Your task would be much easier if you gave your variables meaningful names. e.g.
ArrayList<Integer> al = new ArrayList<Integer>();
Random rand = new Random();
int lineNumber = 1;
int lineLength = 0;
while(lineNumber < 400){
for (int randCount = 0; randCount < lineLength; randCount++) {
int pick = rand.nextInt(100);
al.add(pick);
}
lineLength++;
lineNumber++;
System.out.println("Contents of al: " + al);
al.clear();
System.out.print("Array has been cleared: " + al);
}
for (int j = 0; j<ii;) {
ii++;
val++;
pick = rand.nextInt(100);
al.add(pick);
}
is an infinite loop(j is always 0 and ii is always positive). You should fix it(according to the desired semantics).

Generating data for an array via Random class and sorting

Use the Random class to get numbers from 0 to 99 and store them into the array. Use a for loop to get each random number, store each into the array, and print each value.
Then use the bubble sort to sort the array, and print out the stored array.
here is my program
import java.util.Random;
public class Randomness
{
public static void main(String[] args)
{
Random randomNum = new Random();
for (int number = 0; number <= 99; ++number)
{
int num = randomNum.nextInt(100);
System.out.print(num + " ");
int numValues = num;
int [] values = new int[numValues];
boolean swap;
do
{
swap = false;
int temp;
for (int count = 0; count < numValues-1; count++)
if (values[count] > values[count+1])
{
temp = values[count];
values[count] = values[count+1];
values[count+1] = temp;
swap = true;
}
} while (swap);
System.out.print(values[count] + " ");
}
}
}
i get error
System.out.print(values[count] + " "); array required, but Random found.
please help!
You aren't creating any random values in your array. You are creating an array of random length (between 0 to 99). You need to initialize each element of your array with a random:
Random randomNum = new Random();
int numValues = 100;
int[] values = new int[numValues];
for (int number = 0; number < numValues; ++number)
{
int num = randomNum.nextInt(100);
System.out.print(num + " ");
values[number] = num;
}
Then do the bubble sort.

Categories