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).
Related
This is my code that calculates ISBN 13th number but I seem to be having trouble. It keeps giving me an error on the return about invalid character constant and every time I change it, it gives an error on the method name I don't understand why.
import java.util.Scanner;
public class ISBN {
public static int VerifyISBN(String isbn) {
if(isbn.matches("[0-9]+") && isbn.length() > 12){
for(int i = 0; i < 12; i++){
char digit = isbn.charAt(i);
int sum = 0;
if (Character.isDigit(digit)){
int digitValue = digit - '0';
if(i % 2 == 0)
sum += digitValue;
else sum += 3 * digitValue;
}
else
return 'invalid'; (This is where I get the error)
}
}
}
public static void main(String[] args) {
final String TITLE = "ISBN-13 Identifier";
System.out.println("Welcome to the " + TITLE);
Scanner input = new Scanner(System.in);
String response;
do {
System.out.print("Enter the first 12 digits of an ISBN-13: ");
String isbn = input.nextLine().trim();
//String isbnVerifier = generateISBN(isbn);
//if(isbn.equals("INVALID"));
System.out.println("The 13th number of" + isbn + " is " +
((verifyISBN(isbn))));
System.out.print("Do this again? [nY]");
response = input.nextLine().toUpperCase();
} while (!response.equals("N"));
input.close();
System.out.println("Thank you for using the " + TITLE);
}
}
Two problems:
The literal 'invalid' is incorrect Java syntax. A string is delimited with double quotes. Single quotes are used to delimit single-character literals, such as 'a' but cannot be used for strings of characters.
The method is declared to return an integer, so you cannot return a String.
If your intent is to return a sentinel value indicating that the input was invalid, you should probably use something like -1, which can then be interpreted by the caller as the error condition.
Or, you could define the method to throw an exception.
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 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.
I have to use different methods for this code, no java shortcuts!
Here is my code:
import java.io.*;
import java.util.Scanner;
public class pg3a {
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
String hex;
char choice = 'y';
boolean isValid = false;
do {
switch (choice) {
case 'y':
System.out.print("Do you want to enter a hexadecimal number? ");
System.out.print("y or n?: ");
choice = keyboard.next().charAt(0);
System.out.print("Enter a hexadecimal number: #");
hex = keyboard.next();
hex = hex.toUpperCase();
int hexLength = hex.length();
isValid = valid(hex);
if (isValid) {
System.out.println(hex + " is valid and equal to" + convert(hex));
}
else {
System.out.println(hex + " is invalid.");
}
case 'n':
System.out.println("quit");
}
}while (choice != 'n');
}
public static boolean valid (String validString) {
int a = 0;
if (validString.charAt(0) == '-') {
a = 1;
}
for (int i=a; i< validString.length(); i++) {
if (!((validString.charAt(i) >= 'a' && validString.charAt(i) <= 'f')|| (validString.charAt(i) >= 0 && validString.charAt(i) <= 9)))
{
return false;
}
}
return true;
}
How can I make it so that after the program checks all the parameters for the hexadecimal number and calculates what it should be in decimal form, it prints out that the hexadecimal number is valid and then what the decimal number is??
Also how can I make it a loop that ends with either ^z or ^d to end the program?
To convert Strings representing hexadecimal numbers to Integer, you can use the Integer.toString(String, int); method:
Integer parsedValue = Integer.parseInt(hex, 16);
The first argument is the string to be converted, the second is the radix specification, hence is this value 16 for now.
To be complete, the Integer.toString(Integer, int) is the reverse if the above: it converts an Integer value to a string in the specified radix.
Just create a method named convert, and make it return this.
Printing an Integer is not a big issue, you can just concatenate it to any String using the + operator.
System.out.println("The value: " + parsedValue);
Also, keep in mind, that you have a little problem:
This line makes all the charachters uppercase in your string:
hex = hex.toUpperCase();
But here you check for lowercase letters:
if (!((validString.charAt(i) >= 'a' && validString.charAt(i) <= 'f')|| (validString.charAt(i) >= 0 && validString.charAt(i) <= 9)))
Either do hex=hex.toLowerCase();, or adjust the above condition to check to be between 'A' and 'F'.
Have to mention though that checking the validity of a String ot be converted to a numeric value is different: it tinvolves a try-catch block: try to convert the number, and if it fails, it is not valid...
Integer value; //have to declare it here to be able to access it outside of the try block
try {
value = Integer.parseInt(hex,16);
} catch(NumberFormatException e) {
//if you want to get the stack trace
e.printStackTrace(); //if not using a proper logging framework!!! Don't just print it!
//handle the situation: e.g. break loop, write eror message, offer retry for user, etc...
}
How can i find decimal(dot) in a given number in java.
I am getting input from user, he may give integer or float value.
I need to find he entered integer or float, is it possible?
if yes could u tell me please.
--
Thanks
Assuming you got the digits of the number in a String, it would be
String number = ...;
if (number.indexOf('.') > -1)
...
you can try with yourNumberString.indexOf("."). If it returns a number greater than -1 there's a dot in the input.
Anticipating your need, I would suggest that you use java.util.Scanner for number parsing, and use its hasNextXXX methods instead of dealing with parseInt etc and deal with NumberFormatException.
import java.util.*;
String[] inputs = {
"1",
"100000000000000",
"123.45",
"blah",
" "
};
for (String input : inputs) {
Scanner sc = new Scanner(input);
if (sc.hasNextInt()) {
int i = sc.nextInt();
System.out.println("(int) " + i);
} else if (sc.hasNextLong()) {
long ll = sc.nextLong();
System.out.println("(long) " + ll);
} else if (sc.hasNextDouble()) {
double d = sc.nextDouble();
System.out.println("(double) " + d);
} else if (sc.hasNext()) {
System.out.println("(string) " + sc.next());
}
}
This prints:
(int) 1
(long) 100000000000000
(double) 123.45
(string) blah
You do not need to explicitly search for the location of the decimal point as some answers suggest. Simply parse the String into a double and then check whether that double represents an integer value. This has the advantage of coping with scientific notation for doubles; e.g. "1E-10", as well as failing to parse badly formatted input; e.g. "12.34.56" (whereas searching for a '.' character would not detect this).
String s = ...
Double d = new Double(s);
int i = d.intValue();
if (i != d) {
System.err.println("User entered a real number.");
} else {
System.err.println("User entered an integer.");
}
Some other ways to do this:
given
String input = ...
the following evaluates to true if it's a decimal number
input.split(".").length == 2
or
input.matches(".+\\..+")
or
!input.matches("\\d+")