I'm working on a project for school where we have to spin a cube a number of times and find the longest run of the numbers that are received from the cube. I am almost finished with the code, and it complies, but whenever I run it I get the same error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at number_cube.number_cube.cubeToss(number_cube.java:20)
at number_cube.number_cube.main(number_cube.java:10)
Can anybody help me with this?
Here is my code:
public class number_cube {
public static int ans;
public static void main(String[]args){
Scanner scan = new Scanner(System.in);
System.out.println("How many times would you like to toss the cube?");
ans = scan.nextInt();
cubeToss();
getLongestRun();
System.out.println();
}
public static int arr[] = new int[ans];
public static int[] cubeToss(){
for(int i = 0; i < ans; i++){
int randnum = (int) (1 + Math.random() * (6-1));
arr[i] = randnum;
}
return arr;
}
public static void getLongestRun(){
int longest = 0;
int length = 1;
for(int i = 1; i < ans; i++)
if(arr[i] == arr[i-1]){
length++;
}
else{
length = 1;
}
if(length > longest){
longest = length;
}
System.out.println("The longest run is " + longest + ".");
}
}
You used the variable ans as the length of your arr array, but when the array was created, ans didn't have a value (Java initialized it to 0), so the arr array has length 0. The main method isn't called until the class is initialized; all static variables are initialized before the main method is called.
Don't create the array until you have a valid length:
ans = scan.nextInt();
arr = new int[ans]; // Add this line.
cubeToss();
You need to initialize the array after you got the value for ans. Currently you are initialize the Array with ans = 0 at the startup for the program (where ans is 0).
A correct solution may be:
public static void main(String[]args){
Scanner scan = new Scanner(System.in);
System.out.println("How many times would you like to toss the cube?");
arr[] = new int[scan.nextInt()];
public static int arr[] = new int[ans];
From the jls-12.4: when The JVM is still trying to execute the method main of class number_cube, the invocation is permitted only if the class has been initialized. However, Initialization of a class consists of executing its static initializers and the initializers for static fields (class variables) declared in the class.
That is why, static fields declared in class context always gets instantiated first.
For your class which are: int[] arr and int ans. static variable ans initialized to the value 0 which is default value of integer. Hence, Instantiating the static array arr has the length 0 and being empty. When you are trying to access it in the cubeToss() function using a loop, an AIBE 0 is being thrown as the array has length 0(or, the array is empty).
So, after reading the ans in the main method in the main method using ans = scan.nextInt();, try creating the array in the main method: arr = new int[ans]
public static int[] arr;
and then initialize only after getting ans from System.in
Related
I'm extremely new to Java and we're tasked to take random values of an array and pass them through a method where it adds all of them for a running total.
For the sumMethod I'd like to take each value from all the index (given by sizeOfArray) and add them together.
Thank you!
public static void sumMethod(double[] arrayOfDoubles){
//How to get the value from each indexes (given by sizeOfArray) and add them for the sum
int arrayLength = arrayOfDoubles.length;
System.out.println(arrayOfDoubles);
}
public static void main(String[] args) {
//1-3: Set up Scanner object to collect user's input on the size of array.
Scanner keyboard = new Scanner(System.in);
System.out.println("How many double numerical entries do you have?");
//4: Declare an array of size sizeOfArray
int sizeOfArray = keyboard.nextInt();
//Initialize array
double[] arrayOfDoubles;
arrayOfDoubles = new double[sizeOfArray];
for(int i = 0; i < sizeOfArray; i++){
//5: Use the Random number Class and walk over the array
Random randomNum = new Random();
arrayOfDoubles[i] = randomNum.nextDouble(0.0 , 100.0);
//6: Invoke SumMethod
sumMethod(arrayOfDoubles);
}
}
}
public static void sumMethod(double[] arrayOfDoubles) {
double sum = 0;
for (int j = 0; j < arrayOfDoubles.length; j++) {
sum += arrayOfDoubles[j];
}
}
This will work too, if you are not familiar with the for-each loop yet.
Additionally, it is better to use arrayOfDoubles.length in the loop, in case you edit the code later, and change the size, or add or remove an element.
For sumMethod, I'd say the first thing you could do is give it a return value rather than void, (public static double sumMethod). That way when you run that method in main you can hold onto the result it prints out.
I may be wrong but my understanding is that your goal is to take an array and sum up the values within. For that purpose, the following would be a way to do it.
public static double sumMethod(double[] arrayOfDoubles) {
double total = 0;
for (double num : arrayOfDoubles) {
total += num;
}
return total;
}
public class Main
{
public static void main(String[] args)
{
int[] num = {1,2,3,4};
System.out.println(Counter.add(num));
}
}
Class
public class Counter
{
public static int add(int[] numb)
{
for(int i=0;i<numb.length;i++){
numb[i]++;
System.out.println(numb[i]);
int result = result + numb[i];
}
return result;
}
}
I am trying to output the total number in the array list, but with a twist, having +1 to each number in the array list, so 1,2,3,4 would give me 14, as 1+2+3+4 = 10 + 4 (+1 to each number), do I have to use .split to give me the total amount of variable in the array to add onto the total addition?
Do I have to use .split to give me the total amount of variable in the array to add onto the total addition?
No. You can simply return the sum, plus the length of the Array. Also you declare result within the for loop, so it is only in scope within the loop. Move it outside of the loop
public static int add(int[] numb)
{
int result = 0;
for(int i=0;i<numb.length;i++){
System.out.println(numb[i]);
result += numb[i];
}
return result + numb.length;
}
Which, when called with the Array int[] num = {1,2,3,4}; outputs 14.
I want to make a program which, after filling an array in main(), through a method, returns the arithmetic mean of the elements contained in that array.
When I call the method to execute the process (the line where I use the System.out.print) it gives me an error, saying that the method is not applicable for the arguments in it. But it should lead to an array of ints.
Code
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) {
System.out.println(meanArray (2, 6, 9, 19, 1));
}
static int meanArray (int [] a) {
Scanner inputLine = new Scanner(System.in);
int numbers;
int start;
int sum = 0;
int mean;
numbers = inputLine.nextInt();
for (start = 0; start < numbers; start++) {
a[start] = inputLine.nextInt();
sum = sum + a[start];
}
mean = sum/numbers;
return mean;
}
}
When you call
System.out.println (meanArray (2, 6, 9, 19, 1));
it expected a method with a signature like
public static Something meanArray(int a, int b, int c, int d, int e) {
Most likely what you intended was
public static Something meanArray(int... a) {
which accepts a variable number of arguments.
The problem in this code is you create a method that take an integer array as parameter and you send different integer values but not an integer array when calling the method. Instead calling;
meanArray(1,2,4,3)
you should declare integer array and pass the variable to the method.
It will be better to declare array variable first and pass it to the function like:
int a[]={1,2,3,4};
meanArray(a);
And you donot need to declare another numbers variable ( lenth is inbuilt function to return size of an array)inside the method for summing elements of array, try as follows inside the meanArray();
for(start=0;start<a.length;start++){
sum+=a[start];
}
If you want to test the numbers in your code, declare and initialize the array with:
int[] array ={2,6,9,19,1}; and then call meanArray(array);
If you want to test an arbitrary set of numbers from console, you need to declare the array differently with:
int[] array = new int[5]; //*5 states how many numbers you will input from console *
and then you need to change the loop interval to: start < array.length;
I am having trouble printing out the first two columns of the results in a table but as I am new to programming I am having issues and wondering where the issue is in my code. The brief states I must create:
A parameterless static int method, randInt(), that will return a random integer in the range 0..9 inclusive. This method will include a call to Math.random().
A static void method named randTest that takes a single integer argument, n. This should perform the following actions:
Declare an int array of 10 elements named counts. This will be used to record how often each possible value is returned by randInt.
Call randInt n times, each time incrementing the count of the element of counts corresponding to the value returned.
Print the results to the console in a clear tabular form. The output should look like the following:
This is my code:
import java.util.Arrays;
public class RandNumGenerator {
public static int RandInt(){
double n = Math.random()*10;
return (int) n;
}
public static void randTest(int n){
int [] counts = new int [10];
for(int i=0;i<n;i++){
counts[i] = RandInt();
System.out.println(counts[i]);
}
}
public static void main(String[] args) {
int sampleSize = 1000;
System.out.println ("Sample Size: " + sampleSize);
String[] intArray = new String[] {"Value","Count","Expected","Abs Diff","Percent Diff"};
System.out.println(Arrays.toString(intArray));
randTest(10);
}
}
public static void randTest(int n){
Question for you to think about: What is the parameter here? Hint: It's not 10... What do you actually want to DO n times?
counts[i] = RandInt();
You really want to create 10 random numbers and store them into the array? Nope. You want to create "sampleSize" numbers and increase the array on the correct position. What would the correct position be?
counts[ correctPosition ] = counts[ correctPosition ] + 1;
...would be more correct, if you can figure out the correctPosition.
Also I would move the output from the main method to randTest() where you have everything together.
I'm brand new to Java coding i'm trying to create a histogram with the following methods that were given to me. The comments are the instruction to each of our method that we will later use to create a main method and print a histogram. I have got up to method 3 and was able to compile everything fine but i'm not sure if i'm doing them right, I just know that they are compiling correctly up to method 4. I just don't know what to do for method 5.
/*
Method 1:
Find the maximun value in an array
*/
public static int max(int[]arr){
int maxValue = arr[0];
for ( int i=1; i < arr.length; i++ ){
if (arr[i] > maxValue){
maxValue = arr[i];
}
}
return maxValue;
}
/*
Method 2:
Compute a random integer in the range [a..b)
*/
public static int randomInteger(int a, int b){;
int randomNum;
randomNum = a+(int)(Math.random() * ((b-a)+1));
return randomNum;
}
/*
Method 3:
Draw a Simple histogram of the array arr.
*/
public static void drawHistogram(int[] arr){
for ( int i=0; i<arr.length; i++ ){
System.out.print((i*10+1)+"-"+(i*10+10)+":"+"\t");
for (int j=0; j<arr[i]; j++)
System.out.print("*");
System.out.println();
}
}
/*
Method 4:
Compute num random integers in the range [0..range) and put the frequency in arr[]
*/
public static void doSingleTest(int[] arr, int num, int range){
for (int i=1; i<=num; i++){
int random = randomInteger(0,range);
arr[random]++;
}
}
/*
Method 5:
Compute num pairs of random integers in the range [0..range) and put the frequency in arr[]
*/
public static void doPairsTesting(int[] arr, int num, int range){
}
public static void main(String[] args) {
int test[] = new int[]{1,2,3,4,6,11,7};
System.out.println("method1 = "+ max(test));
System.out.println("method2 = "+randomInteger(1,20));
drawHistogram(test);
doSingleTest(test,1,5);
System.out.println("method4 = "+Arrays.toString(test));
}
It's fault design int random = int randomInteger(range); I think you need to read docs abot java basics.
I fixed method4 in next way:
public static void doSingleTest(int[] arr, int num, int range){
for (int i=1; i<=num; i++){
int random = randomInteger(0,range);
arr[random]++;
}
}
For testing your methods, use next main method, it prints results to console or you can use Debugger in your IDE:
public static void main(String[] args) {
int test[] = new int[]{1,2,3,4,6,11,7};
System.out.println("mathod1 = "+ max(test));
System.out.println("mathod2 = "+randomInteger(1,20));
drawHistogram(test);
doSingleTest(test,1,5);
System.out.println("mathod4 = "+Arrays.toString(test));
}
And at last your method 5 must to return value of needed type or be void:
public static void doPairsTest(int[] arr, int num, int range){
}
For computing random integers, you might want to consider using the Random class. Here is some documentation: http://docs.oracle.com/javase/6/docs/api/java/util/Random.html
You can do this by declaring a Random object inside your class like this:
static Random randomGenerator = new Random();
And then within each of your methods, you can use randomGenerator.nextInt(n), where n will be the end of the range you want random numbers to be included. (exclusive of n, starting with 0).
For method 4, you probably want to set the return type to be an array. And then you can either leverage this randomGenerator, or given your current code, you'd have to pass in two parameters to your randomInteger method.
For method 5, you can simply use your doSingleTest method and then divide the entries of your array by 2 before returning the array. This works because if you find two 3s, your doSingleTest would have a frequency of 2 at the appropriate position. And dividing this by 2 would give you the number of pairs. Also you don't have to worry about odd numbers because the int type in Java simply drops remainders.
I also just noticed that you did not set a return type for method 5, so go ahead and set that to be int[]
And use a public static void main(String[] args) method to test your methods.
For method 5, are you referring to the dopairtest? In case so here is how I solved that:
static void doPairsTest(int[] arr3, int num2, int range3){
for (int i = 0 ; i < num2 ; i++) {
int rand2 = randomInteger(0, range3);
int rand3 = randomInteger(0, range3);
int randomPair = (rand2 * 10) + rand3 ;
System.out.println(randomPair);
arr3[randomPair] ++ ;
}
}
As you can see I just declared and assigned randomly generated values from my previous method into rand2 and rand 3 and then I added the two of them so they add up to a double digit.
Did you find out how to do the histogram? I am very confused on how to plot it based on the numbers and frequencies we generated.
public static void drawHistogram(int[] arr){
int n=0;
for (int i=1;i<=99;i++)
if (arr[i]>n)
n=arr[i];
for (;n>0;n--)
{
String r=" ";
for (int i=0;i<=99;i++)
if (n<=arr[i])
{
System.out.print(r+"*");
r=" ";
}
else
r+=" ";
System.out.println();
}
}