I have this button and a text field and i wanted to add value on the variable when the button is clicked everything is working apart from I'm unable to add value to string variable
For example if i put value 20 on tempvalue string it should have 20 and i put 30 it should have 50 but what i get is null2050.
I tried += operator which didn't work.
Isn't there any operator that keep adding value on top it or do i have to write new method ?
private String tempvalue;
btnEnter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String getTxt = textField.getText();
tempvalue += getTxt;
System.out.println(tempvalue);
}
});
You get Strings from Textfields.
String input = getTxt;
You have to parse the String to an integer or any other number type.
int value = Integer.parseInt(input);
Then you can do calculations.
You should also always check if the User Input really is a number.
Use try/catch to avoid wrong input:
int value = 0;
int firstValue = 5; //example variable
try{
value = Integer.parseInt(input);
}catch(Exception e1){
System.out.println("Your input could not be parsed to a number");
}
int result = firstValue + value; //always be sure all your values are numbers and not strings
System.out.println("Result: "+result);
In total:
private int tempvalue = 0;
btnEnter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String getTxt = textField.getText();
int value = 0;
try{
value = Integer.parseInt(getTxt);
}catch(Exception e1){
System.out.println("Your input could not be parsed to a number");
}
tempvalue += value;
System.out.println("Result: "+tempvalue);
}
});
}
You're simply concatenating your Strings.
In fact you start from null then you add 20 but as a String and then 30 but always as a String.
Transform in each step into a number and then you have your result done.
As commented by #Jesper the code are concatenating strings and not applying computations such as sum, subtraction and son on ...
So, try out to change the code to convert from java.lang.String to java.langInteger
Integer tempValue += new Integer( getText );
System.out.println( tempvalue );
or using a static method from Integer wrap class
Integer tempValue += Integer.parseInt( getText );
System.out.println( tempvalue );
or then using a int Java type (with auto-box automatically)
int tempValue += Integer.parseInt( getText ).intValue();
System.out.println( tempvalue );
Be careful about string to integer conversions. This can rise a NumberFormatException on runtime.
Related
It is possible to convert a String in this way? We have same paramater and Java makes the right choise. If the value is an integer - we call parseInt(value), else if the value is an double - we call parseDouble(value) or the value is an boolean - we call parseBoolean(value);
public int parseInt(String value) {
int newValue = Integer.valueOf(value).intValue();
return newValue;
}
public double parseDouble(String value) {
double newValue = Double.valueOf(value).doubleValue();
return newValue;
}
public boolean parseBoolean(String value) {
boolean newValue = Boolean.valueOf(value).booleanValue();
return newValue;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ConvertStrings convert = new ConvertStrings();
System.out.println("Enter the value:");
String value = sc.next();
//If value is an Integer - we call parseInt(value);
//If value is an double - we call parseDouble(value);
//If value is an boolean - we call parseBoolean(value);
sc.close();
}
Scanner has really helpful methods exactly for this like hasNextInt(), hasNextLong(), hasNextBoolean(). So you can use those :).
Scanner scanner = new Scanner(System.in);
if (scanner.hasNextBoolean()) {
boolean nextBoolean = scanner.nextBoolean();
} else if (scanner.hasNextInt()) {
boolean nextInt = scanner.nextInt();
}
If you only have the String (i.e., "value" was obtained elsewhere), you could do this:
try {
int ival = Integer.valueOf(value);
... // do something with the int
} catch (NumberFormatException ei)
// it isn't an integer, so try it as a double
try {
double dval = Double.valueOf(value);
... // do something with it
} catch ( NumberFormatException ed ) {
// Not a double, either. Assume it is boolean
boolean b = Boolean.valueOf(value);
...
}
}
Just so you know, there is a subtle difference between the Integer.valueOf() and Integer.parseInt() methods. Although not overly important since Autoboxing was introduced in Java 1.5 it is still worth noting for specific reasons described here. After all, the Integer.valueOf() method utilizes the Integer.parseInt() method within its method code anyways. Other good reads with regards to this can be found in this SO Post and in this SO Post.
I don't know what version of Java you are coding with but the unboxing as used in:
Integer.valueOf(value).intValue();
is unnecessary.
Since you're methods are returning a primitive data type, I would use the .parseXxx..(), type methods from the Integer class instead of the valueOf() method unless of course you want to take advantage of the caching mechanism available with the valueOf() method:
public int parseInt(String value) {
int newValue = Integer.parseInt(value);
return newValue;
}
But I would take it a step further and validate the fact that the supplied string argument via the value parameter was indeed a numerical value. Even though you would normally do this before calling a method like parseInt(), I don't think it hurts to have it just in case a pre-validation wasn't done. I would use the String#matches() method along with a Regular Expression (RegEx) for this, for example:
public int parseInt(String value) {
// Does value contain a signed or unsigned Integer
// type string numerical value?
if (!value.matches("-?\\d+")) {
//No - Throw an Exception.
throw new IllegalArgumentException(this.getClass().getName()
+ ".parseInt() - Invalid numerical value supplied (" + value + ")!");
}
// Yes - Convert numerical string to a primitive int value.
int newValue = Integer.parseInt(value);
return newValue;
}
As time goes on you may find that using the Integer class methods directly rather than through yet another method would be easier and more beneficial. This of course would depend entirely upon what you are doing.
For your methods, you may want to try this:
public int parseInt(String value) {
if (!value.matches("-?\\d+")) {
throw new IllegalArgumentException(this.getClass().getName()
+ ".parseInt() - Invalid numerical value supplied (" + value + ")!");
}
int newValue = Integer.parseInt(value);
return newValue;
}
public double parseDouble(String value) {
if (!value.matches("-?\\d+(\\.\\d+)?")) {
throw new IllegalArgumentException(this.getClass().getName()
+ ".parseDouble() - Invalid numerical value supplied (" + value + ")!");
}
double newValue = Double.parseDouble(value);
return newValue;
}
public float parseFloat(String value) {
if (!value.matches("-?\\d+(\\.\\d+)?")) {
throw new IllegalArgumentException(this.getClass().getName()
+ ".parseFloat() - Invalid numerical value supplied (" + value + ")!");
}
float newValue = Float.parseFloat(value);
return newValue;
}
public boolean parseBoolean(String value) {
value = value.toLowerCase();
boolean newValue = false;
if (value.matches("true")
|| value.matches("false")
|| value.matches("yes")
|| value.matches("no")) {
if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes")) {
newValue = true;
}
}
return newValue;
}
To use these methods you might do something like this:
Scanner sc = new Scanner(System.in);
//ConvertStrings convert = new ConvertStrings(); // Don't know what this class does.
String ls = System.lineSeparator();
int aINT;
double aDOUBLE;
float aFLOAT;
boolean aBOOLEAN;
String value = "";
while (!value.equals("q")) {
System.out.print("Enter a value (q to quit): --> ");
value = sc.nextLine();
if (value.equalsIgnoreCase("q")) {
break;
}
if (value.equals("")) {
System.out.println(">> Invalid Entry! You must enter a String! <<" + ls);
continue;
}
if (value.matches("-?\\d+")) {
aINT = parseInt(value);
System.out.println("A Integer (int) value of " + aINT + " was supplied." + ls);
}
else if (value.matches("-?\\d+(\\.\\d+)?([df])?")) {
if (value.matches("-?\\d+(\\.\\d+)?d")) {
aDOUBLE = parseDouble(value.toLowerCase().replace("d", ""));
System.out.println("A Double (double) value of " + aDOUBLE + " was supplied." + ls);
}
else if (value.matches("-?\\d+(\\.\\d+)?f")) {
aFLOAT = parseFloat(value.toLowerCase().replace("f", ""));
System.out.println("A Float (float) value of " + aFLOAT + " was supplied." + ls);
}
else {
aDOUBLE = parseDouble(value);
System.out.println("A Double/Float (double/float) value of " + aDOUBLE + " was supplied." + ls);
}
}
else if (value.toLowerCase().matches("true")
|| value.toLowerCase().matches("yes")
|| value.toLowerCase().matches("false")
|| value.toLowerCase().matches("no")) {
aBOOLEAN = parseBoolean(value);
System.out.println("A Boolean (boolean) value of '" + aBOOLEAN + "' was supplied." + ls);
}
else {
System.out.println("A String was supplied! (\"" + value + "\")" + ls);
}
}
In the above example code the following string values can be supplied:
A string of any size which would ultimately return and display that
string if it's not a numerical value.
A String representation of a signed or unsigned Integer type
numerical value.
A String representation of a signed or unsigned Double/Float type
numerical value.
A String representation of a signed or unsigned Double type numerical
value followed by the 'd' designation, for example: "453.665d" or
"3236d".
A String representation of a signed or unsigned Float type numerical
value followed by the 'f' designation, for example: "127.33f" or
32f.
A String representation of a Boolean type value, for example:
"true" or "yes" or "false" or "no".
Regular Expressions used in code:
The parseInt() method:
if (!value.matches("-?\\d+")) {
A Integer value. If the String held within the variable value matches to be a signed or unsigned integer numerical type value containing one or more digits.
The parseDouble() and parseFloat() methods:
if (!value.matches("-?\\d+(\\.\\d+)?")) {
A Double or Float value. If the String held within the variable value matches to be a signed or unsigned Integer or Double/Float Type numerical value containing one or more digits.
In example run code:
else if (value.matches("-?\\d+(\\.\\d+)?([df])?")) {
A Double or Float value. If the String held within the variable value matches to be a signed or unsigned Integer or Double/Float Type numerical value containing one or more digits and contains the letter d OR the letter f at the end.
In example run code:
if (value.matches("-?\\d+(\\.\\d+)?d")) {
A Double value. If the String held within the variable value matches to be a signed or unsigned Integer or Double/Float Type numerical value containing one or more digits and contains the letter d at the end (as in: 345d or 343.42d).
In example run code:
if (value.matches("-?\\d+(\\.\\d+)?f")) {
A Float value. If the String held within the variable value matches to be a signed or unsigned Integer or Double/Float Type numerical value containing one or more digits and contains the letter f at the end (as in: 345f or 343.42f).
Is there any way to simplify the following code. How it is roughly set up is it's scanning for a value, though if the input throws an exception, it needs to say nonono and reask for the value. I need to collect both values x and y like this so then I can operate on them in a scientific calculator way. Having the inputted string "RESULT" = the answer of the previous calculation is a requirement. These two loops that ask for x and y are so similar, with only "first operand" and "x = answer", and "second operand" and "y = answer" being different. So is there any way I can optimize this code so that there is only one loop needed since both are so similar? Here's the code.
String operand;
double x = 0;
double y = 0;
//These two arrays are the differences between both of the loops that follow. Everything besides first, x and second, y are the same
String arr[] = {"first", "second"};
Double var[] = {x, y};
boolean operandLoop1 = false;
//x
while (!operandLoop1) {
System.out.print("Enter " + arr[0] + " operand: ");
operand = calcOption.next(); // retrieve first value
if (operand.equals("RESULT")) {
var[0] = answer; // If I want to use the previous result as my input
operandLoop1 = true;
} else {
try {
var[0] = Double.parseDouble(operand); // Assumes that if it isn't RESULT, then I'll want to put in a number
operandLoop1 = true;
} catch (NumberFormatException nfe) { // necessary if I type anything else in besides RESULT and a double
System.out.print("Error: Invalid input! Correct inputs are any real number and \"RESULT\"!");
}
}
}
boolean operandLoop2 = false;
//y
while (!operandLoop2) {
System.out.print("Enter" + arr[1] + " operand: ");
operand = calcOption.next(); // retrieve second value
if (operand.equals("RESULT")) {
var[1] = answer; // If I want to use the previous result as my input
operandLoop2 = true;
} else {
try {
var[1] = Double.parseDouble(operand); // Assumes that if it isn't RESULT, then I'll want to put in a number
operandLoop2 = true;
} catch (NumberFormatException nfe) { // necessary if I type anything else in besides RESULT and a double
System.out.print("Error: Invalid input! Correct inputs are any real number and \"RESULT\"!");
}
}
}
Apologies about the length, but hopefully I can get it approximately half in length.
Since the only difference between the two sections is the array index, you can use a for loop, as follows:
for (int i = 0; i < 2; i++) {
boolean operandLoop = false;
while (!operandLoop) {
System.out.print("Enter " + arr[i] + " operand: ");
operand = calcOption.next(); // retrieve value
if (operand.equals("RESULT")) {
var[i] = answer; // If I want to use the previous result as my input
operandLoop = true;
} else {
try {
var[i] = Double.parseDouble(operand); // Assumes that if it isn't RESULT, then I'll want to put in a number
operandLoop = true;
} catch (NumberFormatException nfe) { // necessary if I type anything else in besides RESULT and a double
System.out.print("Error: Invalid input! Correct inputs are any real number and \"RESULT\"!");
}
}
}
}
You can also make it a method, passing in the parameters for calcOption, answer, and the ordinal (arr[0]), and replacing all of the assignments for var[0] with return statements. I don't know the type of calcOption, but it would look something like this:
Double methodName(Object calcOption, Double answer, String ordinal) {
boolean operandLoop = false;
while (!operandLoop) {
System.out.print("Enter " + ordinal + " operand: ");
String operand = calcOption.next(); // retrieve value
if (operand.equals("RESULT")) {
return answer; // If I want to use the previous result as my input
} else {
try {
return Double.parseDouble(operand); // Assumes that if it isn't RESULT, then I'll want to put in a number
} catch (NumberFormatException nfe) { // necessary if I type anything else in besides RESULT and a double
throw new RuntimeException("Error: Invalid input! Correct inputs are any real number and \"RESULT\"!");
}
}
}
}
My application will get number as string from end user. If the number is not numeric, i have to throw error message by saying that to provide number. This i can fix by using NumberFormatException. Another scenario is, user entered greater than Long.MAX value. How i can check this case and give error message to the user to enter smaller number than Long.MAX value? I should not use any third party or open source lib to fix this issue. Even if they are providing solution, How they are resolving it?
Use BigInteger to parse user input and compare the result with Long.MAX_VALUE
String userInput = ...;
BigInteger bigInt = new BigInteger(userInput);
if(bigInt.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0) {
throw new Exception(userInput + ": value is too large");
}
If the entered number is greater than Long.MAX value, then what will you do next. It will cause an error as you don't know where to store it.
Better way is to check at the time of user input is in range or not. If it is greater than Long.MAX, store it in BigInteger
Use BigInteger and the longValueExact() method, and catch exceptions:
public static void main(String[] args) {
test("123");
test("9223372036854775807"); // Long.MAX_VALUE
test("-9223372036854775808"); // Long.MIN_VALUE
test("9223372036854775808"); // Long.MAX_VALUE + 1
test("-9223372036854775809"); // Long.MIN_VALUE - 1
test("abc");
}
private static void test(String input) {
long longVal;
try {
longVal = new BigInteger(input).longValueExact();
} catch (NumberFormatException e) {
System.out.println("Value is not a valid integer number: " + input);
return;
} catch (ArithmeticException e) {
System.out.println("Value exceeds range of long: " + input);
return;
}
System.out.println("Got valid long value: " + longVal);
}
OUTPUT
Got valid long value: 123
Got valid long value: 9223372036854775807
Got valid long value: -9223372036854775808
Value exceeds range of long: 9223372036854775808
Value exceeds range of long: -9223372036854775809
Value is not a valid integer number: abc
You can access the max value using Long.MAX_VALUE and check the user entered value in if condition.
Here is another solution without using an extra class other than Java core
public static void main(String[] args) {
System.out.println(isLargerThanLONGMAXVALUE("9223372036854775807")); // false
System.out.println(isLargerThanLONGMAXVALUE("9223372036854775806")); // false
System.out.println(isLargerThanLONGMAXVALUE("9223372036854775808")); // true
System.out.println(isLargerThanLONGMAXVALUE("645459223372036854775807")); // true
System.out.println(isLargerThanLONGMAXVALUE("922")); // false
}
public static boolean isLargerThanLONGMAXVALUE (String number) {
String longMax = String.valueOf(Long.MAX_VALUE);
if (number.length() > longMax.length()) return true;
if (number.length() < longMax.length()) return false;
long a, b = 0;
for (int i = 1 ; i < number.length() ; i++){
a = Long.parseLong(number.substring(0, i));
b = Long.parseLong(longMax.substring(0, i));
if (a > b) return true;
}
if (Integer.parseInt(number.substring(number.length()-1, number.length())) >
Integer.parseInt(longMax.substring(number.length()-1, number.length())))
return true;
return false;
}
Treating the string as a BigInteger and doing the comparison is the best way. But here's another just to show that there's usually more than one way to accomplish something:
public boolean isInRange(String number) {
String maxValue = Long.toString(Long.MAX_VALUE);
number = number.replaceFirst("^0+", ""); // remove leading zeroes
return number.length() < maxValue.length() ||
(number.length() == maxValue.length() &&
number.compareTo(maxValue) <= 0);
}
This assumes that number is composed entirely of digits (no negative sign).
try{
val n = input.toLong()
}catch(e: Exception){
// invalid Long
}
I am trying to figure out how to convert text from text fields into intergers in Eclipse.
here is what I have so far, and it's been a few days since I have worked on this program and I am also new to java coding. If I have the code I need in here already, I apologize in advance for asking this question.
protected void do_enterButton_actionPerformed(ActionEvent arg0) {
int scr1, scr2, scr3 = -1;
TestScores score = (TestScores)studentList.getSelectedValue();
int score1 = Integer.parseInt(score1TextField.getText());
score.setScore1(score1);
int score2 = Integer.parseInt(score2TextField.getText());
score.setScore2(score2);
int score3 = Integer.parseInt(score3TextField.getText());
score.setScore3(score3);
if (score1TextField != null) {
// this is where I need to convert to text to integer
}
score1 is where you already did the conversion. Integer.parseInt(score1TextField.getText()); was correct.
The Integer.parseInt() you have in there converts text (String values or char sequences) to integer.
You should encase those in a try-catch block though.
try{
test = Integer.parseInt(textval);
}catch(NumberFormatException e){
System.out.println("A number was expected but not found.");
test = 0;
}
I have a basic calculator that is set so when the equal button is pressed then the JTextField is saved in a string form, that's the problem, it's in string form so I do not know how to solve the equation. I've tried using the JavaScript Engine but cannot figure that out. Any help?
//actionListener
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(oneButton)){
input1 = 1;
text.setText(text.getText()+input1);}
else if (e.getSource().equals(twoButton)){
input2 = 2;
text.setText(text.getText()+input2);}
else if(e.getSource().equals(threeButton)){
input3 = 3;
text.setText(text.getText()+input3);}
else if(e.getSource().equals(fourButton)){
input4 = 4;
text.setText(text.getText()+input4);}
else if(e.getSource().equals(fiveButton)){
input5 = 5;
text.setText(text.getText()+input5);}
else if(e.getSource().equals(sixButton)){
input6 = 6;
text.setText(text.getText()+input6);}
else if(e.getSource().equals(sevenButton)){
input7 = 7;
text.setText(text.getText()+input7);}
else if(e.getSource().equals(eightButton)){
input8 = 8;
text.setText(text.getText()+input8);}
else if(e.getSource().equals(nineButton)){
input9 = 9;
text.setText(text.getText()+input9);}
else if(e.getSource().equals(zeroButton)){
input0 = 0;
text.setText(text.getText()+input0);}
else if(e.getSource().equals(plusButton)){
text.setText(text.getText()+" + ");}
else if(e.getSource().equals(minusButton)){
text.setText(text.getText()+" - ");}
else if(e.getSource().equals(timesButton)){
text.setText(text.getText()+" * ");}
else if(e.getSource().equals(dividButton)){
text.setText(text.getText()+" / ");}
else if(e.getSource().equals(clrButton)){
text.setText("");}
else if(e.getSource().equals(enterButton)){
eq = text.getText();
//trying the javascript ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
try {
text.setText((String) engine.eval(eq));
} catch (ScriptException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
If order of operations matter you're going to have to use a stack. If you're only calculating from left to right, you should be fine.
As #Ericson Willians answer, you convert a String to an int or double via:
String str = text.getText();
Integer.parseInt(str);
Double.parseDouble(str);
But, you're likely to run into trouble here because when you press the enter button, you are getting the entire equation you placed in your your text element, aka if you pressed enter and you had the equation stored as "2 + 3", your text.getText() will give you "2 + 3" and you will not be able to use the following without giving you an error.
Integer.parseInt(text.getText()); //NumberFormatException For input string: "2 + 3"
Double.parseDouble(text.getText()); //NumberFormatException for "2 + 3"
You're going to have to break up the string in a specific way before you can convert the strings into integers or doubles. A good way to break up the string would be to use something like:
String st = text.getText();
//Example: String st = "2 + 3";
//remove white space
st = st.replaceAll("\\s","");
//might have to change to allow for negative numbers
String[] splitStrings = (st.split("((?<=[+-/*])|(?=[+-/*]))"));
//Example: splitStrings is now -> ["2","+","3"]
This breaks up the string between operations. You can then get the elements you want and parse them as integers. So for example:
int result;
int left = Integer.parseInt(splitStrings[0]);
String op = splitStrings[1];
int right = Integer.parseInt(splitStrings[2]);
if(op.equals("+")){
result = left + right;
}
text.setText("" + result);
But, since the equation could be big, you should probably create a loop that does something like this and you're going to need an if statement or a switch statement for all the operations.
You can write a calculator that parses strings using antlr: http://www.antlr.org/
Why don't you just use the parse method from the Integer and Double classes?
int integerNumber = Integer.parseInt(text.getText());
double doubleNumber = Double.parseDouble(text.getText());
As you can see, the method parseInt() from the Integer class converts the string in an Integer, and the same happens with Double. After doing this you can perfectly make any math with your strings.