Result not null in my code, if "sorIndex" is invalid - java

I would need some guidance from You, at the moment I have this challenge with this exercise:
The aim of this code would be, to split a String(szoveg) to rows and give back the result row(sorIndex) as a result, if sorIndex is in the range of the String Array(String szoveg is splitted into this array).
If the requested number of the row is not in the valid range(0-length of the array) it should give back a null value. The IDE for testing the excercise returns a mistake, which is the following(Hungarian + English):
"A getSor() metódus nem működik jól. Nem létező sorIndexet megadva
null-t kell visszaadjon a metódus. A konstruktor paramétere:"
"The getSor() method is not working properly. Given a not valid
sorIndex, the method should return null. The parameter of the
constructor:" -there is nothing after this part in the IDE.
public String getSor(int sorIndex) {
int sorok= szoveg.split("\n").length;
String sor;
if (sorIndex >= 0 && sorIndex <= sorok) {
String[] stringTomb = new String[sorok];
stringTomb = szoveg.split("\n");
sor = stringTomb[sorIndex];
} else {
sor = null;
}
return sor;
}
Does anyone have any idea where did I made the mistake?
Thank you!

The error message tells you that if an invalid sorIndex is passed, then a null should be returned. This means that instead of getting into the else branch in your logic, it goes into the if in an invalid manner.
The reason of this is that arrays are 0-indexed, so you should compare against rows (sorok) in a srict manner:
if (sorIndex >= 0 && sorIndex < sorok) {
That should fix the issue. However, your code computes split several times and is superfluous. I would refactor it to:
public String getSor(int sorIndex) {
if (szoveg == null) return null; // Handling the case when szöveg is not properly initialized
String stringTomb[] = szoveg.split("\n");
return ((sorIndex >= 0) && (sorIndex < szoveg.length)) ? stringTomb[sorIndex] : null;
}
I used the ternary operator to make this more readable, concise and short.

Related

What am I missing with this code? Google foo.bar

So recently I got invited to this google foo.bar challenge and I believe the code runs the way it should be. To be precise what I need to find is the number of occurrences of "abc" in a String. When I verify my code with them, I pass 3/10 test cases. I'm starting to feel bad because I don't know what I am doing wrong. I have written the code which I will share with you guys. Also the string needs to be less than 200 characters. When I run this from their website, I pass 3 tests and fail 7. Basically 7 things need to be right.
The actual question:
Write a function called answer(s) that, given a non-empty string less
than 200 characters in length describing the sequence of M&Ms. returns the maximum number of equal parts that can be cut from the cake without leaving any leftovers.
Example : Input : (string) s = "abccbaabccba"
output : (int) 2
Input: (string) s = "abcabcabcabc"
output : (int) 4
public static int answer(String s) {
int counter = 0;
int index;
String findWord ="ABC";
if(s!=null && s.length()<200){
s = s.toUpperCase();
while (s.contains(findWord))
{
index = s.indexOf(findWord);
s = s.substring(index + findWord.length(), s.length());
counter++;
}
}
return counter;
}
I see a couple of things in your code snippet:
1.
if(s.length()<200){
Why are you checking for the length to be lesser than 200? Is that a requirement? If not, you can skip checking the length.
2.
String findWord ="abc";
...
s.contains(findWord)
Can the test program be checking for upper case alphabets? Example: "ABC"? If so, you might need to consider changing your logic for the s.contains() line.
Update:
You should also consider putting a null check for the input string. This will ensure that the test cases will not fail for null inputs.
The logic of your code is well but on the other hand i found that you didn't check for if input string is empty or null.
I belief that google foo.bar wants to see the logic and the way of coding in a proper manner.
so don't be feel bad
I would go for a simpler approach
int beforeLen = s.length ();
String after = s.replace (findWord, "");
int afterLen = after.length ();
return (beforeLen - afterLen) / findWord.length ();
String pattern = "abc";
String line="<input text here>";
int i=0;
Pattern TokenPattern=Pattern.compile(pattern);
if(line!=null){
Matcher m=TokenPattern.matcher(line);
while(m.find()){
i++;
}}
System.out.println("No of occurences : "+ " "+i);
put declaration of index out before while block, isn't never good re-declare the same variable n time.
int index;
while (s.contains(findWord))
{
index = s.indexOf(findWord);
....
}
I hope this help
Update:
try to compact your code
public static int answer(String s) {
int counter = 0;
int index;
String findWord = "ABC";
if (s != null && s.length() < 200) {
s = s.toUpperCase();
while ((index = s.indexOf(findWord)) > -1) {
s = s.substring(index + findWord.length(), s.length());
counter++;
}
}
return counter;
}
Update:
The logic seems good to me, I'm still try to improve the performance, if you can try this
while ((index = s.indexOf(findWord, index)) > -1) {
//s = s.substring(index + findWord.length(), s.length());
index+=findWord.length();
counter++;
}

Dealing with StringIndexOutOfBoundsException in if statement Java

I have a program that gets an input from the console. It checks what the input is then using 'if's it decides what to do. One section test to see what the first four letters of the string are, to see if it needs to deal with it, but not all of the strings are always 4 or more letters long. This means that if you type in something that is less than 4 letters long, it encounters an error, and quits. I can't put that section at the end, because at the end there is an else, which if the command is unknown, is called and something happens. Is there a way I can stop the error from occurring?
My code is:
if(input.equals("help")){
int commandsSize = commands.size();
for(int i = 0; i < commandsSize; i++) {
String value = commands.get(i);
System.out.println(value);
} else if((input.substring(0, 4)).equals("open")) {
...
}
You can check the size of the string the user inputs,
if (input.length() != 4) {
System.out.println("You must enter valid input");
// Probably do something here.
}
if(input.equals("help")){
int commandsSize = commands.size();
for(int i = 0; i < commandsSize; i++) {
String value = commands.get(i);
System.out.println(value);
}
} else if((input.substring(0, 3)).equals("open")) {
...
}
Your code is erroring out on the substring method because if the string is less than 4 characters, the method is going outside the bounds of the string (or the char array that makes up the string). You will also want to check that you string is not null before calling methods on the string object.
To have the same flow as you currently have, but to protect your code against the substring error and not being null, you can do this:
if(input != null && input.equals("help")){
//some code
} else if((input != null && input.length() >= 4) && (input.substring(0, 4)).equals("open")) {
//some code
}

Java: I compare two Strings but it didn't recognize it

I have this problem:
I wrote this function because I need to get the index of the occurrence of a particular string st in a String array
static public int indicestring(String[] array, String st) {
int ret = -1;
for (int i = 0; i < array.length; i++){
if (st.equals(array[i])) {
ret=i;
break;
}
}
return ret;
}
I then called:
System.out.println("indicestring(NODO,"ET2"));
and I got the correct number.
But then when I do:
String[] arcos2 = linea.split("-");//reading from a file and separating by "-"
String aux = arcos2[1];
System.out.println(arcos2[1]);
System.out.println(aux);
if (aux.equals(arcos2[1])) {
System.out.println("Is equal 1");
}
if (aux.equals("ET2")) {
System.out.println("Is equal 2");
}
if ("ET2".equals(aux)) {
System.out.println("is equal 3");
}
The first two prints were ET2, but then it only printed of the 3 ifs is "Is equal 1".... The thing is I have nearly 200 nodes like "ET2" and only 3 are failing and giving me -1 in the first function...
My question is....Am I using wrong the arrays to save and compare the data, because if aux=arcos2[1]="ET2", why is 'aux.equals("ET2") 'or 'arcos2[1].equals("ET2)' not working
? Is ther another function you can recommend to try?(I tried changing equals with compareTo() == 0 and that didn't work either and trimming was also recommended).
Before, I had a similar error where I compare two arrays like this:
if(a[0] == b[0] && a[1] == b[1])
There was a case that clearly was correct but it was ignored...
But it got corrected when a i changed it to:
if (Arrays.equals(a, b))
Is there maybe some change like that
You should put a debug break point in the code and add expression watches to identify the root cause of the problem.

Processing String To Int Conversion Error

I have some simple Processing code that reads serial data coming in, writes it to a string and, depending on what is contained within that string, it converts the string to an int or char and executes some specific code.
My problem is that when I try to convert the data to an integer it either gives me an error or gives me a value of zero ( int(string) returns zero, Integer.parseInt(string) returns an error ). Below is the relevant portion of my code.
String serialreadbuffer;
int t = 0;
boolean STimer = false;
// Serial Message Display (From Controller)
if (myPort.available() > 0)
{ // Check if data is available
serialreadbuffer = myPort.readStringUntil('\n'); // read it and write to variable
if (serialreadbuffer.charAt(0) == 'I')
{
SerialText.setText("INITIALIZED");
t = 0;
STimer = true;
}
else if (serialreadbuffer.charAt(0) == 'U')
{
SerialText.setText("UPDATED");
t = 0;
STimer = true;
}
else if (serialreadbuffer.charAt(0) == 'D')
{
SerialText.setText("DISABLED");
t = 0;
STimer = true;
}
else if (serialreadbuffer.charAt(0) == 'E')
{
SerialText.setText("SERIAL COMMUNICATION ERROR");
t = 0;
STimer = true;
}
else
{
int numberbuffer = Integer.parseInt(serialreadbuffer) * 60 / 6144;
serialreadbuffer = str(numberbuffer);
RPMText.setText(serialreadbuffer);
}
}
Strangely enough, if I assign a string value directly to serialreadbuffer (i.e. serialreadbuffer = "6144") it will work, but if I get the same number from my serial port it gives me the following error:
NumberFormatException: For input string: "6144"
and it gives me that error for the following line:
int numberbuffer = Integer.parseInt(serialreadbuffer) * 60 / 6144;
I was also having a problem with the string.equals() compares (it would always return false, even if the strings were identical), however I got around this by converting the first character to char and using that to compare. Not sure if that is related to this issue or not.
I have scoured the internet and have found no help with this matter. I am not an experienced programmer, so maybe it's something obvious that I'm just not seeing. Your help is greatly appreciated.
trim the String before you parse it insetad of
int numberbuffer = Integer.parseInt(serialreadbuffer) * 60 / 6144;
do
int numberbuffer = Integer.parseInt(serialreadbuffer.trim()) * 60 / 6144;
you might have unprintable characters e.g. \r in it.
There could be some space with the value. Try trimming the string before conversion.
Serialreadbuffer.trim()

Error when try to parse String to Double

i have a string like this
106.826820,-6.303850,0
which i get from parsing the google Maps KML Document.
now i wanna parse its string to Double
this is my code :
public Double getLatitude(){
for(int posisi = GPS_NAME.indexOf(","); posisi > GPS_NAME.length(); posisi++){
TEMP_LAT = "" + GPS_NAME.indexOf(posisi);
}
GPS_LATITUDE = Double.valueOf(TEMP_LAT);
return GPS_LATITUDE;
}
public Double getLongitude(){
int posisiakhir = GPS_NAME.indexOf(",");
for(int i = 0; i < posisiakhir; i++){
TEMP_LON = "" + GPS_NAME.indexOf(i);
}
GPS_LONGITUDE = Double.valueOf(TEMP_LON);
return GPS_LONGITUDE;
}
but when i try to run it i got error like this
could somebody help me solving my problems >_<
and also confirm GPS_LATITUDE = Double.valueOf(TEMP_LAT); TEMP_LAT is not null there - as exception is NullPointerException not NumberFormatException.
You have null pointer exception so you should to it like this:
public Double getLatitude(){
for(int posisi = GPS_NAME.indexOf(","); posisi > GPS_NAME.length(); posisi++){
TEMP_LAT = "" + GPS_NAME.indexOf(posisi);
}
if (TEMP_LAT != null) {
GPS_LATITUDE = Double.parseDouble(TEMP_LAT);
}
return GPS_LATITUDE;
}
And for converting to double rather you should use Double.parseDouble() or also you can use new Double(TEMP_LAT).doubleValue() but first approach is cleaner.
Besides the probable causes for the NPE, I don't really get your logic; it looks completely dodgy to me.
Just some examples:
GPS_NAME.indexOf(",") will either return -1 or an index that is smaller than the length of the string in which is being searched. Then why have a condition that checks if it is larger than the length? posisi > GPS_NAME.length() will never be true, hence the for loops are useless...
Then inside the loops you do TEMP_LAT = "" + GPS_NAME.indexOf(posisi). From the earlier remark we know that posisi is either -1 or some other number that is smaller than the length of the string. So GPS_NAME.indexOf(posisi) will try to find a character repesented by the integer posisi (which will be a rather small number) in the string. How does that make sense?
I'd like to advise you to rethink your logic - perhaps String.split(",") is a good starting point.
Use Double.parseDouble(TEMP_LAT);

Categories