Cannot convert String to int in Java - java

In my program I need to convert a String to Int.
String str = new String(request.getData());
String [] setting = str.split(" ");
String bs = setting[1];
The value of bs is 1024, I use System.out.println to test it, and it displays on the screen with "1024".
But when I use
int blockSize = Integer.parseInt(bs);
it will return an exception point to the line of Integer.parseInt :
Exception in thread "main" java.lang.NumberFormatException: For input string: "1024"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:458)
at java.lang.Integer.valueOf(Integer.java:554)
Can someone help me to solve it? Thanks.

I suspect you have some hidden unicode character in the string bs, you can remove the non-digits with:
bs = bs.replaceAll("\\D", "");
int blockSize = Integer.parseInt(bs);
The code above will also convert the string "1a2" to 12, but that doesn't seem your case.

try this code:
String bs = setting[1].trim().toString();

while( (!bs.matches("\\d+")) && (bs.length > 1))
{
bs = bs.substring(1);
}
if (bs.matches("\\d+")
{
int blockSize = Integer.parseInt(bs);
}
else
{
int blockSize = -1;
}
/* !! Then, check for "-1" in your application of
block size #runtime_exception_prevention */
This will continue to remove the offensive non digit bits down to 1, as necessary, until a digit is found or only one character remains in the string. The second check prevents the exception and returns a flagged value. Checking for this flagged value will intercept runtime exceptions.
NB: I wrote this code in the comment block, please forgive any minor errors, I will gladly correct.

Related

Encoding string using cipher table

I need to encode a given message using cipherTable and a given key. I'm pretty sure there's something wrong with the encode method but i'm not sure what. This code:
import java.util.ArrayList;
public class Prog3Cipher {
// INSTANCE VARIABLES
static char[] keyList; // VARIABLE DESCRIPTION COMMENT
static char[][] cipherTable; // VARIABLE DESCRIPTION COMMENT
String alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static String encode(String message) {
String result = "";
ArrayList<Character> w = new ArrayList<>();
String[] m = new String[]{message};
for (int p = 0; p < m.length; p++) {
int row = Character.getNumericValue(keyList[p]);
int column = Character.getNumericValue(Integer.parseInt(m[p]));
char q = cipherTable[row][column];
w.add(q);
}
result = String.join(" ", (CharSequence) w);
return result;
}
public Prog3Cipher(char code, String key) {
keyList = key.toCharArray();
int offset = code - 'A';
cipherTable = new char[26][26];
for (int x = 0; x < cipherTable.length; x++) {
for (int y = 0; y < cipherTable[0].length; y++) {
cipherTable[x][y] =
alpha.charAt((x + y + offset) % alpha.length());
}
}
}
public static void main(String[] args) {
// Testing only works if using VM argument -ea
Prog3Cipher self = new Prog3Cipher('H', "BABBAGE");
assert "PHXXF MQYBPKNJ".equals(self.encode("Happy Birthday"));
}
}
Output:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Happy Birthday"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at Prog3Cipher.encode(Prog3Cipher.java:24)
at Prog3Cipher.main(Prog3Cipher.java:68)
Process finished with exit code 1
the encode method takes a cipher table, cipherTable, and finds the intersection point of the row and column, which are found with keyList and m, and the intersection is set to q and then added to an Arraylist w. Result is set to a String and returned.
i'm not sure what's wrong as there are no errors with the code so if anyone could look over it and give some guidance it would be much appreciated.
This line is the likely culprit.
int column = Character.getNumericValue(Integer.parseInt(m[p]));
The NumberFormatException is from the Integer.parseInt(). If you inspect m[p] you'll find that it is an array of length 1 with an where m[0]="Happy Birthday". The String "Happy Birthday" can't be parsed as a number, thus the exception.
If you want to break a String into its individual characters, you could use String.toCharArray() like this: char[] m = message.toCharArray();
There are some other issues in your code:
In the main() method an instance of Prog3Cipher is being created, but encode() is static, so the call to self.encode() likely isn't working as you might expect. Removing static from the method declaration of encode() should fix that problem.
Character.getNumericValue() returns the unicode value of the provided character. That method returns 10 for 'A' through 35 for 'Z', so the values don't match the bounds of your cipherTable array.
As written, the for loop in encode() will walk past the end of the keyList[] array. This is because keyList[] only has 7 characters compared to the 14 chars in message.
The encode() method doesn't have any special handling for spaces in message, so they'll most likely also cause an exception.

Why is this code not executing properly? Longest substring problem

So I'm trying to solve the Longest Substring Without Repeating Character problem in a webpage and when I'm trying to upload it it will show me this bug:
class Solution {
public int lengthOfLongestSubstring(String s) {
HashSet<Character> hash = new HashSet<>();
int count = 0, finalCount = 1;
char prevChar = s.charAt(0);
hash.add(prevChar);
for (int i = 1; i < s.length(); i++)
{
char character = s.charAt(i);
if (!hash.contains(character)){
hash.add(character);
count++;
if (count > finalCount) finalCount = count;
}
else{
hash.clear();
hash.add(character);
count = 1;
}
prevChar = character;
}
return finalCount;
} }
Is there anything wrong with it?
If not, do you think my algorithm was efficient? I can't compare its performance since the webpage won't let me upload it.
You call s.charAt(0) in line 5. I imagine they pass in the empty string as a test case and you are getting an out of bounds exception. Prior to line 5 add a check to see if the string length is 0 and if it is return 0.
According to the error description it's doing a dummy-spit at line 5 of the Solution class.
Based on the picture that's:
char prevChar = s.charAt(0);
The error is ArrayIndexOutOfBounds which generally indicates you tried to get more out of something than was actually there (e.g. running over the end of an array).
Here I'd suggest maybe putting in some System.out.println lines at line 3 to sanity check the method parameter, e.g.:
(a) if the input String s is null
or
(b) if the input String s is empty (e.g. "")
charAt(0) will get the first character, but if there are zero characters then trying to get the 1th character is an error, no?
NB: something like this:
System.out.println("Input was :" + s + ":");
Will show both of those conditions, as either:
Input was ::
for an empty String
Input was :null:
for a null String

Why is the Integer.parseInt not working in my java code?

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class MainProgram {
public static void main(String[] args ) throws IOException{
String seconds = " ";
Scanner sc2 = null;
try {
sc2 = new Scanner(new File("/Users/mohammadmuntasir/Downloads/customersfile.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
boolean first = true;
while (sc2.hasNextLine()) {
Scanner s2 = new Scanner(sc2.nextLine());
while (s2.hasNext()) {
String s = s2.next();
if (first == true){
seconds = s;
first = false;
}
}
}
System.out.println(Integer.parseInt(seconds)); // causes ERROR?
}
}
I am trying to read a number from a text file which is in the first line by itself. I made an integer called seconds that will take in the first number and will be parsed into an integer. But I always get a numbers exception error and that I can't parse it. When I display s as a string, it displays a number without spaces next to it. Can anyone explain why this happens?
Here is the stacktrace:
Exception in thread "main" java.lang.NumberFormatException: For input string: "300"
at java.lang.NumberFormatException.forInputString(NumberFormatE‌xception.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at MainProgram.main(MainProgram.java:29)
If the exception message is really this:
java.lang.NumberFormatException: For input string: "300"
then we are starting to get into really obscure causes.
It could be a problem with homoglyphs; i.e. Unicode characters that look like one character but are actually different characters.
It could be a non-printing character. For example an ASCII NUL ... or a Unicode BOM (Byte Order Marker) character.
I can think of three ways to diagnose this:
Run your code in a debugger and set a breakpoint on the parseInt method. Then look at the String object that you are trying to parse, checking its length (say N) and the first N char values in the character array.
Use a file tool to examine the file as bytes. (On UNIX / Linux / MacOSX, use the od command.)
Add some code to get the string as an array of characters. For each array entry, cast the char to an int and print the resulting number.
All three ways should tell you exactly what the characters in the string are, and that should explain why parseInt thinks they are wrong.
Another possibility is that you copied the exception message incorrectly. The stacktrace was a bit mangled by the time you got it into the Question ...
Have a look at your input file with a hex-editor. It might start with some "strange" hex codes called Byte Order Markers. This would explain why the Exception is so misleading becaus BOMs won't be shown on the console.
can you try this, I had the same probleme , Integer.ParseInt(String) didn't work for me, I added .trim() and it works perfectly:
int id_of_command;
try {
id_of_command = Integer.parseInt(id_of_Commands_str.trim());
}
catch (NumberFormatException e)
{
id_of_command = 0;
}
If you are sure you are reading an integer, you can use seconds.trim() to trim any spaces and parse it.
If you are trying to parse space then it would cause an issue. Please check what value of seconds you are trying to parse.
Exception in thread "main" java.lang.NumberFormatException: For input string: " "
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
at java.lang.Integer.parseInt(Integer.java:615)
at HelloWorld.main(HelloWorld.java:22)
Additionally try catching the exception and printing the value which is causing it. Something like this:
try{
System.out.println(Integer.parseInt(seconds));
}
catch(Exception e){
System.out.println("String value: '" + seconds + "'");
}
Can you update the question with stack-trace. Not sure what are the contents in your file.
Is it possible to append your code with something like this and put out your answer :
StringBuilder sb = new StringBuilder();
for (char c : seconds.toCharArray())
{
sb.append((int)c).append(",");
}
System.out.println(sb);
Your string can be empty or you string may contain space. So use trim & then parse.

Output for reversing a string does not come as expected

Chandu is a bad student. Once his teacher asked him to print the reverse of a given string. He took three hours to solve it. The teacher got agitated at Chandu and asked you the same question. Can you solve it?
Input
The first line contains an integer T, denoting the number of test cases.
Each test case contains a string S, comprising of only lower case letters.
Output
For each test case, print the reverse of the string S.
Constraints
1 <= T <= 10
1 <= |S| <= 30
Input Sample Output(Plaintext Link)
2
ab ba
aba aba
Time Limit
1 sec(s) for each input file.
Memory Limit
256 MB
Source Limit
1024 KB
MyApproach1
MyApproach2
To reverse a string I used XOR logic to reverse the string.
#Edit
public static void main(String args[] ) throws Exception
{
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int i = 1; i <= T; ++i)
{
String input = sc.next();
int len = input.length();
StringBuilder input1 = new StringBuilder(len);
int end = input.length()-1;
int start = 0;
while (start<end)
{
input1.setCharAt(start,input.charAt(start)^input.charAt(end));
input1.setCharAt(end,input.charAt(end)^input.charAt(start));
input1.setCharAt(start,input.charAt(start)^input.charAt(end));
++start;
--end;
}
System.out.println(input1.toString());
}
}
I am still getting the following error.
How do I correct this?
For approach 1, all you need to do is remove the call to sc.nextLine() and everything will be fine. That's because each line contains a "token" i.e. a word, delimited by whitespace. That's what sc.next() will return. No need to call nextLine() after that.
For your approach 2, you should carefully read the API documentation of StringBuilder. This shows you how to create a String from a StringBuilder, and vice versa. (Whenever I write Java code, I have a browser window with the API documentation for quick reference next to my editor window. It's very useful.)
Edit (after the latest edit to the question):
There is a compilation problem and a runtime problem. First, the XOR operator produces a result of type int, even if its operands are char. So you should put your expression in parentheses and cast it to char. Once you've done that, you'll get a runtime error because you are trying to index an element of a StringBuilder which does not yet exist. When you created the StringBuilder like this:
StringBuilder input1=new StringBuilder(len);
len is the initial capacity. The value of the StringBuilder instance is initially "". You then call setCharAt() but the current size of the StringBuilder is 0, so you get an index-out-of-bounds exception. You need to initialise the StringBuilder with the string itself:
StringBuilder input1=new StringBuilder(input);
Now you won't get an exception, but you'll get the wrong answer. That's because of a problem with your XOR logic.
After
sc.nextInt();
write
sc.nextLine();
before starting first loop.
For the two lines of your code
String s1 = sc.next();
sc.nextLine();
write just
String s1 = sc.nextLine();
The next() function gives you characters before a space while next line gives you whole line.
It'll work Fine.

Space Replacement for Float/Int/Double

I am working on a class assignment this morning and I want to try and solve a problem I have noticed in all of my team mates programs so far; the fact that spaces in an int/float/double cause Java to freak out.
To solve this issue I had a very crazy idea but it does work under certain circumstances. However the problem is that is does not always work and I cannot figure out why. Here is my "main" method:
import java.util.Scanner; //needed for scanner class
public class Test2
{
public static void main(String[] args)
{
BugChecking bc = new BugChecking();
String i;
double i2 = 0;
Scanner in = new Scanner(System.in);
System.out.println("Please enter a positive integer");
while (i2 <= 0.0)
{
i = in.nextLine();
i = bc.deleteSpaces(i);
//cast back to float
i2 = Double.parseDouble(i);
if (i2 <= 0.0)
{
System.out.println("Please enter a number greater than 0.");
}
}
in.close();
System.out.println(i2);
}
}
So here is the class, note that I am working with floats but I made it so that it can be used for any type so long as it can be cast to a string:
public class BugChecking
{
BugChecking()
{
}
public String deleteSpaces(String s)
{
//convert string into a char array
char[] cArray = s.toCharArray();
//now use for loop to find and remove spaces
for (i3 = 0; i3 < cArray.length; i3++)
{
if ((Character.isWhitespace(cArray[i3])) && (i3 != cArray.length)) //If current element contains a space remove it via overwrite
{
for (i4 = i3; i4 < cArray.length-1;i4++)
{
//move array elements over by one element
storage1 = cArray[i4+1];
cArray[i4] = storage1;
}
}
}
s = new String(cArray);
return s;
}
int i3; //for iteration
int i4; //for iteration
char storage1; //for storage
}
Now, the goal is to remove spaces from the array in order to fix the problem stated at the beginning of the post and from what I can tell this code should achieve that and it does, but only when the first character of an input is the space.
For example, if I input " 2.0332" the output is "2.0332".
However if I input "2.03 445 " the output is "2.03" and the rest gets lost somewhere.
This second example is what I am trying to figure out how to fix.
EDIT:
David's suggestion below was able to fix the problem. Bypassed sending an int. Send it directly as a string then convert (I always heard this described as casting) to desired variable type. Corrected code put in place above in the Main method.
A little side note, if you plan on using this even though replace is much easier, be sure to add an && check to the if statement in deleteSpaces to make sure that the if statement only executes if you are not on the final array element of cArray. If you pass the last element value via i3 to the next for loop which sets i4 to the value of i3 it will trigger an OutOfBounds error I think since it will only check up to the last element - 1.
If you'd like to get rid of all white spaces inbetween a String use replaceAll(String regex,String replacement) or replace(char oldChar, char newChar):
String sBefore = "2.03 445 ";
String sAfter = sBefore.replaceAll("\\s+", "");//replace white space and tabs
//String sAfter = sBefore.replace(' ', '');//replace white space only
double i = 0;
try {
i = Double.parseDouble(sAfter);//parse to integer
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
System.out.println(i);//2.03445
UPDATE:
Looking at your code snippet the problem might be that you read it directly as a float/int/double (thus entering a whitespace stops the nextFloat()) rather read the input as a String using nextLine(), delete the white spaces then attempt to convert it to the appropriate format.
This seems to work fine for me:
public static void main(String[] args) {
//bugChecking bc = new bugChecking();
float i = 0.0f;
String tmp = "";
Scanner in = new Scanner(System.in);
System.out.println("Please enter a positive integer");
while (true) {
tmp = in.nextLine();//read line
tmp = tmp.replaceAll("\\s+", "");//get rid of spaces
if (tmp.isEmpty()) {//wrong input
System.err.println("Please enter a number greater than 0.");
} else {//correct input
try{//attempt to convert sring to float
i = new Float(tmp);
}catch(NumberFormatException nfe) {
System.err.println(nfe.getMessage());
}
System.out.println(i);
break;//got correct input halt loop
}
}
in.close();
}
EDIT:
as a side note please start all class names with a capital letter i.e bugChecking class should be BugChecking the same applies for test2 class it should be Test2
String objects have methods on them that allow you to do this kind of thing. The one you want in particular is String.replace. This pretty much does what you're trying to do for you.
String input = " 2.03 445 ";
input = input.replace(" ", ""); // "2.03445"
You could also use regular expressions to replace more than just spaces. For example, to get rid of everything that isn't a digit or a period:
String input = "123,232 . 03 445 ";
input = input.replaceAll("[^\\d.]", ""); // "123232.03445"
This will replace any non-digit, non-period character so that you're left with only those characters in the input. See the javadocs for Pattern to learn a bit about regular expressions, or search for one of the many tutorials available online.
Edit: One other remark, String.trim will remove all whitespace from the beginning and end of your string to turn " 2.0332" into "2.0332":
String input = " 2.0332 ";
input = input.trim(); // "2.0332"
Edit 2: With your update, I see the problem now. Scanner.nextFloat is what's breaking on the space. If you change your code to use Scanner.nextLine like so:
while (i <= 0) {
String input = in.nextLine();
input = input.replaceAll("[^\\d.]", "");
float i = Float.parseFloat(input);
if (i <= 0.0f) {
System.out.println("Please enter a number greater than 0.");
}
System.out.println(i);
}
That code will properly accept you entering things like "123,232 . 03 445". Use any of the solutions in place of my replaceAll and it will work.
Scanner.nextFloat will split your input automatically based on whitespace. Scanner can take a delimiter when you construct it (for example, new Scanner(System.in, ",./ ") will delimit on ,, ., /, and )" The default constructor, new Scanner(System.in), automatically delimits based on whitespace.
I guess you're using the first argument from you main method. If you main method looks somehow like this:
public static void main(String[] args){
System.out.println(deleteSpaces(args[0]);
}
Your problem is, that spaces separate the arguments that get handed to your main method. So running you class like this:
java MyNumberConverter 22.2 33
The first argument arg[0] is "22.2" and the second arg[1] "33"
But like other have suggested, String.replace is a better way of doing this anyway.

Categories

Resources