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
Related
I have a program made in which users can make a self chosen x number of computations. So far so good. After the x number of computations have been made, I want to present the user all the wrong answers during the assessment. Everytime a user answers wrongly the Class "Erroranalysis" will be called. There I want to store the number of the calculation, the components of the calculation (Eg. 12 and 13 for "12+13"), the given answer and the result of the computation. Those are 5 variables. So after the chosen number of calculations have been done I want Java to put out: (Eg.)
"calculation number 3 was wrong. 13 + 18 = 31, you had: 32"
"calculation number 7 was wrong. 21 + 16 = 37, you had: 25"
etc etc
the 'add' is with a red curly stripe underneath. So I have no clue how to add this range of variables into an Array. And also how to get them out accordingly.
import java.util.ArrayList;
public class Erroranalysis
{
static ArrayList<Integer> mistakes = new ArrayList<Integer>();
public static void main(String[] args)
{
if (Sumup.counter <= Numberofcalculations.numcalc)
{
int[][] incorrect = { {Sumup.counter}, {Sumup.part1}, {Sumup.part2}, {Sumup.result}, {Sumup.answer} };
mistakes.add(incorrect);
}
if (Sumup.counter > Numberofcalculations.numcalc)
{
for (int i : mistakes)
System.out.println("Calculation number "+(incorrect[0]) + " was wrong: " + (incorrect[1])+ " + " +(incorrect[2]) + " = " + (incorrect[3])+", you had: "+ (incorrect[4]));
}
}
}
Looks like you declared the wrong ArrayList type. ArrayList accepts a generic parameter that determines the type of the elements in the list.
Try this:
private static ArrayList<int[][]> mistakes = new ArrayList<int[][]>();
By passing Integer, you told the compiler that this is a list of Integer objects (Integer is a wrapper class for the primitive type int). Then, inside the method, you tried to add an element of type int[][] to the list, so you got a compilation error.
Ok I'm sure I'm doing something wrong here.
result = []
for (aMp in arMap) {
println("0 " + result)
println("1 " + aMp)
println("2 " + delegate.findSingleMap(aMp))
result.addAll(delegate.findSingleMap(aMp))
println "3 " + result
}
return result
The println result are the following: (I have 2 element in arMap, so it print the four value 2 times)
0 []
1 [ID:XXX, Type:4]
2 [[First:21/Nov/2013, Type:4, error code:SXR07, ID:XXX, Test ID:5]]
3 [[First:21/Nov/2013, Type:4, error code:SXR07, ID:XXX, Test ID:5]]
0 [[First:21/Nov/2013, Type:4, error code:SXR07, ID:XXX, Test ID:5]]
1 [ID:YYY, Type:4]
2 [[First:12/Oct/2012, Type:4, error code:SXR07, ID:YYY, Test ID:6]]
3 [[First:12/Oct/2012, Type:4, error code:SXR07, ID:YYY, Test ID:6]]
As you can see the findSingleMap function work properly, but the second time I use the AddAll, my result array loose the value XXX.
What am I doing wrong?
As stated by the OP int the comments the method findSingleMap modifies the (global) result variable.
for (aEl in map) {
result = result.findAll { it[aEl.key] == aEl.value }
}
return result
Not writing def in front a variable declares it (in simple scripts) global, which might result in strange behaviour like this. So don't do it, unless you have to codegolf.
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?
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;
Hello guys I'am beginner of the Java and i've got some problems with array&arraylist. My main problem is how to write computing, dynamic data into the array and later how to read it? Here's my weird code:
public static void main(String[] args) {
int yil, bolum = 0, kalan;
Scanner klavye = new Scanner(System.in);
ArrayList liste = new ArrayList();
//or shall i use this? >> int[] liste = new int[10];
System.out.println("Yıl Girin: "); // enter the 1453
yil = klavye.nextInt();
do{ // process makes 1453 separate then write in the array or arraylist. [1, 4, 5, 3]
kalan = yil % 10;
liste.add(kalan); //my problem starts in here. How can i add "kalan" into the "liste".
bolum = yil / 10;
yil = bolum;
}while( bolum == 0 );
System.out.println("Sayının Basamak Sayısı: " + liste.size()); //in here read the number of elements of the "liste"
klavye.close();
}
Edit:
//needs to be like that
while( bolum != 0 );
System.out.println("Sayının Basamak Sayısı: " + liste);
I think that you most likely want your loop stopping condition to be:
while( bolum != 0)
because bolum will only be 0 when there are no more digits left in your number to process. Also, as amit mentions above it could be the case that the user entered 0 when prompted for a number, so you should take that into account.
To obtain a string representation of your ArrayList (showing the elements it contains through their string representations), you can just use
System.out.println("Sayının Basamak Sayısı: " + liste);
No need to convert to an array. This works because it causes liste's toString method to be called (which is why we don't need to call it explicitly).
You must change this line:
}while( bolum == 0 );
To this:
}while( bolum > 0 );
If you want to print your elements in the ArrayList, update your last statement to print as below:
System.out.println("Sayının Basamak Sayısı: " + liste);
Or you can iterate your list and print as :
for(Object i: liste){
System.out.println(i);
}
This will print your individual list items in separate lines.
Also please fix your while condition as while(bolum != 0); as it may terminate after the very first iteration as bolum will be non zero i.e. 1, 2...(!= 0).