why do i have to use Integer.parseInt? - java

I am new to Java so forgive me if this is a silly question.
First I did the following (this is a section from my code):
public static void team()
{
int score = JOptionPane.showInputDialog("Enter the team score...");
calculate(score);
}
But I kept getting an error saying: "Incompatible types string cannot be converted to int".
So I thought I may need to use parsing. I did the following and it worked:
public static void team()
{
int myScore;
String score = JOptionPane.showInputDialog("Enter the team score...");
myScore = Integer.parseInt(score);
calculate(myScore);
}
I would like to know why there is a need for me to parse the variable "score"? In the first piece of code, I declared the variable score as an integer, so would it not store the input which I expect to be an Integer in the variable score which is then passed into the method calculate. I understand that parsing is when you convert a String into an Integer. However in this case, I do not expect the user to input a string so why is there a need for parsing?

The simple reason is: because JOptionPane.showInputDialog() returns a String, regardless of what you actually want the user to input.
There's no mechanism in Java to do automatic conversion based on the type of your destination variable myScore (though some other languages can do this, e.g. implicit conversions in Scala).
You could (in principle) create a custom dialog that returns an int , e.g. by getting the user to choose from a pulldown list of numbers, and then no parsing would be needed. But otherwise, you have to do parsing explicitly.

The JOptionPane.showInputDialog("Enter the team score..."); returns a String which you tried to store in a int. That is why you are getting the "incompatible types".
See Javadocs for more information.

Because a string is stored differently than an integer. Integers are stored in binary, while as a String is a collection of characters.
Example:
The number 14 would be stored as 1110 in Binary. However, as a String, it's stored as 00110001 00110100
Take a look at this http://www.roubaixinteractive.com/PlayGround/Binary_Conversion/The_Characters.asp
Integer.parseInt() basically does the dirty work for you, by looking up the characters in a lookup table, and as long as they correlate with proper integer values, it coverts it over to binary form, to be stored in an integer.

Related

Parsing a string into different variable types

Relatively new to programming here so I apologize if this is rather basic.
I am trying to convert string lines into actual variables of different types.
My input is a file in the following format:
double d1, d2 = 3.14, d3;
int a, b = 17, c, g;
global int gInt = 1;
final int fInt = 2;
String s1, s2 = "Still with me?", s3;
These lines are all strings at this point. I wish to extract the variables from the strings and receive the actual variables so I can use and manipulate them.
So far I've tried using regex but I'm stumbling here. Would love some direction as to how this is possible.
I thought of making a general type format for example:
public class IntType{
boolean finalFlag;
boolean globalFlag;
String variableName;
IntType(String variableName, boolean finalFlag, boolean globalFlag){
this.finalflag = finalFlag;
this.globalFlag = globalFlag;
this.variableName = variableName;
}
}
Creating a new wrapper for each of the variable types.
By using and manipulating I would like to then compare between the wrappers I've created and check for duplicate declarations etc'.
But I don't know if I'm on the right path.
Note: Disregard bad format (i.e. no ";" at the end and so on)
While others said that this is not possible, it actually is. However it goes somewhat deep into Java. Just search for java dynamic classloading. For example here:
Method to dynamically load java class files
It allows you do dynamically load a java file at runtime. However your current input does not look like a java file but it can easily be converted to one by wrapping it with a small wrapper class like:
public class CodeWrapper() {
// Insert code from file here
}
You can do this with easy file or text manipulations before loading the ressource as class.
After you have loaded the class you can access its variables via reflection, for example by
Field[] fields = myClassObject.getClass().getFields();
This allows you to access the visibility modifier, the type of the variable, the name, the content and more.
Of course this approach presumes that your code actually is valid java code.
If it is not and you are trying to confirm if it is, you can try to load it. If it fails, it was non-valid.
I have no experience with Java, but as far as my knowledge serves me, it is not possible to actually create variables using a file in any language. You'll want to create some sort of list object which can hold a variable amount of items of a certain type. Then you can read the values from a file, parse them to the type you want it to be, and then save it to the list of the corresponding type.
EDIT:
If I were you, I would change my file layout if possible. It would then look something like this:
1 2 3 4 //1 int, 2 floats, 3 booleans and 4 strings
53
3.14
2.8272
true
false
false
#etc.
In pseudo code, you would then read it as follows:
string[] input = file.Readline().split(' '); // Read the first line and split on the space character
int[] integers = new int[int.Parse(input[0])] // initialise an array with specefied elements
// Make an array for floats and booleans and strings the same way
while(not file.eof) // While you have not reached the end of the file
{
integers.insert(int.Parse(file.ReadLine())) // parse your values according to the size which was given on the first line of the file
}
If you can not change the file layout, then you'll have to do some smart string splitting to extract the values from the file and then create some sort of dynamic array which resizes as you add more values to it.
MORE EDITS:
Based on your comment:
You'll want to split on the '=' character first. From the first half of the split, you'll want to search for a type and from the second half, you can split again on the ',' to find all the values.

NumberFormatException error on returning largest number?

I'm practicing Java online and one of the practice problems is to:
"Write a method called largerAbsVal that takes two integers as parameters and returns the larger of the two absolute values. A call of largerAbsVal(11, 2) would return 11, and a call of largerAbsVal(4, -5) would return 5."
I have already wrote my method solution which so far is:
public static int largerAbsVal(int a, int b) {
return Math.max(Math.abs(a), Math.abs(b));
}
But for some reason, the website keeps telling me that my code caused an error of type NumberFormatException? I already declared the two parameters as integers at the heading so what exactly is wrong with my code in this case?
Any help is greatly appreciated!
From NumberFormatExecpton:
Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.
The code you posted works great! My guess is your error is somewhere before that piece of code where you're converting a string to an int. Example:
Integer.parseInt(string)
And that the string given is malformed (i.e. not an int). For example, something like "2.1" will throw an error like this.
Hope this helps!

Having issue with a very simple java program, not displaying proper result

here is my code that isn't working:
Scanner hello = new Scanner (System.in);
double a = 10;
double c;
System.out.print("Enter the value: ");
c = hello.nextDouble();
double f = a + c;
System.out.printf("The sum of 10 plus user entry is : ", a+c);
No syntax error whatsoever, no error displayed, this is the result :
Enter the value: 100
The sum of 10 plus user entry is :
So there is no result in the second line,,, for the command ( a+c ) as in program. But if i use a ' %.2f ' before ( a+c ) command, it works fine,,
like :
System.out.printf("The sum of 10 plus user entry is : %.2f", a+c);
I tried to search about the '%.2f' but got to know it is used just to ascertain that the following number is to be displayed as a number with two decimal places. (kinda round off thing, i guess)..
I'm totally a rookie at Java. Started studying it at college right now. Was just curious to know about this concept and reason behind why this program worked only with the '%.2f' typed in it, and not without it, although it showed no error. Will be great if someone can answer it. thanks :-)
Java's System.out.printf() method doesn't append information; it substitutes it. The '%.2f' means: "Replace this with the next argument, and convert it to a floating-point number 2 places precise." Removing the '%.2f' would mean that a+c would have nowhere to go, and printf() would discard it.
Since Java's System.out.printf() method is actually based on the printf() from C/C++, you might want to check out this guide.
You are using the wrong function.
You should be using
System.out.println(myString)
Or
System.out.print(myString)
You would format your code as
System.out.println(myExplinationString + a+c)
System.out is an instance of java.io.PrintStream class that is provided as a static field of the System class. printf(String format, Object... args) is one of the methods of the PrintStream class, check this Oracle tutorial on formatting numbers. In brief, the first argument is a format string that may contain plain text and format specifiers, e.g. %.2f, that are applied to the next argument(s). All format specifiers are explained in the description of the java.util.Formatter class. Note, that double value is autoboxed to Double.

What is the best approach to parse a String type to other numeric types available in Java?

Let's consider the following code snippet in Java. There are some of possible approaches (that I know) to parse a String value to other numeric types (Let's say for the sake of simplicity, it is an Integer, a wrapper type in Java).
package parsing;
final public class Parsing
{
public static void main(String[] args)
{
String s="100";
Integer temp=new Integer(s);
System.out.print("\ntemp = "+temp);
temp=Integer.parseInt(s);
System.out.print("\ntemp = "+temp);
temp=Integer.valueOf(s).intValue();
System.out.print("\ntemp = "+temp);
temp=Integer.getInteger(s);
System.out.print("\ntemp = "+temp);
}
}
In all the cases except the last one, returns the value 100 after converting it into an Integer. Which one is the best approach to parse a String value to other numeric types available in Java? The last case returns NULL even if the String object s already contains a parsable value. Why?
Calling Integer.getInteger("42") attempts to fetch the value of the system property whose name is "42". Unless you really do have a system property with that name, it will return null.
Here is the Java 7 javadoc if you want more details.
Yes, the name of the method is misleading, and its utility is questionable.
FWIW, I'd use Integer.parseInt(String) if I required an int result and Integer.valueOf(String) if I required an Integer. I'd only use new Integer(String) if I required the object to be a new Integer and not one that might be shared.
(The reasoning is the same as for new Integer(int) versus Integer.valueOf(int). Again, read the javadocs for a more complete explanation.)
temp=Integer.parseInt(s);
unlike the other it just calculate a int, not a Integer. (this is not a big advantage though)
The last case returns NULL even if the String object s already contains a parsable value. Why?
It's not doing what you think it's doing:
public static Integer getInteger(String nm)
Determines the integer value of the system property with the specified name.
See API Doc.
Also see the doc for other related methods, they do different things.
new Integer(s); //you are creating new object
parseInt(s); // parses and returns int (primitive)
valueOf(s); //returns cached Integer object with the int value in s
So, it depends: if you need int then parseInt(s) and if you need Integer then valueOf(s).
Integer.parseInt(s) is the best approach.
Interger#valueOf() method will return an Integer object equal to the value of new Integer(Integer.parseInt(s)).
Integer.getInteger() is not even a candidate.
Integer.getInteger(String) says that
Determines the integer value of the system property with the specified name.
If there is no property with the specified name, if the specified name is empty or null, or if the property does not have the correct numeric format, then null is returned.
In other words, this method returns an Integer object equal to the value of:
getInteger(nm, null)
And here is best explanation of your confusion.
Edited :
AFAIK:
Integer.valueOf(String) converts a String to a number by assuming the String is a numeric representation. In other words. Integer.valueOf("100") yields the number 100.
Integer.getInteger(String) converts a String to a number by assuming the String is the name of a system property numeric representation. In other words. Integer.getInteger("100") is likely to yield null.
getInteger(String s) returns the integer value of the system property with the specified name.If there is no property with the specified name, if the specified name is empty or null, or if the property does not have the correct numeric format, then null is returned. Note that this is equivalent to getInteger(s, null) evidently its not doing what you expect it to do!
Now analyzing the remaining approaches, valueOf() result is an Integer object that represents the integer value specified by the string,an Integer object equal to the value of: new Integer(Integer.parseInt(s)), so lets rule out this first.
Now the new Integer(s) approach, now if you want to work with the int value, you again need to get the intValue(), So finally it turns out that Integer.parseInt(s) approach is better (depends).
Javadoc can provide you with more details in case you need.
I prefer parseInt(...).
The reason that your last output is null is because getInteger(...) get the integer value from a property. To set the value of a property, use an option -D. Therefore, if you use the command line
java -D100=5 Test
You will not get the null but you'll get 5. Here, the option -D sets the property named "100" to value "5".
See getInteger(), which "determines the integer value of the system property with the specified name."

Determining input for Overloaded Method

I'm running into a bit of an issue with determining if the user input is an int or double.
Here's a sample:
public static int Square(int x)
{
return x*x;
}
public static double Square(double x)
{
return x*x;
}
I need to figure out how to determine based on the Scanner if the input is a int or double for the above methods. However since this is my first programming class, I'm not allowed to use anything that hasn't been taught - which in this case, has been the basics.
Is there anyway of possibly taking the input as a String and checking to see if there is a '.' involved and then storing that into an int or double?
Lastly, I'm not asking for you to program it out, but rather help me think of a way of getting a solution. Any help is appreciated :)
The Scanner has a bunch of methods like hasNextInt, hasNextDouble, etc. which tell you whether the "next token read by the Scanner can be interpreted as a (whatever)".
Since you mentioned you've learned about the Scanner object, I assume the methods of that class are available to you for your use. In this case, you can detect if an input is an integer, double, or just obtain an entire line. The methods you would most be interested here would be the hasNextDouble() method (returns a boolean indicating whether or not the current token in the Scanner is actually a double or not) and the nextDouble() method (if the next token in the Scanner is in fact a double, parse it from the Scanner as one). This is probably the best direction for determining input types from a file or standard input.
Another option is to use the wrapper classes static methods for converting values. These are generally named like Integer.parseInt(str) or Double.parseDouble(str) which will convert a given String object into the appropriate basic type. See the Double classes method pasrseDouble(String s) for more details. It could be used in this way:
String value = "123.45"
double convertedValue = 0.0;
try {
convertedValue = Double.parseDouble(value);
} catch (NuberFormatException nfe) {
System.err.println("Not a double");
}
This method is probably best used for values that exist within the application already and need to be verified (it would be overkill to construct a Scanner on one small String for this purpose).
Finally, yet another potential (but not very clean, straightforward, or probably correct technique) could be looking at the String object directly and trying to find if it contains a decimal point, or other indicators that it is in fact a double. You may be able to use indexOf(String substr) to determine if it appears in the String ever. I suspect this method has a lot of potential problems though (say for example, what if the String has multiple '.' characters?). I wouldn't suggest this route because it is error prone and hard to follow. It might be an option if that's what the constraints are, however.
So, IMHO, your options should go as follow:
Use the Scanner methods hasNextDouble() and nextDouble()
Use the wrapper class methods Double.parseDouble(String s)
Use String methods to try and identify the value (avoid this technique at all costs if either of the above options are available).
Since you think you won't be allowed to use the Scanner methods there are a number of alternatives you try. You mentioned checking to see if a String contains a .. To do this you could use the contains method on String.
"Some words".contains("or") // evaluates to true
The problem with this approach is that there are many Strings that contain . but aren't floating point numbers. For examples, sentences, URLs and IP addresses. However, I doubt you're lecturer is trying to catch you out with and will probably just be giving you ints and doubles.
So instead you could try casting. Casting a double to an int results in the decimal portion of the number being discarded.
double doubleValue = 2.7;
int castedDoubleValue = (int) doubleValue; // evaluates to 2
double integerValue = 3.0;
int castedIntegerValue = (int) integerValue; // evaluates to 3
Hopefully, that should be enough to get you started on writing a solution to the problem.
Can be checked like this
if(scanner.hasNextDouble()}
{
System.out.println("Is double");
}
if(scanner.hasNextDouble()}
{
System.out.println("Is double");
}

Categories

Resources