Array Index out of Bounds Exception 0 [duplicate] - java

This question already has answers here:
java.lang.ArrayIndexOutOfBoundsException: 0 - Array larger than Index?
(5 answers)
Closed 8 years ago.
When I try to comply I get this Error:
"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0"
I do not know hy
package Darts;
import java.util.Random;
import static java.lang.Integer.*;
/**
* Created by BryanSingh on 12/12/14.
* Dartsim.java
*
*/
public class DartSim
{
public static void main(String[] args)
{
//int trials = 0;
int trials = Integer.parseInt(args[0]);
DartSim myDart = new DartSim();
for (int i=1; i<=trials; i++)
{
myDart.toss();
System.out.println("pi = " + 4.0 * (double) myDart.getHits() / myDart.getThrows());
}
}
private int hits;
private int tries;
private Random gen;
public DartSim()
{
hits = 0;
tries = 0;
gen = new Random();
}
public void toss()
{
double x = 2 * gen.nextDouble() - 1;
double y = 2 * gen.nextDouble() - 1;
if(x*x+y*y<1)
{
hits = hits +1;
}
tries = tries +1;
}
public int getHits()
{
return hits;
}
public int getThrows()
{
return tries;
}
}

You aren't specifying any arguments when you run the program so args[0] isn't a valid index.
// to use 10 when there aren't args...
int trials = (args.length > 0) ? Integer.parseInt(args[0]) : 10;

Array Index Out Of Bounds Exception occurs in a for loop when it attempts to use the value of i in this case and the value of i is less than zero.

java.lang.ArrayIndexOutOfBoundsException: 0 is self explanatory args[0] position of array is not having value, that's why int trials = Integer.parseInt(args[0]); line throwing exception, you have to pass argument to your program.

Related

How to get random numbers with different probabilities in different ranges in java? [duplicate]

This question already has answers here:
Coding pattern for random percentage branching?
(7 answers)
Closed 4 years ago.
I want to get an integer random number between 0 and 100 with different probabilities in different ranges.
For example I want the probability of values between 0 and 20 to be 0.5 and the probability of values between 21 and 80 to be 0.4 and the probability of values between 81 and 100 to be 0.1.
Is there any method or class in Java or any library for Java to do it? If not, how can I do it myself?
You just need to have an extra random number determining the range it should generate:
int getRandomNumberWithRangeProbability() {
double range = Math.random();
if (range < 0.5) {
return randomWithRange(0, 20);
} else if (range < 0.9) {
return randomWithRange(21, 80);
} else {
return randomWithRange(81, 100);
}
}
int randomWithRange(int min, int max) {
int range = (max - min) + 1;
return (int) (Math.random() * range) + min;
}
A small test can be found here.
Credits to AusCBloke for the randomWithRange() method.
You should get random in each range and then get another random between 0 and 1 and treat in your interest
Good Luck
ETG
I can think of this way don't know if there is any inbuilt function for doing this or not
So Make a function that will return random between two integers.
make a variable probable having random value of 1-10
Satisfy these condition
if(probable>=0 && probable<=5){
random = getUniqueRandom(0, 20);
}
else if(probable>=6 && probable<=9) {
random = getUniqueRandom(21, 80);
}
else if (probable == 10) {
random = getUniqueRandom(81, 100);
}
Here is the working implementation
import java.util.Random;
public class Solution {
private static Random r = new Random();
public static void main(String[] args) {
int pro1 = 0, pro2 =0, pro3 =0;
for(int i=0; i<10000; i++) {
int probable = getUniqueRandom(0, 10);
int random = 0;
if(probable>=0 && probable<=5){
random = getUniqueRandom(0, 20);
pro1++;
}
else if(probable>=6 && probable<=9) {
random = getUniqueRandom(21, 80);
pro2++;
}
else if (probable == 10) {
random = getUniqueRandom(81, 100);
pro3++;
}
//System.out.println(random);
}
System.out.println("Checked 10000 Times.\n0-20 Found: "+pro1);
System.out.println("21-80 Found: "+pro2);
System.out.println("81-100 Found: "+pro3);
}
static int getUniqueRandom(int min, int max){
int num = r.nextInt(max-min+1) + min;
return num;
}
}

Weird exponentiation error [duplicate]

This question already has answers here:
Java exponent error at 2^31 power [duplicate]
(2 answers)
Closed 8 years ago.
So, I have this code, which works fine for the first 4 numbers, but then it gives a wrong number, What's the problem? (I know I can also use Math.pow, but I wanted to try doing it myself first)
public static void main(String [] args){
int number = 98;
int result = number;
int exponentt = 5;
int exponent = exponentt--;
System.out.println(Math.pow(number, exponent));
for (int i = 0; i < exponentt ;i++) {
result = result * number;
System.out.println(result );
}
}
Console:
9604
92236816
449273376
Switch your int number to a long and you will get the right result.
public static void main(String [] args){
**long** number = 98;
**long** result = number;
int exponentt = 5;
int exponent = exponentt--;
System.out.println(Math.pow(number, exponent));
for (int i = 0; i < exponentt ;i++) {
result = result * number;
System.out.println(result );
}
}
It's going outside of the range for the int and giving you weird results. int can only store up to 2,147,483,647 -- 98^4 is well over that (9,039,207,968)

A field to count the amount instances of a class [duplicate]

This question already has answers here:
post increment operator java
(3 answers)
Closed 9 years ago.
I need to create a field to count the number of instances made by a class
public class Circle
{
private int diameter;
private int xPosition;
private int yPosition;
private String color;
private boolean isVisible;
private static int count = 0;
/**
* Create a new circle at default position with default color.
*/
public Circle()
{
diameter = 30;
xPosition = 20;
yPosition = 60;
color = "blue";
isVisible = false;
count = count++;
}
public void returnCount(){
System.out.println(count);
}
This is what Ive been playing with. I was hoping the count would increment by 1 each time a variable is created. However it just stays at 0.
Thanks for any help, Ciaran.
Use just:
count++;
Why? because:
count = count ++;
is similar to doing something like this:
temp = count ; // temp is 0.
count = count +1; // increment count
count = temp; // assign temp (which is 0) to count.
Take a look at a similar post-increament question.
The post increment operator implicitly uses a temp variable.
so,
count = count ++;
is not equal to
count++;
in java.
This is because of the invalid use of ++ operator.
Your code can be corrected simply by correcting the line as below.
// count = count++; incorrect
count++; // correct
// count = count + 1; // correct
When you use count++, the count variable is incremented by 1; but the value returned from the operator is the previous value of count variable.
You can learn this by trying the below.
public class Test {
public static void main(String[] args) {
int count = 0;
System.out.println(count++); // line 1
System.out.println(count++);
}
}
When you run above below is the results.
0
1
That is "line 1" prints only 0 since the return value of count++ is always the previous value.

Using loops to compute factorial numbers, Java

I'm trying to compute the value of 7 factorial and display the answer, but when I tried to look up a way to do this I kept finding code that was written so that a number first had to be put in from the user and then it would factor whatever number the user put in. But I already know what number I need, obviously, so the code is going to be different and I'm having trouble figuring out how to do this.
I tried this at first
public class Ch4_Lab_7
{
public static void main(String[] args)
{
int factorial = 7;
while (factorial <= 7)
{
if (factorial > 0)
System.out.println(factorial*facto…
factorial--;
}
}
}
But all it does is display 7*7, then 6*6, then 5*5, and so on, and this isn't what I'm trying to do.
Does anyone know how to do it correctly?
import java.util.Scanner;
public class factorial {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
//Gives Prompt
System.out.print("Enter a number to find the factorial of it");
//Enter the times you want to run
int number = input.nextInt();
//Declares new int
int factor = 1;
//Runs loop and multiplies factor each time runned
for (int i=1; i<=number; i++) {
factor = factor*i;
}
//Prints out final number
System.out.println(factor);
}
}
Just keep multiplying it and until it reaches the number you inputted. Then print.
Input:5
Output:120
input:7
Output:5040
You need to have two variables, one for the factorial calculation and other for the purpose of counter. Try this, i have not tested it but should work:
public static void main(String[] args)
{
int input = 7;
int factorial = 1;
while (input > 0)
{
factorial = factorial * input
input--;
}
System.out.println("Factorial = " + factorial);
}
int a=7, fact=1, b=1;
do
{
fact=fact*b;//fact has the value 1 as constant and fact into b will be save in fact to multiply again.
System.out.print(fact);
b++;
}
while(a>=b); // a is greater and equals tob.
1st reason:
The methods you seen are probably recursive, which you seem to have edited.
2nd:
You are not storing, ANYWHERE the temporal results of factorial.
Try this
//number->n for n!
int number = 7;
//We'll store here the result of n!
int result = 1;
//we start from 7 and count backwards until 1
while (number > 0) {
//Multiply result and current number, and update result
result = number*result;
//Update the number, counting backwards here
number--;
}
//Print result in Screen
System.out.println(result);
Try this:
public static void main(String args[]) {
int i = 7;
int j = factorial(i); //Call the method
System.out.println(j); //Print result
}
public static int factorial(int i) { //Recursive method
if(i == 1)
return 1;
else
return i * factorial(i - 1);
}
This would print out the factorial of 7.
public class Factorial {
public static void main(String[] args) {
int result = factorial(5); //this is where we do 5!, to test.
System.out.println(result);
}
public static int factorial(int n) {
int x = 1;
int y = 1;
for (int i = 1; i <= n; i++) {
y = x * i;
x = y;
}
return y;
}
}
/*so, for 3! for example, we have:
i=1:
y = x * i, where x = 1, so that means:
y = 1*1 ; y= 1; x = y so x = 1. Then i increments =>
i = 2:
y = x * i. x is 1 and i is 2, so we have y = 2. Next step in code: x=y, means x = 2. Then i increments =>
i = 3:
y = x *i so we have y = 2*3. y=6. */

How to nail down the java.lang.ArrayIndexOutOfBoundsException cause?

This is a continuation from:
Recursive Fibonacci memoization.
I keep getting
an java.lang.ArrayIndexOutOfBoundsException error when trying to run the code. I'm getting the error on lines 63 and 40 which are
63: int fib = dictionary[num]; // dictionary is a class level array.
40: answer = fibonacci(num); // Answer is an int calling the fibonacci function and passing "num" to it.
Here is the full code:
import javax.swing.JOptionPane;
public class question2
{
//class variable
static int count = 0;
static int [] dictionary;
//main method
public static void main(String[] args)
{
//user input
int num = Integer.parseInt(JOptionPane.showInputDialog("Enter num:")), answer;
//Catches negative numbers, exits
if (num < 0)
{
JOptionPane.showMessageDialog(null,"ERROR: fibonacci sequence not defined for negative numbers.");
System.exit(1);
}
//info dialog
JOptionPane.showMessageDialog(null,"About to calculate fibonacci("+num+")");
//giving the array "num" elements
dictionary = new int [num];
//fill array with 0
for (int i=0; i<dictionary.length;i++)
dictionary[i]=0;
//adds value of 1 for fib(1)
if (dictionary.length>=2)
dictionary[1]= 1;
//method call
answer = fibonacci(num);
//output
JOptionPane.showMessageDialog(null,"Fibonacci("+num+") is "+answer+" (took "+count+" calls)");
}
static int fibonacci(int num)
{
count++;
// Base cases: f(0) is 0, f(1) is 1
if (num==0)
return 0;
if (num==1)
return 1;
// Other cases: f(num) = f(num-1) + f(num-2)/
else
{
//check array for value
int fib = dictionary[num];
//add new value to array
if (fib==0)
{
fib = fibonacci(num-1) + fibonacci(num-2);
dictionary[num] = fib;
}
return fib;
}
}
} //class terminator
The array is of size num (int fib = dictionary[num];) so the max index you can access is num-1. You try to access index num (dictionary[num] = fib;) which is out of bounds.

Categories

Resources