Java Array Index Out of Bounds Exception No matter the array length - java

package helloworld;
public class windspeed {
public static void main(String args[]) {
int t = Integer.parseInt(args[44]); //this is the array input for temperature
int v = Integer.parseInt(args[15]); //this is the array input for wind speed
double x = Math.pow(v, 0.16); //this is the exponent math for the end of the equation
if (t < 0) {
t = t*(-1); //this is the absolute value for temperature
}
double w = (35.74 + 0.6215*t)+((0.4275*t - 35.75)* x); //this is the actual calculation
if (t<=50 && v>3 && v<120) { //this is so the code runs only when the equation works
System.out.println(w);
}
if (t>50 || v<3 || v>120){
System.out.println("The wind chill equation doesn't work with these inputs, try again.");
}
}
}
This gives me an ArrayIndexOutOfBounds error. It doesn't matter what I put in the [] I get an error... why? and how can I fix it?

The reason is
int t = Integer.parseInt(args[44]);
Do you have 45 arguments?

The problem here is the way in which you are creating the arrays:
int t = Integer.parseInt(args[44]); //this is the array input for temperature
int v = Integer.parseInt(args[15]); //this is the array input for wind speed
args refers to the command line arguments that are passed to the main() method of your program. If you try to parse args[44] when there aren't 45 arguments (0 indexing, remember ?) you will end up assigning null to your array.
So, all you will later end up with is an ArrayIndexOutOfBoundsException becuase you cannot index a null array.
int t[] = new int[44]; // please notice the brackets
int v[] = new int[15]; //this is the array input for wind speed
The above method shall suffice if all you need is the size
Arrays in Java are int[] t or int t[]. Either of them will do but the brackets need to be there.
Use Math.abs() to find the absolute value. Saves you the if()

int t = Integer.parseInt(args[44]); //this is the array input for temperature
int v = Integer.parseInt(args[15]); //this is the array input for wind speed
args i.e. args is the command line arguments for main method. Do you have 45 elements inside the args if not than it will throw ArrayIndexOutOfBounds.
To know the length please use:
args.length
Than you can proceed. Hope it helps.

In these lines :
int t = Integer.parseInt(args[44]); //this is the array input for temperature
int v = Integer.parseInt(args[15]); //this is the array input for wind speed
You say that you run your program with at least 45 parameters!! where on the 15. place is wind speed and on the 44. is temperature.
You probably running program with NO parameters at all or with one.
Note that if you run program with parameters : "hello world how are you" the program would have args of size 5 with having hello in args[0], world in args[1] etc.

What you have now is:
- take the 15th command line argument and cast to to Integer;
- take the 44th command line argument and cast it to Integer.
Are you sure that it is what you need?

Related

Error showing up while printing GCD

I came across a question which says to input two numbers and print
their GCD(Greatest common Divisor).
Here is the code which i wrote:
import java.io.*;
class gcd {
public static void main(String args[]) throws IOException{
static int m=0;
static int gcd=0;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter two integers");
String s1=br.readLine();
int g1=Integer.parseInt(s1);
String s2=br.readLine();
int g2=Integer.parseInt(s2);
int maxim=Math.max(g1,g2);
int minim=Math.min(g1,g2);
while(m!=0){
m = maxim % minim;
if(m == 0){
gcd=minim;
}
maxim=minim;
minim=m;
}
System.out.println("GCD="+minim);
}
}
If i enter two numbers, say 25 and 45, the GCD result should be 5. However, the output is coming as 25.
Please find out the error in my code.
You should still be getting compilation errors with declaration of 'm' and 'gcd' as static. You do not need to declare them static.
The other bug you have is, you are initializing m to 0, and the while loop statement is
while(m!=0){
so the while loop will not get executed even once since the condition 'm != 0' is false. This explains why the output is 25 when your input is 45 and 25. Consider using a do-while loop so that the loop gets executed at least once. Another bug is that your final print statement is printing the value of 'minim', is that what you want? Shouldn't you be printing the variable that stores the final gcd value. I have given you all the hints so that you have the satisfaction of fixing the bugs by yourself!
Firstly, I will recommend to create a function and then do the calculation.
Your code is incorrect
maxim = 45
minim = 25
m = maxim %minim // m=45%25 = 20
m !=0
maxim = minim // maxim=minim=25
m=minim // m=25
//In your next iteration
maxim=25
minim=25
m = maxim %minim // m=25%25 = 0
m==0
gcd= minim // i.e 25
So, your code is incorrect
Try this -
public static void gcd(int a, int b)
{
if(a==b)
return a;
else if(a>b)
return gcd(a-b,b);
else
return gcd(a,b-a);
}

Java Sort Data From A File Method writeToFile

I have to write a method to write data to a file. It has to take an array of integers as a parameter and write them to a file, but I am getting an error on these lines:
Integer[] x = val.toArray(new Integer[val.size(25)]);
if (x < 0) break;
public static void writeToFile (String filename, int[] x) throws IOException {
PrintWriter outputWriter = new PrintWriter("integers.txt");
System.out.println("Please enter 25 scores.");
System.out.println("You must hit enter after you enter each score.");
Scanner sc = new Scanner(System.in);
int score = 0;
while (score < 25) {
int val = sc.nextInt();
Integer[] x = val.toArray(new Integer[val.size(25)]);
if (x < 0) break;
outputWriter.println(x);
score++; }
outputWriter.flush();
outputWriter.close();
}
There are a couple of things. First off, you are trying to do things that are not possible to do with an int. Look at the ever helpful java API when trying to use a class:
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html
Next, if I was writing your program (which I'm not and I do not intend to), I would watch your instantiations. The array is being instantiated every loop which means that you will have a new array every time the user puts in a value. Meaning all the previous numbers are going to be lost. Also, take the integer array out of the parameter. You aren't even using it in the method.
Instantiate your array outside of the loop with a size of 25 elements:
int[] array = new int[25];
Now, you can place the items in this array every loop like this:
array[score] = val;
This places the value in the indexes 0 -> 24. It seems to me that in order to truly understand how to do this program you are going to have to have a refresher on arrays and how they work.
Finally, the computer sees this method as a sequence. So, line by line think about what is happening on your program. Ideally, this is what should be happening.
Instantiate your objects: the scanner, the array (where the ints are stored), the Print writer
give instructions to the user how to use the program.
run a loop 25 times doing this:
- scanning in an int
- placing the int into the array at the appropriate index
write the array into the file
flush the writer.
close the writer.

Java Error - .charAt() returning two characters in a string of numbers

I am selecting certain digits out of a large number. I'm saving the number in a string, and then saving each character as a subarray. This is what I have so far (I'm not finished). But when this code runs, System.out.print(v[0]) returns "55". I can't understand why. Printing anything else returns a similiarly (seemingly) random two numbers.
Thanks!
public class P432 { public static void main(String[] args) {
String x = "73167176531330624919225119674426574742355349194934"+
"96983520312774506326239578318016984801869478851843"+
"85861560789112949495459501737958331952853208805511"+
"12540698747158523863050715693290963295227443043557"+
"66896648950445244523161731856403098711121722383113"+
"62229893423380308135336276614282806444486645238749"+
"30358907296290491560440772390713810515859307960866"+
"70172427121883998797908792274921901699720888093776"+
"65727333001053367881220235421809751254540594752243"+
"52584907711670556013604839586446706324415722155397"+
"53697817977846174064955149290862569321978468622482"+
"83972241375657056057490261407972968652414535100474"+
"82166370484403199890008895243450658541227588666881"+
"16427171479924442928230863465674813919123162824586"+
"17866458359124566529476545682848912883142607690042"+
"24219022671055626321111109370544217506941658960408"+
"07198403850962455444362981230987879927244284909188"+
"84580156166097919133875499200524063689912560717606"+
"05886116467109405077541002256983155200055935729725"+
"71636269561882670428252483600823257530420752963450";
int[] v = new int[1000];
for (int g=0; g<1000; g++)
{
v[g] = x.charAt(g);
}
System.out.print(v[0]);
}}
As Jim said, you need to change the array to be char instead of int.
By the way, you can use v.length instead of the number 1000 in the for loop.
.length returns the length (size) of the array (1000 in this case), so if you'll want to change the array size in the future - you won't need to change the for loop condition.

preventing Array index out of bounds exception with coins

I am trying to figure out a way to separate a monetary value into quarters, dimes, nickels and pennies in the most efficient way. This is currently my code:
public class CoinReader {
private static int amount = 0;
public static void main(String[] args) {
amount = (int)(Double.parseDouble(args[0])*100);
System.out.println("Five: " + computeCoin(500));
System.out.println("one: " + computeCoin(100) );
System.out.println("Q : " + computeCoin(25) );
System.out.println("D : " + computeCoin(10) );
System.out.println("N : " + computeCoin(5) );
System.out.println("P : " + computeCoin(1) );
}
public static int computeCoin(int cointValue) {
int val = amount / cointValue;
amount -= val * cointValue;
return val;
}
}
I am currently getting an Array index out of bounds exception and I know it has something to do with the String array and the amount variable but I am trying to learn about arrays and I am trying to get this program to work. Any help would be appreciated. Thanks.
You are using args[0] and args appears to be empty.
How do you call your program ? You must have forgotten to pass a parameter.
args array is empty, there is no element with index 0. You have to pass one command line argument to your program. When running from a command line make sure you pass a numeric value as an argument like this:
java CoinReader 113.25
It runs:
javac CoinReader.java
java CoinReader 1230
Ouput
Five: 246
one: 0
Q : 0
D : 0
N : 0
P : 0
Have fun to make it work correctly :-P
EDIT:
As already mentioned by the other guys the parameter String args[] refers to the arguments you provide on the command line when you run your compiled Program. You'll get an ArrayOutOfBondsException when you provide no argument as the array will be empty then.
When I say Have fun to make it work I mean that there seems to be an error in your computeCoin method as it won't output results for P, N, D and Q. But this is beyond your initial question.
SECOND EDIT:
It not just runs. It runs perfectly fine.
java CoinReader 10.11
Output:
Five: 2
one: 0
Q : 0
D : 1
N : 0
P : 1

Trying to Make an Average Finder, Not Using ReadLine(), using Only Console

New to Java, basically started yesterday.
Okay, so here's the thing.
I'm trying to make an 'averager', if you wanna call it that, that accepts a random amount of numbers. I shouldn't have to define it in the program, it has to be arbitrary. I have to make it work on Console.
But I can't use Console.ReadLine() or Scanner or any of that. I have to input the data through the Console itself. So, when I call it, I'd type into the Console:
java AveragerConsole 1 4 82.4
which calls the program and gives the three arguments: 1, 4 and 82.4
I think that the problem I'm having is, I can't seem to tell it this:
If the next field in the array is empty, calculate the average (check Line 14 in code)
My code's below:
public class AveragerConsole
{
public static void main(String args[])
{
boolean stop = false;
int n = 0;
double x;
double total = 0;
while (stop == false)
{
if (args[n] == "") //Line 14
{
double average = total / (n-1);
System.out.println("Average is equal to: "+average);
stop = true;
}
else
{
x = Double.parseDouble(args[n]);
total = total + x;
n = n + 1;
}
}
}
}
The following error appears:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at AveragerConsole.main(AveragerConsole.java:14)
for(String number : args) {
// do something with one argument, your else branch mostly
}
Also, you don't need n, you already have the number of arguments, it's the args length.
This is the simplest way to do it.
For String value comparisons, you must use the equals() method.
if ("".equals(args[n]))
And next, the max valid index in an array is always array.length - 1. If you try to access the array.length index, it'll give you ArrayIndexOutOfBoundsException.
You've got this probably because your if did not evaluate properly, as you used == for String value comparison.
On a side note, I really doubt if this if condition of yours is ever gonna be evaluated, unless you manually enter a blank string after inputting all the numbers.
Change the condition in your while to this and your program seems to be working all fine for n numbers. (#SilviuBurcea's solution seems to be the best since you don't need to keep track of the n yourself)
while (n < args.length)
You gave 3 inputs and array start couting from 0. The array args as per your input is as follows.
args[0] = 1
args[1] = 4
args[2] = 82.4
and
args[3] = // Index out of bound
Better implementation would be like follows
double sum = 0.0;
// No fault tolerant checking implemented
for(String value: args)
sum += Double.parseDouble(value);
double average = sum/args.length;

Categories