I make chessboard, where alone king will walk according to the rules of chess.
Below it's method to make, it called for 2 times for i and j coordinate of King, I Made input variable String to check if this King's coordinates already exist. Than I try to convert it to integer, seems something wrong with this conversion.
import java.util.*;
public class King {
int move(String iK){
Random rand = new Random();
Integer coordinateKing = Integer.valueOf(iK);
if (iK == null){
coordinateKing = rand.nextInt(8);
}else{
int caseI;
switch(caseI = rand.nextInt(2)){
case 0: if (coordinateKing < 8){ coordinateKing++; } else {caseI = rand.nextInt(2);}
break;
case 1: if (coordinateKing > 0){ coordinateKing--; } else {caseI = rand.nextInt(2);}
break;
default:
break;
}
}
return coordinateKing;
}
}
I have problem like this:
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:454)
at java.lang.Integer.valueOf(Integer.java:582)
at chess_engine.King.move(King.java:6)
at chess_engine.MainClass.main(MainClass.java:12)
Thanks in advance!
You're attempting to convert iK to an integer before you check to see if it's null. This line is where the exception is thrown:
Integer coordinateKing = Integer.valueOf(iK);
But you check if (iK == null) on the line following that. You should do a null test first. You can fix this by declaring coordinateKing before your if statement and setting its value in the if...else blocks.
Integer coordinateKing = 0;
if (iK == null){
coordinateKing = rand.nextInt(8);
} else {
coordinateKing = Integer.valueOf(iK);
int caseI;
...
}
You call this
Integer coordinateKing = Integer.valueOf(iK);
but iK can be NULL there. do your null check first
The exception is pretty self-explanatory. iK is a null String, which can't be converted to an Integer. What Integer do you want when iK is null?
It is a runtime error: here the iK is receiving a null value and an Integer object can store null but the method valueOf() internally uses the parseInt() method which returns an int value and a null cannot be converted to int
Related
I am making a Hash Table in java.
In searching function, I am doing some comparison in IF statement. but it is not doing any comparison.
here's is some part of my code.
while (table[pos]!=null) {
if (table[pos]==key) {
System.out.println("SEARCH "+key+" at INDEX "+home);
return;
}
else {pos=h(home+p(i));
i++;
}
}
System.out.println("Failed to find "+key+".");
return;
}
It doesn't work even when table[pos] and key are the same!
but I add very simple assigning variable to another one. It work! I don't know why it works. I wanna know it xD
while (table[pos]!=null) {
int x = table[pos];
if (x==key) {
System.out.println("SEARCH "+key+" at INDEX "+home);
return;
}
else {pos=h(home+p(i));
i++;
}
}
System.out.println("Failed to find "+key+".");
return;
}
Well, if table[pos] and key are both Integer (and table[pos] must be a reference type, since you are comparing it to null in the while statement), they should be compared with equals, not with ==, since two different Integer objects may have the same int value.
When you assign table[pos] to the int variable x, it is un-boxed to a primitive value.
Now, when you compare the int x to the Integer key, the key is also un-boxed to an int, and int comparison works with ==.
This can be demonstrated by the following short example:
Integer i1 = 300;
Integer i2 = 300;
System.out.println (i1 == i2);
int i3 = i1;
System.out.println (i3 == i2);
which outputs:
false
true
The code code would be:
while (table[pos] != null) {
if (table[pos].equals(key)) {
System.out.println("SEARCH "+key+" at INDEX "+home);
return;
} else {
pos = h(home + p(i));
i++;
}
}
System.out.println("Failed to find "+key+".");
When comparing two objects with ==, you check if both of these references point to the same place in the memory, while using == with primitives simply checks if values are the same. To correctly check equation of values inside two Integers you should use equals() method.
In your second example you used unboxing from Integer to int so it checked values as you expected it to do. In the first one you compared if both values point to the same place in memory.
Actually the correct way is to use both just like HashMap does for example, this way we will always be sure. This is for example how HashMap does it internally:
if(((k = first.key) == key || (key != null && key.equals(k)))) ...
So in your case it would be:
if ((table[pos] == key) || (key != null && (table[pos].equals(key)))) {
Problem:
Remove the substring t from a string s, repeatedly and print the number of steps involved to do the same.
Explanation/Working:
For Example: t = ab, s = aabb. In the first step, we check if t is
contained within s. Here, t is contained in the middle i.e. a(ab)b.
So, we will remove it and the resultant will be ab and increment the
count value by 1. We again check if t is contained within s. Now, t is
equal to s i.e. (ab). So, we remove that from s and increment the
count. So, since t is no more contained in s, we stop and print the
count value, which is 2 in this case.
So, here's what I have tried:
Code 1:
static int maxMoves(String s, String t) {
int count = 0,i;
while(true)
{
if(s.contains(t))
{
i = s.indexOf(t);
s = s.substring(0,i) + s.substring(i + t.length());
}
else break;
++count;
}
return count;
}
I am just able to pass 9/14 test cases on Hackerrank, due to some reason (I am getting "Wrong Answer" for rest of the cases). After a while, I found out that there is something called replace() method in Java. So, I tried using that by replacing the if condition and came up with a second version of code.
Code 2:
static int maxMoves(String s, String t) {
int count = 0,i;
while(true)
{
if(s.contains(t))
s.replace(t,""); //Marked Statement
else break;
++count;
}
return count;
}
But for some reason (I don't know why), the "Marked Statement" in the above code gets executed infinitely (this I noticed when I replaced the "Marked Statement" with System.out.println(s.replace(t,""));). I don't the reason for the same.
Since, I am passing only 9/14 test cases, there must be some logical error that is leading to a "Wrong Answer". How do I overcome that if I use Code 1? And if I use Code 2, how do I avoid infinite execution of the "Marked Statement"? Or is there anyone who would like to suggest me a Code 3?
Thank you in advance :)
Try saving the new (returned) string instead of ignoring it.
s = s.replace(t,"");
replace returns a new string; you seemed to think that it alters the given string in-place.
Try adding some simple parameter checks of the strings. The strings shouldn't be equal to null and they should have a length greater than 0 to allow for counts greater than 0.
static int maxMoves(String s, String t) {
int count = 0,i;
if(s == null || s.length() == 0 || t == null || t.length() == 0)
return 0;
while(true)
{
if(s.contains(t) && !s.equals(""))
s = s.replace(t,""); //Marked Statement
else break;
++count;
}
return count;
}
You might be missing on the edge cases in the code 1.
In code 2, you are not storing the new string formed after the replace function.
The replace function replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
Try this out:
public static int findCount(String s, String t){
if( null == s || "" == s || null == t || "" == t)
return 0;
int count =0;
while(true){
if(s.contains(t)){
count++;
int i = s.indexOf(t);
s = s.substring(0, i)+s.substring(i+t.length(), s.length());
// s = s.replace(t,"");
}
else
break;
}
return count;
}
String r1="ramraviraravivimravi";
String r2="ravi";
int count=0,i;
while(r1.contains(r2))
{
count++;
i=r1.indexOf(r2);
StringBuilder s1=new StringBuilder(r1);
s1.delete(i,i+r2.length());
System.out.println(s1.toString());
r1=s1.toString();
}
System.out.println(count);
First of all no logical difference in both the codes.
All the mentioned answers are to rectify the error of code 2 but none told how to pass all (14/14) cases.
Here I am mentioning a test case where your code will fail.
s = "abcabcabab";
t = "abcab"
Your answer 1
Expected answer 2
According to your code:
In 1st step, removig t from index 0 of s,
s will reduce to "cabab", so the count will be 1 only.
But actual answer should be 2
I first step, remove t from index 3 of s,
s will reduced to "abcab", count = 1.
In 2nd step removing t from index 0,
s will reduced to "", count = 2.
So answer would be 2.
If anyone know how to handle such cases, please let me know.
Okay, so, what I have, is supposed to be a simple dice roller. 2 textfields, one for the number of die you want to roll, and the other for the total. (Well, and a third for each individual die rolled, but that's besides the point) This works fine, as long as the number of die text field isn't empty. When the field is empty, I just get a NumberFormatException
My code:
Button d4 = new Button("d4 ");
d4.setLayoutX(240);
d4.setLayoutY(90);
d4.addEventHandler(ActionEvent.ACTION, new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent actionEvent) {
tooltip.setText("");
int d4_num = Integer.parseInt(d4_text.getText()); //d4_text is for the number of die
d4_num = d4_num + 1;
int sum = 0;
for (int i = 1; i < d4_num; i++){
int result = 1 + (int)(Math.random() *4);
sum = sum += result;
tooltip.appendText((String.valueOf("d4_" + i + " =" + result + "\n")));
}
d4_result.setText(String.valueOf(sum));
}
});
I've tried checking the value of d4_text in different ways, each one either giving an error because I can't check for null, or a string, or whatever.
To safely check for 'whether the field contains an integer value' you could do the following:
final String fieldValue = d4_text.getText();
if (fieldValue != null && fieldValue.matches("\\d+")) {
int d4_num = Integer.parseInt(fieldValue);
... the rest of your logic that relies on having a correct d4_num value
} else {
... output some error message like 'please enter a few digits'
}
Here you check that the field contains a non-null string which consists only of digits, at least one.
There is still a possibility that a user would break this entering a number that is too long for int; you could also add some reasonable restriction on field value length:
if (fieldValue != null && fieldValue.matches("\\d{2}")) {
Here, only numbers consisting exactly of 2 digits will be accepted.
Try this before pass the integer value
if (d4_text.getText() == null || d4_text.getText().trim().isEmpty()) {
// your code here }
You can catch that exception, and set it to zero in case of NumberFormatException
int d4_num;
try {
d4_num = Integer.parseInt(d4_text.getText());
} catch (NumberFormatException e) {
d4_num = 0;
}
I've tried checking the value of d4_text in different ways, each one
either giving an error because I can't check for null, or a string, or
whatever.
First : check that the field is not null (Note that by default Java FX input textfields are not null but a tricky client code may change it) and not empty(by trimming the whitespaces).
Second : check that it is a number or catch the exception.
Using an Integer rather than int helps to determinate if the submitted value is a Integer. Integer that accepts the null value may convey a failing input but int that is necessary valued with a numeric value cannot.
Integer d4_num = null;
String textToConvertToInt = d4_text.getText();
if (textToConvertToInt != null && !textToConvertToInt.trim().equals("")){
try{
d4_num = Integer.parseInt(textToConvertToInt);
}
catch (NumberFormatException e){
// handle the exception
}
}
You can also use apache-common-lang to do it :
String textToConvertToInt = d4_text.getText();
Integer d4_num = null;
if (NumberUtils.isNumber(textToConvertToInt)){
d4_num = Integer.parseInt(textToConvertToInt );
}
I am trying to send two variables from one sketch to another, using the oscP5 library for processing.
The message I am sending is created like this:
OscMessage myMessage = new OscMessage("/test");
myMessage.add(title);
myMessage.add("Zeit");
oscP5.send(myMessage, remoteLocation);
In the second sketch, I receive the data like that:
void oscEvent(OscMessage theOscMessage) {
if(theOscMessage.checkAddrPattern("/test")) {
String title = theOscMessage.get(0).stringValue();
String layoutType = theOscMessage.get(1).stringValue();
addToQueue(title, layoutType);
}
}
And here my simplified addToQueue function:
void addToQueue(String title, String layoutType) {
if(!existsInQueues(title)) {
upcomingHeadlines.add(new Headline(title, printAxis, scrollSpeed, layoutType));
}
}
Every time I start the sketches, I get the error:
ERROR # OscP5 ERROR. an error occured while forwarding an OscMessage to a method in your program. please check your code for any possible errors that might occur in the method where incoming OscMessages are parsed e.g. check for casting errors, possible nullpointers, array overflows ... .
method in charge : oscEvent java.lang.reflect.InvocationTargetException
I have been able to track the problem down to the layoutType-Variable. If I change
String layoutType = theOscMessage.get(1).stringValue();
to
String layoutType = "Zeit";
no error occurs.
That is quite confusing, because both versions should have the same result.
The error message does not help me in any way.
Edit
I have compared the two possible variables like that:
String layoutType = theOscMessage.get(1).stringValue();
String layoutTypeB = "Zeit";
if(layoutType.equals(layoutTypeB)) println("Same String!");
Since gets printed to the console, both have to be the same … I really do not know where to search for an error anymore.
Edit 2
I have wrapped my second sketch in try {...} catch(Exception ex) {ex.printStackTrace();} like that:
void oscEvent(OscMessage theOscMessage) {
try {
if(theOscMessage.checkAddrPattern("/test")) {
if(debug && debugFeed) println("Received message from other sketch.");
String title = theOscMessage.get(0).stringValue();
String layoutTypeO = (String)theOscMessage.get(1).stringValue();
String layoutType = "Zeit";
if(debug && debugTemp) {
if(layoutType.equals(layoutTypeO)) println("IS DOCH GLEICH!");
}
if(debug && debugFeed) println("Parsed Information.");
if(debug && debugFeed) println("-----");
addToQueue(title, layoutTypeO);
}
} catch(Exception ex) {ex.printStackTrace();}
}
That gives me this error as result:
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:635)
at java.util.ArrayList.get(ArrayList.java:411)
at printer$Headline.useLayout(printer.java:260)
at printer$Headline.<init>(printer.java:188)
at printer.addToQueue(printer.java:407)
at printer.oscEvent(printer.java:395)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at oscP5.OscP5.invoke(Unknown Source)
at oscP5.OscP5.callMethod(Unknown Source)
at oscP5.OscP5.process(Unknown Source)
at oscP5.OscNetManager.process(Unknown Source)
at netP5.AbstractUdpServer.run(Unknown Source)
at java.lang.Thread.run(Thread.java:744)
Edit 4
Constructor for my Headline-Class:
class Headline {
//Define Variables
Layout layout;
String title, lastHeadline;
float yPos, speed;
float transparency = 255;
boolean fullyPrinted = false;
int boundingBoxHeight;
// Initialize Class Function
Headline(String t, float y, float s, String lay) {
title = t;
yPos = y;
speed = s;
layout = useLayout(lay);
boundingBoxHeight = calculateTextHeight(title);
}
You might want to know about useLayout() too, so here it is:
Layout useLayout(String name) {
ArrayList layoutVariants = new ArrayList<Layout>();
int existingLayouts = layouts.size();
Layout chosenLayout;
for(int i = 0; i < existingLayouts; i++) {
Layout currentLayout = (Layout)layouts.get(i);
if(currentLayout.layoutType == name) {
layoutVariants.add(currentLayout);
}
}
if(layoutVariants != null) {
int rand = (int)(Math.random() * layoutVariants.size());
chosenLayout = (Layout)layoutVariants.get(rand);
} else {
chosenLayout = (Layout)layouts.get((int)(Math.random() * existingLayouts));
}
return chosenLayout;
}
There are two problems with your code, and both of them are in your useLayout method.
The first problem is that you are not comparing Stringss correctly on this line:
if(currentLayout.layoutType == name) {
name is a String, and I assume currentLayout.layoutType is too. Two Strings that are equal but not the same will not compare equal under ==. As a result of this, your layoutVariants list will quite probably be empty at the end of the for loop.
This line should read:
if(currentLayout.layoutType.equals(name)) {
See also this question.
The second problem is that you don't correctly handle the case that the layoutVariants list is empty. The problem is on this line:
if(layoutVariants != null) {
layoutVariants will never be null, so the else branch of this if statement will never execute. Because layoutVariants.size() will be zero, rand will always be zero. Trying to get the element at index 0 in an empty ArrayList will give you precisely the IndexOutOfBoundsException you are seeing.
I imagine you want the else block to execute if the layout name given isn't recognised, in other words, if the layoutVariants list is empty, rather than null. In that case, change this line to
if(!layoutVariants.isEmpty()) {
Note the ! (not-operator) before layoutVariants. You want the code under the if statement to run if the layoutVariants element is not empty.
EDIT in response to your comments: a null ArrayList is very much not the same as an empty one. null is a special value meaning that the variable doesn't have an object of a given type.
Let's try a real-world analogy: a shopping bag. If you have an empty bag, or no bag at all, then you have no shopping either way. However, you can put things into an empty bag, and count how many items it contains, for example. If you don't have a bag, then it doesn't make sense to put an item in it, as there's no bag to put the item into. null represents the case where you don't have a bag.
Similarly, a String is a collection of characters, and the collection of characters can exist even if it doesn't contain any characters.
isEmpty() can be used for any collection, and, if you're using Java 6 or later, Strings as well. Off the top of my head I can't name any other classes that have an isEmpty method. You'll just have to consult the documentation for these classes to find out.
I've not worked with Processing much, but I am aware that Processing is built on Java, so I would expect any standard Java method to work. Also, I wouldn't worry about 'clearing' a variable: the JVM is generally very good at clearing up after you. There's certainly nothing I can see wrong with your code in this respect.
EDIT 2 in response to your further comment: ArrayList arr; declares a variable of type ArrayList. However, the variable arr is uninitialized: it does not have a value (not even null) and it is an error to try to read the value of this variable before you have assigned a value to it:
ArrayList arr;
System.out.println(arr); // compiler error: arr might not have been initialised.
Assign null and the code then compiles:
ArrayList arr = null;
System.out.println(arr); // prints 'null'.
It's not often you need to declare a variable and not give it a name, but one common case is where you want to assign different values to the same variable on both sides of an if statement. The following code doesn't compile:
int y = getMeSomeInteger(); // assume this function exists
if (y == 4) {
int x = 2;
} else {
int x = 5;
}
System.out.println(x); // compiler error: cannot find symbol x
The reason it doesn't compile is that each variable x is only available within the braces { and } that contain it. At the bottom, neither variable x is available and so you get a compiler error.
We need to declare x further up. We could instead write the following;
int y = getMeSomeInteger(); // assume this function exists
int x = 0;
if (y == 4) {
x = 2;
} else {
x = 5;
}
System.out.println(x);
This code compiles and runs, but the value 0 initially assigned to x is never used. There isn't a lot of point in doing this, and we can get rid of this unused value by declaring the variable but not immediately giving it a value.
int y = getMeSomeInteger(); // assume this function exists
int x;
if (y == 4) {
x = 2;
} else {
x = 5;
}
System.out.println(x);
I wish to return a string from a method object that is called by another method in another class. My problem is: when I attempt to assign the returned value to a String in the other class, it cannot find the method object within the class object.
Guessing Game = new Guessing();
This makes the object using the class Guessing.Java
else if (buttonObj == guess){
double g = yourGuess.getNumber();
if ((g > 0)&&(g < 11)){
Game.StartGame(g);
label3.setVisible(false);
yourGuess.setEnabled(false);
label1.setText(Game.StartGame());
}else{
label3.setVisible(true);
yourGuess.requestFocus(true);
}
}
When I try retrieving the String from the StartGame method within the Guessing.Java class, it says it cannot find the class.
public String StartGame(double guess){
int round = 1;
int guesses = 3;
String correct = "correct";
if (guesses > 0){
if (guess == ans){
correct = "correct";
}else if ((guess == ans - 1)||(guess == ans + 1)){
correct = "hot";
guesses--;
}else if ((guess == ans - 2)||(guess == ans - 2)){
correct = "warm";
guesses--;
}else{
correct = "cold";
guesses--;
}
}else{
correct = "round";
}
return correct;
}
I have tried several different things and looked it up multiple times but nothing works, can anyone help?
First of all fix your code by using these Naming Conventions.
Change your code to this,
if (buttonObj == guess){
double g = yourGuess.getNumber();
if ((g > 0)&&(g < 11)){
String startGameStr = Game.StartGame(g);
label3.setVisible(false);
yourGuess.setEnabled(false);
label1.setText(startGameStr);
}else{
label3.setVisible(true);
yourGuess.requestFocus(true);
}
}
It is hard to tell what is causing the "class not found" exception with the details given.
But one thing I could see it : You are calling the method as:
label1.setText(Game.StartGame());
But the method expects a double argument.
according to the first code segment there two overloaded methods in Guessing class
StartGame(Double g)
StartGame()
seems to be like you are calling the second method when you try to assing the returned string to that label which probably retuning emty string or since that method doesn't exist you get method not found exception.