Number Format Exception - converting with parseInt - java

I am working at converting string number into binary. But Eclipse throws a NumberFormatException. Can I ask you, to look at my code? I have no idea what is wrong..
public float liczbaF(String lancuch){
float array [] = new float [31];
float liczba;
double mantysa;
int znak;
long cecha;
char element[] = new char[22];
String temp="";
if (lancuch.charAt(0)=='1')
znak=-1;
else
znak=1;
for(int i=1;i<8;i++)
{
element[i-1] = lancuch.charAt(i);
}
temp=String.valueOf(element);
System.out.println(temp);
cecha=Integer.parseInt(temp,10);
cecha=cecha-127;
System.out.println(cecha);
for(int i=31;i>9;i--)
{
element[31-i] = lancuch.charAt(i);
}
temp=String.valueOf(element);
mantysa=(((Integer.parseInt(temp,10))/(pow(2,22)))+1);
liczba=(float)(mantysa*pow(2,cecha));
return liczba;
}
It throws:
Exception in thread "main" java.lang.NumberFormatException: For input string: "1001101
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Konwersja.liczbaF(Konwersja.java:30)
at Main.main(Main.java:10)
I will be grateful for any help.
Thank you

Your element array is 22 long:
char element[] = new char[22];
but you only fill in the first 7 elements:
for(int i=1;i<8;i++)
{
element[i-1] = lancuch.charAt(i);
}
So there are null characters at the end of the string, which make it unparseable as an integer.
This works better:
temp=String.valueOf(element,0,7);
I would recommend using a StringBuilder to add characters to a String, not a char array.

The reason for NumberFormatException is the hidden characters of element array. element array has a length of 22 but only filled by first few characters. So the rest are '\u0000'. An easy solution is:
modify this line:
temp=String.valueOf(element);
to:
temp=String.valueOf(element).trim();

Related

Java-Error trying to sort an int

package programame;
import java.util.Scanner;
import java.util.Arrays;
public class E100 {
public static int ascendente(int a)
{
String str = Integer.toString(a);
String max[] = str.split("");
Arrays.sort(max);
String str1 = Arrays.toString(max);
int ascendente = Integer.parseInt(str1);
return ascendente;
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int intentos = sc.nextInt();
int x = sc.nextInt();
System.out.println(ascendente(x));
}
}
Hi, I am trying to sort an int read from a scanner, but everytime I run it it gives me the error =
Exception in thread "main" java.lang.NumberFormatException: For input string: "[3, 4, 6, 7]" at
java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at
java.lang.Integer.parseInt(Integer.java:615) at
programame.E100.ascendente(E100.java:18) at
programame.E100.main(E100.java:25)
C:\Users\agn12\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
The exception
java.lang.NumberFormatException: For input string: "[3, 4, 6, 7]"
says that Java cannot convert such string to an Int as you are requesting.
It can be of use to be able to read the compiler error:
programame.E100.ascendente(E100.java:18) at
programame.E100.main(E100.java:25)
It tells you that the problem arises at line 25 in method main of E100.java, that in turn calls the method ascendente and the problem is at line 18 where you try to convert to an int an array of strings.
You are trying to split the number 3467 into its constituent decimal digits, sort them, and re-construct the digits into a single string:
String max[] = str.split("");
Arrays.sort(max);
String str1 = Arrays.toString(max);
The problem is that Arrays.toString returns a human-readable representation of the array, which is in the form "[3, 4, 6, 7]". This, obviously, cannot be parsed as an int. You are expecting to get the string "3467".
A better way of doing it (in terms of runtime efficiency and ease of coding) is to split the string into individual characters, instead of one-character strings. Then you can sort them, and easily turn them back into a string using one of String's constructors:
char[] max = str.toCharArray();
Arrays.sort(max);
String str1 = new String(max);
The rest of your code can stay the same.
The fault is with this line
String str1 = Arrays.toString(max);
You are trying to convert an array of numbers to string so
max = [2]
So str1 = "[2]"
and then converting this to a number
int ascendente = Integer.parseInt(str1);
Gives an error :: java.lang.NumberFormatException

How to print ASCII value of an int in JAVA

I've searched for this on the internet but was unable to find a precise solution, one possible solution I found was to read the integer as a String, and use charAt method and then cast the character to int to print the ascii value.
But is there any other possible way to do it other than the above stated method?
int a=sc.nextInt();
//code to convert it into its equivalent ASCII value.
For example, consider the read integer as 1, and now I want the ASCII value of 1 to be printed on the screen,which is 49
I assume you're looking for this:
System.out.print((char)a);
The easy way to do that is:
For the Whole String
public class ConvertToAscii{
public static void main(String args[]){
String number = "1234";
int []arr = new int[number.length()];
System.out.println("THe asscii value of each character is: ");
for(int i=0;i<arr.length;i++){
arr[i] = number.charAt(i); // assign the integer value of character i.e ascii
System.out.print(" "+arr[i]);
}
}
}
For the single Character:
String number="123";
asciiValue = (int) number.charAt(0)//it coverts the character at 0 position to ascii value

Cannot convert String to int in 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.

Converting string array to int with a delimiter

I can't figure out why I'm getting a null pointer exception. I'm trying to convert a line numbers that the user enters after a prompt, and I want to deliminate it either a space " " a comma "," or a comma and a space ", ".
Here's my code, I'm getting a null pointer exception on the nums[i]=Integer.parseInt(holder[i]); line. I just can't figure out why.
String again="n";
int[] nums = null;
do {
Scanner scan = new Scanner (System.in);
System.out.println("Enter a sequence of integers separated by a combination of commas or spaces: ");
String in=scan.nextLine();
String[] holder=in.split(",| |, ");
for (int i=0; i<holder.length; i++) {
nums[i]=Integer.parseInt(holder[i]);
System.out.print(nums[i]);
}
}
while (again=="y");
Ok Thanks everyone, I got it working by initializing the length of the nums array to the length of the holder array as suggested in the accepted answer. Like this:
int[] nums = new int[holder.length];
I have a second question though, as my regex seems to be failing, I can get it to read if delineated by "," or by " " but not by ", " any ideas?
Here's my error:
Enter a sequence of integers separated by a combination of commas or spaces:
1, 2, 3
Exception in thread "main" 1java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at SortComparison.main(SortComparison.java:20)
Your null pointer exception is caused by the fact that you have initialized the nums array to null, then try to "point" to it in your for loop. You can lose int[] nums = null and add:
int[] nums = new int[holder.length];
immediately before the for loop (after you've created the holder array, obviously).
You have set
int[] nums = null;
and then try to access
num[i]
which gives you the NullPointerException. You first need to contruct the array to hold the required number of elements:
int[] nums = new int[holder.length]
You better print your holder[i] before parsing it into an Integer, to see what's in it.
I am guessing that holder[i] is not having a valid value for an Integer.

Converting a String to an Integer

I'm trying to convert a String to an Integer. I have the following code:
List<String> strings = populateSomeStrings();
List<Integer> ints = new ArrayList<Integer>();
for (int i = 0; i < strings.size(); i++) {
ints.add(Integer.valueOf(strings.get(i)));
}
When I run it I get an exception saying:
java.lang.NumberFormatException: Invalid int: "1000"
Any ideas why this would be happening? I also tried Integer.parseInt but it does the same thing.
Thanks
There's obviously something in your strings that isn't numeric.
Catch the exception and print out the string length and code points for each character, using codePointAt for example.
That should tell you what's wrong.

Categories

Resources