I'm using a for loop as a form of validation check to make sure the input for the variable stScore is a number over 0 and under or equal to 100, example shown here, if the input isn't correct, the score parameter will be shown as 0:
for(int i = 0; i < 3; i++)
if ((stScore[i] > 0 && stScore[i] <= 100))
score[i] = stScore[i];
else
score[i] = 0;
My question is if there is any way to display a string (to say something like error!) in place of that 0 instead? Of course at the base of things you can't have an int array include a string, but I was wondering if there is a workaround for this.
Thanks
A workaround would be to ascribe some magic meaning to a particular int value that would never otherwise occur in your data. E.g., declare a constant:
private static final int INVALID_SCORE = -1;
Use it both when assigning:
if ((stScore[i] > 0 && stScore[i] <= 100))
score[i] = stScore[i];
else
score[i] = INVALID_SCORE;
And when printing:
System.out.println(score[i] != INVALID_SCORE ? score[i] : "Invalid score!");
The disadvantage is that it will cause problems if you forget to treat the value specially in later code that uses the data.
No, unfortunately you cannot :(. But we usually don't use 0 as an error code. In these situations I use Integer.MIN_VALUE to indicate an error.
So your code will be like this:
for(int i = 0; i < 3; i++)
if ((stScore[i] > 0 && stScore[i] <= 100))
score[i] = stScore[i];
else
score[i] = Integer.MIN_VALUE;
I suggest you not to use 0. Because 0, when it is an exit code, it usually means "OK". In C++, the main method returns 0 when the program exits with no errors. Alternatively, Integer.MAX_VALUE can be used as well.
For more readable code, you can declare a constant called ERROR:
final int ERROR = Integer.MIN_VALUE;
The best option would be to set any invalid inputs to -1. Then on output you could have an if statement the checks for the error value (-1) and outputs an appropriate error message.
It's bad practice to mix types in any sort of collection; avoid it whenever possible.
throw new IllegalArgumentException("your score is below zero");
That would seem to be appropriate
Related
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;
I'm trying to do a homework assignment. I have to use dynamic programming to display whether the next person to move is in a win/loss state. I don't need help with the actual problem, I need help with an index out of bounds exception I'm getting that baffles me. I'm only going to paste part of my code here, because I only need the for loops looked at. I also don't want anyone in my class seeing all my code and copying it. If you need more data please let me know. So here is the code:
if(primeArray[x] == true){
for(int i = 1; i <= x; i++){
if(primeArray[i]== true){
newRowNumber = x - i;
}
if(dynaProgram[newRowNumber][columnNumber] < minimum){
minimum = dynaProgram[newRowNumber][columnNumber];
}
}
}
//COMPOSITE CASE FOR X!
else{
for(int k = 1; k <= x; k++){
if((primeArray[k] == false)){
newRowNumber = x - k;
}
if(dynaProgram[newRowNumber][columnNumber] < minimum){
minimum = dynaProgram[newRowNumber][columnNumber];
}
}
For some reason the if(primeArray[i] == true runs correctly, but I'm getting index out of bounds exception on if(primeArray[k] == false. The only difference between these two is the use of the variable k over i in the for loop.(the for loops are identical) I haven't used either variables anywhere else in my code. I have no idea why this occurs for one but not the other. In both cases, x remains the same number.
I am also getting an index out of bounds exception on the second minimum = dynaProgram[newRowNumber][columnNumber], while the first doesn't encounter an error. I know it's probably a stupid error, but I can't figure it out. If I change the 'k' for loop to k < x the index of out bounds exception in the if(primeArray[k] == false line goes away, but then it isn't correct. (The error on the second minimum = dynaProgram[newRowNumber][columnNumber] doesn't go away however.)
All this code is in a nested for loop which iterates through the rows and columns in the table to fill them in. If I remove the above code and just put dynaProgram[rowNumber][columnNumber] = 1 I don't have an issue, so I don't believe that is the problem.
When accessing an array of length 5 (for example)
int[] fred = new int[5];
the first element will be fred[0] and the last will be fred[4]
So when doing something like:
if(primeArray[i]== true){
Make sure that i is less than the array length. Using a value of i equal to the array length will throw an exception.
this problem cannot be solved this time, due to major errors in the code which need to be corrected first before submitting the question.
Instead of:
if (result = true)
do
if (result)
Also, instead of:
for (int index = 0; index < lineList.size() - 1; index =+2)
do
for (int index = 0; index < lineList.size(); index +=2)
Edited: Two issues on your for statement:
index < lineList.size() - 1 will not hit the last item. Either remove - 1 or change < for <=
Index does not increment its value. Change index =+2 for index +=2.
One obvious bug I could find was:
if (result = true)
which should be:
if (result == true)
You have a section with two errors. Compare with my sample:
for (int index = 0; index < lineList.size() - 1; index += 2)
if (usr.add(list.get(index))) System.out.println(list.get(index));
Or, in another idiom:
boolean take = true;
for (String line : lineList) {
if (take) usr.add(line);
take = !take;
}
One problem is here:
if (result = true)
You probably meant to write:
if (result == true)
A better way to write this check is:
if (result)
There might also be an off-by-one bug in index < lineList.size() - 1. If the file contains an odd number of lines, your current code will disregard the last line. I say might since it's not entirely clear what you expect to happen in this case.
Finally, the whole thing can be implemented with a single loop and without the list (i.e. just with the set).
I'm trying to make a tetris game for android to help learn game programming for android. My goLeft/Rights break right when the button is pressed, the code for going left is in a class separate of the fields int array, and the list parts array. The fields array is accessed by a referenced variable (TetrisWorld tetrisworld;). While part list array is public so accessed through a variable(part) code for which is in the goLeft() code. It breaks at: if(tetrisworld.fields[x][part.y] != 0) Code for left:
public void goLeft() {
int x = 0;
for(int i = 0; i < 4; i++) {
TetrisParts part = parts.get(i);
x = part.x - 1;
if(tetrisworld.fields[x][part.y] != 0) {
noleft = true;
break;
}
}
if(noleft == false) {
for(int i = 0; i < 4; i++) {
TetrisParts part = parts.get(i);
part.x--;
}
}
}
The code for the fields int array:
int fields[][] = new int[WORLD_WIDTH][WORLD_HEIGHT];
WORLD_WIDTH and WORLD_HEIGHT are both static final ints, width being 9 and height being 19
I've tried putting if(tetrisworld.fields[0][0] == 0) and it still crashes so I don't think it has to do with the variables. Also It doesn't go out of bound even if I haven't added the code to check for that yet because I have the teroid spawning around x = 5 and since I can't go left/right once there's not a chance of that happening
I've tried moving the goLeft/Right methods to the gamescreen class which has a "world = TetrisWorld();" and it still bugs out at the same spot
UPDATE:
Ok just adding:
tetrisworld != null
to the first if statement fixed it, my question now is, why did it fix it? Why can't I move without this check? It clearly isn't null cause as far as I know; it's fully responsive now.
But an easier way to have solved this which is SOOOO easy is changing fields to static... then access it lika so: TetrisWorld.fields so my updated code is:
public void goLeft()
{
noleft = false;
for (int i = 0; i < 4; i++)
{
part = parts.get(i);
if (part.x - 1 < 0 || TetrisWorld.fields[part.x - 1][part.y] != 0)
{
noleft = true;
break;
}
}
if (noleft == false)
{
for (int i = 0; i < 4; i++)
{
part = parts.get(i);
part.x--;
}
}
}
Looks like you are hitting IndexOutOfBoundsException.
When you are doing x = part.x - 1;, your x variable can become lesser tan zero, thus your code will act like if(tetrisworld.fields[-1][part.y] != 0
It looks like you're getting a java.lang.NullPointerException when trying to access the array in tetrisworld. In the line you mention there are several ways that this could occur:
if(tetrisworld.fields[x][part.y] != 0) {
tetrisworld could be null.
The fields member of tetrisworld could be null.
The second array that you're looking up by using tetrisworld.fields[x].
The value of part could be null.
Having a quick look through your source code it looks to me like you never initialise tetrisworld, either at declaration using:
TetrisWorld tetrisworld = new TetrisWorld();
Or at some other point which is certain to have happened before your goLeft() method is called.
Ok I believe I found the answer, referencing: http://en.wikipedia.org/wiki/Null_Object_pattern
Apparently java will throw an NPE if you don't check for it first if you have a null reference? Is there any way to initialize it without doing a TetrisWorld tetrisworld = new TetrisWorld(); because it's already created in a different class so i get a thousand errors, an actual stack overflow! lul... Still not 100% positive. Please comment to verify and possibly suggest a better way to go about this.
I was wondering, do you have a neat way of doing this ?
if(orderBean.getFiles().size() > 0 && orderBean.getFiles().size() < 5)
without declaring a variable that is not needed anywhere else ?
int filesCount = orderBean.getFiles().size();
if(filesCount > 0 && filesCount < 5) {
I mean, in for loop we are "declaring conditions" for the actual iteration, one can declare a variable and then specify the conditions. Here one can't do it, and neither can do something like
if(5 > orderBean.getFiles().size() > 0)
Simple utility method:
public static boolean isBetween(int value, int min, int max)
{
return((value > min) && (value < max));
}
Several third-party libraries have classes encapsulating the concept of a range, such as Apache commons-lang's Range (and subclasses).
Using classes such as this you could express your constraint similar to:
if (new IntRange(0, 5).contains(orderBean.getFiles().size())
// (though actually Apache's Range is INclusive, so it'd be new Range(1, 4) - meh
with the added bonus that the range object could be defined as a constant value elsewhere in the class.
However, without pulling in other libraries and using their classes, Java's strong syntax means you can't massage the language itself to provide this feature nicely. And (in my own opinion), pulling in a third party library just for this small amount of syntactic sugar isn't worth it.
If getFiles() returns a java.util.Collection, !getFiles().isEmpty() && size<5 can be OK.
On the other hand, unless you encapsulate the container which provides method such as boolean sizeBetween(int min, int max).
This is one ugly way to do this. I would just use a local variable.
EDIT: If size() > 0 as well.
if (orderBean.getFiles().size() + Integer.MIN_VALUE-1 < Integer.MIN_VALUE + 5-1)
java is not python.
you can't do anything like this
if(0 < i < 5) or if(i in range(0,6))
you mentioned the easiest way :
int i = getFilesSize();
if(0 < i && i < 5){
//operations
}
of
if(0 < i){
if(i < 5){
//operations
}
}
If this is really bothering you, why not write your own method isBetween(orderBean.getFiles().size(),0,5)?
Another option is to use isEmpty as it is a tad clearer:
if(!orderBean.getFiles().isEmpty() && orderBean.getFiles().size() < 5)
Please just write a static method somewhere and write:
if( isSizeBetween(orderBean.getFiles(), 0, 5) ){
// do your stuff
}
Nowadays you can use lodash:
var x = 1;
var y = 5;
var z = 3;
_.inRange(z,x,y);
//results true