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()
Related
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.
I have a long String with binary values. And i have a hash map that has the Binary digits as a key and char as a value. I have a function that supposed to read the binary string using 2 pointers and compare with hashmap and store the corresponding char in main.decodedTxt. However, im getting string out of bound exception for this. I don't know how to solve this. I'm getting exception on "String temp =" line. I have a picture link of the console output to see better picture.
public static void bitStringToText (String binText){
String bs = binText;
int from =0;
int to = 1;
while(bs != null){
String temp = bs.substring(from, to);
if (main.newMapDecoding.containsKey(temp)){
main.decodedTxt += main.newMapDecoding.get(temp);
from =to;
to = from +1;
} else {
to = to + 1;
}
}
}
Image of console exception is here
First of all there is no need to check if bs is null because no part of your code changes the value of bs. Your current code will cross the possible index of your binText at some point. It's better to loop just binText and check if you find something within it. After all you have to traverse the complete string anyways. Change your code as follows
public static void bitStringToText (String binText){
//no need to do this if you are not modifying the contents of binText
//String bs = binText;
int from =0;
int to = 1;
int size = binText.length();
String temp = "";
while(to <= size ){
temp = binText.substring(from, to);
if (main.newMapDecoding.containsKey(temp)){
main.decodedTxt += main.newMapDecoding.get(temp);
from =to;
to = from +1;
} else {
to = to + 1;
}
}
}
Hope it helps.
First, give it a try to practice debugging. It is an easy case. Either use run in debug mode (place break point on String temp = bs.substring(from, to); line) or print values of from and to before the same line. It will help to understand what is going on.
Solution:
If bs is not null you will always have StringIndexOutOfBoundsException. Because you are not checking if to is pointing to not existed index of bs String. Easiest example of the first one will be empty String: bs == "".
One of the solution could be to replace condition in while to while (to <= bs.length()).
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++;
}
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
}
I tried to develop a java program using netbeans in which a GUI accepts subject marks from five text fields and displays the total marks, percentage and the grade in their respective text fields.
The problem is I am getting errors while executing the GUI. I tried replacing int with double to hold decimal values of percentage but that didn't help. I am unable to find any errors and since I am a beginner i am unable to understand the errors given in the monitor by my netbeans. Please help.
ERRORS: Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: " 34"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:481)
at java.lang.Integer.parseInt(Integer.java:527)
at NewJFrame.submit_buttonActionPerformed(NewJFrame.java:173)
at NewJFrame.access$000(NewJFrame.java:4)
at NewJFrame$1.actionPerformed(NewJFrame.java:60)
Here's the coding I've done.
int sub1_ = Integer.parseInt(sub1.getText());
int sub2_ = Integer.parseInt(sub2.getText());
int sub3_ = Integer.parseInt(sub3.getText());
int sub4_ = Integer.parseInt(sub4.getText());
int sub5_ = Integer.parseInt(sub5.getText());
// Here each subject holds a max. of 100 marks.
int a = sub1_+sub2_+sub3_+sub4_+sub5_;
total_marks.setText(""+a);
// Since each subject holds a max. of 100 marks, the total marks of five subjects sums up to 500.
int b = (a/500)*100;
percentage.setText(b+"%");
if(b<=100&&b>=91)
{grade.setText("A1");}
else if(b<=90&&b>=81)
{grade.setText("A2");}
else if(b<=80&&b>=71)
{grade.setText("B1");}
else if(b<=70&&b>=61)
{grade.setText("B2");}
else if(b<=60&&b>=51)
{grade.setText("C1");}
else if(b<=50&&b>=35)
{grade.setText("C2");}
else if(b<=34&&b>=0)
{grade.setText("D");}
else {grade.setText("");}
java.lang.NumberFormatException: For input string: " 34"
Trim the String of whitespace before using the parse methods.
try {
int sub1_ = Integer.parseInt(sub1.getText().trim());
int sub2_ = Integer.parseInt(sub2.getText().trim());
int sub3_ = Integer.parseInt(sub3.getText().trim());
int sub4_ = Integer.parseInt(sub4.getText().trim());
int sub5_ = Integer.parseInt(sub5.getText().trim());
} catch (NumberFormatException e) {
// invalid input
}
At some point you are trying to parse the integer " 34", the leading space is a problem for the parsing method.
You should either make sure your integer has no whitespace when you create it, or use the trim() function to remove leading and trailing whitespace,
In addition to the issues already reported, the line int b = (a/500)*100; should be int b = (a * 100) / 500; or, simpler, int b = a/5;. The division by 500 rounds down to an integer, so if a is less than 500 the result is zero.
In addition to the question asked, there is a way to reduce the clutter in your code.
For example, you have multiple if-statements that all do the same thing, but with different numbers.
In this case, you can just create a function.
private boolean inRangeOf(int value, int max, int min) {
return value <= max && value >= min;
}
You can then replace your conditions with calls to inRangeOf(x, a, b)
if( inRangeOf(b, 100, 91) ) {
grade.setText("A1");
}
else if( inRangeOf(b, 90, 81) ) {
grade.setText("A2");
}
else if( inRangeOf(b, 80, 71) ) {
grade.setText("B1");
}