Syntax error on string to int java - java

I am new to Java and I get confused here. Why do I get an error when I want to convert string to int in java?
If I type in msi(a to e), and I want to use msii variable inside if statement to outside, and I can't, so I try using sout outside. But I get an error.
public static void main(String args[]){
Scanner i=new Scanner (System.in);
System.out.println("Name\t\t\t");
String nama=i.nextLine();
System.out.println("Nim\t\t\t");
String nim=i.nextLine();
System.out.println("grade\t\t");
String msi=i.next();
switch(msi) {
case "a||A":
{
msii=Integer.parseInt(msi);
msii=4;
break;
}
case "b||B":
{
msii=Integer.parseInt(msi);
msii=3;
break;
}
case "c||C":
{
msii=Integer.parseInt(msi);
msii=2;
break;
}
case "d||D":
{
msii=Integer.parseInt(msi);
msii=1;
break;
}
case "e||E":
{
msii=Integer.parseInt(msi);
msii=4;
break;
}
default:
System.out.println("tidak ada");
break;
}
System.out.println(+msii);

You didn't declare datatype for msii.
It must be declared as int msii globally or int msii=Integer.parseInt(msi);

Since you did not include any stacktrace of the Exception you get, I'm going to assume you get the NumberFormatException
From oracle:
public static int parseInt(String s)
throws NumberFormatException
Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method.
Parameters:
s - a String containing the int representation to be parsed
Returns:
the integer value represented by the argument in decimal.
Throws:
NumberFormatException - if the string does not contain a parsable integer.
Note that I marked the line
The characters in the string must all be decimal digits
This should already answer at least why you get an error.
You are trying to parse non decimal characters
We cant really help you more than that until you provide a more accurate description on what is it that you are trying to do.

Related

error while parsing an int from a char in String

import java.util.*;
public class test
{
public static void main(String[] args)
{
int i = 123;
String s = Integer.toString(i);
int Test = Integer.parseInt(s, s.charAt(0)); // ERROR!
}
}
I want to parse the input string based on char position to get the positional integer.
Error message:
Exception in thread "main" java.lang.NumberFormatException: radix 49 greater than Character.MAX_RADIX
at java.lang.Integer.parseInt(Unknown Source)
at test.main(test.java:11)
That method you are calling parseInt(String, int) expects a radix; something that denotes the "number system" you want to work in, like
parseInt("10", 10)
(10 for decimal)! Instead, use
Integer.parseInt(i)
or
Integer.parseInt(i, 10)
assuming you want to work in the decimal system. And to explain your error message - lets have a look at what your code is actually doing. In essence, it calls:
Integer.parseInt("123", '1')
and that boils down to a call
Integer.parseInt("123", 49) // '1' --> int --> 49!
And there we go - as it nicely lines up with your error message; as 49 isn't a valid radix for parsing numbers.
But the real answer here: don't just blindly use some library method. Study its documentation, so you understand what it is doing; and what the parameters you are passing to it actually mean.
Thus, turn here and read what parseInt(String, int) is about!
Integer.parseInt(parameter) expects the parameter to be a String.
You could try Integer.parseInt(s.charAt(0) + ""). The +"" is to append the character to an empty String thereby casting the char to String and this is exactly what the method expects.
Another method to parse Characters to Integers (and in my opinion much better!) is to use Character.getNumericValue(s.charAt(0));
Check this post for further details on converting char to int
Need to convert String.valueOf(s.charAt(0)) to String.valueOf(s.charAt(0)) i.e. Char to String.
import java.util.*;
public class test
{
public static void main(String[] args)
{
int i = 123;
String s = Integer.toString(i);
int Test = Integer.parseInt(String.valueOf(s.charAt(0)));
}
}
Let use what we have here.
To parse one digit from a String into an integer. Use getNumericValue(char)
In your case, to get the first character into a number :
int n = Character.getNumericValue(s.charAt(0));
Be aware that you should take the absolute value if you integer can be negative.

Check if a String follows a certain format?

I have written a program that takes a ASCII character input (it actually takes a String then I use charAt(0)) into a JTextField then displays its hex, binary, int, and octal values using g2d.drawString(). I want the ability to also put in "integer" values (again actually being Strings) and display the info. In order to separate the "integer" values from the "char" inputs, I want to be able to input char values as they are, and integers using the pattern #i. This way, I can use an if statement to check if the "integer" pattern is followed, otherwise (else) evaluate the input as a ascii "char". How can I check if a String follows this pattern?
Example:
char input:
3 //I'll evaluate this as the ascii character value of 3
int input:
3i //I'll evaluate this as the integer value of 3
Note: Integer inputs could be multiple digits.
Look at the Pattern class. You will be able to do what you want with this.
Something like this?
if (str.length() == 1) {
char ch = charAt(0);
// code here
} else if (str.endsWith("i")) {
int num = Integer.parseInt(str.substring(0, str.length() - 1));
// code here
} else {
throw new IllegalArgumentException("Bad input: " + str);
}
The parseInt() will throw NumberFormatException if value preceding the i is not valid. Since that is a subclass of IllegalArgumentException, the code above will throw IllegalArgumentException for any bad text.

Number Format Exception for Large value

This block of code gives Number Format Exception on input 600000 in n
import java.util.*;
class SpoTwo{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int testcase,n,answer;
long bin;
String s;
testcase=sc.nextInt();
for(int i=0;i<testcase;i++){
n=sc.nextInt();
s=Integer.toBinaryString(n);
bin=Integer.parseInt(s);
answer=(int)Math.pow(2,bin*2);
System.out.println(answer%1000000007);
}
}
}
Exception:
Exception in thread "main" java.lang.NumberFormatException: For input string: "10010010011111000000"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:495)
at java.lang.Integer.parseInt(Integer.java:527)
at SpoTwo.main(SpoTwo.java:12)
The binary representation of 600000 is 10010010011111000000. This is not a valid base 10 integer. It is a valid base 2 integer. Use
bin = Integer.parseInt(s, 2);
Here's the method's javadoc.
The overloaded parseInt method you were using
Parses the string argument as a signed decimal integer. The characters
in the string must all be decimal digits, except that the first
character may be an ASCII minus sign '-' ('\u002D') to indicate a
negative value or an ASCII plus sign '+' ('\u002B') to indicate a
positive value. The resulting integer value is returned, exactly as if
the argument and the radix 10 were given as arguments to the
parseInt(java.lang.String, int) method.
you got a string and move to binary and then converts that string to an integer and then vc is the power, so that the whole supports a certain number of houses, so it's a blast, u can use paserInt putting the number of homes or turns the whole into a double.

CharSequence to Integer with multiple +ve and -ve signss

i have learned that to convert charsequence to integer we can use this statement
String cs="123";
int number = Integer.parseInt(cs.toString());
what if
cs = "++-+--25";
will this statement still run and give answer -25 according to string given??
You are end up with a NumberFormatException since ++-+--25 is not a valid integer.
See the docs of parseInt()
Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method.
So you are allowed to do
CharSequence cs = "-25"; //gives you -25
and
CharSequence cs = "+25"; //gives you 25
Otherwise ,take necessary steps to face the Exception :)
So know the char Sequence is a valid string just write a simple method to return true or false and then proceed further
public static boolean {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false; // no boss you entered a wrong format
}
return true; //valid integer
}
Then your code looks like
if(isInteger(cs.toString())){
int number = Integer.parseInt(cs.toString());
// proceed remaining
}else{
// No, Operation cannot be completed.Give proper input.
}
Answer to your question is code will run and throw Exception as "++-+--25" is not a valid int,
java.lang.NumberFormatException: For input string: "++-+--25"
You will get
java.lang.NumberFormatException: For input string: "++-+--25"
Tested example :
CharSequence cs = "++-+--25";
System.out.println("" + Integer.parseInt(cs.toString()));

java.lang.NumberFormatException: For input string: "10.0"

This code must validate input data from the findActions() method:
try {
System.out.println(findActions(lookingArea.substring(0, right)));// always printing valid number string
Integer.parseInt(findActions(lookingArea.substring(0, right)));// checking for number format
}
catch(NumberFormatException exc) {
System.out.println(exc);
}
But I always have java.lang.NumberFormatException: For input string: "*number*"
that is so strange, because checking with System.out.println(findActions(lookingArea.substring(0, right)));,
I get *number* like 10.0
Integer.parseInt doesn't expect the . character. If you're sure it can be converted to an int, then do one of the following:
Eliminate the ".0" off the end of the string before parsing it, or
Call Double.parseDouble, and cast the result to int.
Quoting the linked Javadocs above:
The characters in the string must all be decimal digits, except that
the first character may be an ASCII minus sign '-' ('\u002D') to
indicate a negative value or an ASCII plus sign '+' ('\u002B') to
indicate a positive value.
10.0 is not an integer number. Instead, you can use:
int num = (int) Double.parseDouble(...);
One of the reason could be that your string is too long to convert into Integer type, So you can declare it as Long or Double based on the provided input.
Long l = Long.parseLong(str);

Categories