the second condition in the if statment with or operator - java

I have the following if statment which contains of two conditions with or perator. So in the following code I am getting this error
java.lang.NumberFormatException: For input string: ""
I thought in java the second condition in the if statment is checked if the first condition is not valid.
The compressDuration could be empty or null or blank or a String vlaue like 100.
In the case below the compressDuration is empty also it is blank also the second condition Integer.parseInt(compressDuration.trim()) must not be checked?
How can I write the if statment to conver the 4 cases empty or null or blank or a String vlaue like 100.?
String compressDuration = "";
if(StringUtils.isBlank(compressDuration) || Integer.parseInt(compressDuration.trim())){
System.out.println("The compressDuration has no value or a ");
}else{
}

I thought in java the second condition in the if statment is checked if the first condition is not valid.
I assume you mean not checked if the first condition is false. And that's correct, it isn't. So clearly, StringUtils.isBlank isn't returning false for "" if what's in your question is a valid example of what you're doing.
I suspect, though, that you have a string with whitespace in it, not "". Note that you're using trim when passing to Integer.parseInt, but not when passing to StringUtils.isBlank.
Note that as Eran pointed out, your code doesn't compile; int can't be used with the || operator, but your code has the condition boolean || int, which lends weight to the idea that this code isn't an accurate representation of what you actually have.
But I suspect it's the trim in the one case but not the other which is the problem.
Perhaps:
String compressDuration = /*...get it from wherever...*/;
compressDuration = compressDuration.trim();
int duration;
if (StringUtils.isBlank(compressDuration) || (duration = Integer.parseInt(compressDuration.trim())) < 0) {
System.out.println("The compressDuration has no value or a value less than zero");
} else {
System.out.println("The compressDuration is " + duration);
}
or if you don't like side-effects in if conditions (and there are good reasons to not like them, but I make some exceptions for very simple cases):
String compressDuration = /*...get it from wherever...*/;
compressDuration = compressDuration.trim();
int duration = StringUtils.isBlank(compressDuration) ? -1 : Integer.parseInt(compressDuration.trim();
if (duration < 0) {
System.out.println("The compressDuration has no value or a value less than zero");
} else {
System.out.println("The compressDuration is " + duration);
}

Try isInt method which will return true if it is valid integer.
if(!isInt(compressDuration.trim())) {
System.out.println("The compressDuration has no value or a ");
} else{
}
public boolean isInt(String str) {
try{
int num = Integer.parseInt(str);
// is an integer!
} catch (NumberFormatException e) {
// not an integer!
return false;
}
return true;
}

Related

NumberFormatException when parsing negative integer

I am writing a java program to determine if a number is a palindrome.
My code works properly if the argument passed is a positive integer, but throws a NumberFormatException when passing a negative integer.
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at com.stu.Main.isPalindrome(Main.java:28)
at com.stu.Main.main(Main.java:7)
The following solution I took from another stackoverflow thread, which seems to be what the instructor wants us to use, however in the while loop I assume that since a negative number is always less than 0, it will break out of the loop and not calculate the palindrome:
public static int reverse(int number)
{
int result = 0;
int remainder;
while (number > 0)
{
remainder = number % 10;
number = number / 10;
result = result * 10 + remainder;
}
return result;
}
So, I am using strings in my solution below to solve this issue.
Note: we have not yet got to splits and regexps yet.
public class Main {
public static void main(String[] args) {
isPalindrome(-1221); // throws exception
isPalindrome(707); // works as expected - returns true
isPalindrome(11212); // works as expected - returns false
isPalindrome(123321);// works as expected - returns true
}
public static boolean isPalindrome(int number){
if(number < 10 && number > -10) {
return false;
}
String origNumber = String.valueOf(number);
String reverse = "";
while(number > 0) {
reverse += String.valueOf(number % 10);
number /= 10;
}
if(Integer.parseInt(origNumber) == Integer.parseInt(reverse)) {
System.out.println("The original number was " + origNumber + " and the reverse is " + reverse);
System.out.println("Number is a palindrome!");
return true;
}
else
System.out.println("The original number was " + origNumber + " and the reverse is " + reverse);
System.out.println("Sorry, the number is NOT a palindrome!");
return false;
}
}
I am looking for two things here.
First, how do I solve the issue with the negative number in the while loop in the case of the instructors preferred solution?
Second, how can I solve the NumberFormatException in my solution?
Edit: a third question. Why does my solution return false if I never parse back to an int?
if(Integer.parseInt(origNumber) == Integer.parseInt(reverse)) // works
to
if(origNumber == reverse) // does not work
Thanks!
Ok, the easiest way to solve your first and second problem is just to remove the negative sign by using Math.abs(yourNumber) and that's it.
As,
The java.lang.Math.abs() returns the absolute value of a given argument.
If the argument is not negative, the argument is returned.
If the argument is negative, the negation of the argument is returned.
This will solve both of your first and second problem.
Coming to the third one, if you are not converting back to integer you are getting false as to compare string you neet to use equals() method as,
== tests for reference equality (whether they are the same object).
.equals() tests for value equality (whether they are logically "equal").
Hope that helps!! ;)

Java check String input

I am trying to check an input String:
- length
- type
- special char at the end
The input is a identity card like this 24659213Q.
So what I got for now is:
public void datosUsuario() {
System.out.print("Write ID: ");
input = scanner.nextLine();
}
//ID check
public void comprobacion() {
System.out.println("Checking ID length...");
if (input.length() == 9){
status = true;
System.out.println("Length: OK!");
} else {
System.out.println("Length not OK! Try again!\n");
status = false;
}
}
So I am checking the entire String for having 8+1 length and now I am having problems checking if it has 8 digits and a char at the end of the input.
Any ideas would be apreciated! Thank you!
I'd use a regular expression:
String input = scanner.nextLine();
input.matches("/^[0-9]{8}[A-Za-z]$/);
See String.matches and regular expression documentation.
A simple method would be:
//ID check
public void comprobacion() {
System.out.println("Checking ID length...");
if (input.length() == 9) {
if (Character.isAlphabetic(input.charAt(8)) {
status = true;
System.out.println("OK!");
} else {
status = false;
System.out.println("Length: OK, but last character must be alphabetic");
}
} else {
System.out.println("Length not OK! Try again!\n");
status = false;
}
You can use reg ex,
public static void comprobacion(String input) {
status = false;
if(input.matches("\\d{8}\\w{1}"))
{
status = true;
}
}
Here, \d{8} = eight digits
\w{1} = one alphabetical character
You could use "Character.isDigit()" to determine if a character is a digit or not. In other words, you could create a for loop to interate through each character, checking whether it is a digit or not. Here's an example:
String input = "24659213Q";
for(int c = 0; c < input.length()-1; c++){
//Checks all but the last character
if( !Character.isDigit( input.charAt(c) ) ){
System.out.println("The String does not start with 8 digits");
}
}
if( Character.isDigit( input.charAt(8) ) ){
//Checks only last character
System.out.println("The String does not end with a char");
}
The method of regular expression can also be followed as mentioned above. There is one more way to do it.
1)Split the string into two -one with 8 characters and the other with last one character.
2)Parse the first String
Integer.parseInt(subStringOfFirst8Char) in a try catch block catching NUmberFormatException.
If you don't catch the exception it is alright else it is wrong.

How to detect if a number is greater than Long.MAX value

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
}

Printing out variables from different methods in java?

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...
}

Returning the result of comparing two strings using 'contains'

So, I've got two strings being input and the subString looked for in the mString. When I change the method to boolean it returns the correct output of true or false (by using return on the contains statement).
I don't know how to use that statement to check the outcome of that contains operator. I've got the following done up.
public class CheckingString
{
public static void main(String[] args)
{
// adding boolean value to indicate false or true
boolean check;
// scanner set up and input of two Strings (mString and subString)
Scanner scan = new Scanner(System.in);
System.out.println("What is the long string you want to enter? ");
String mString = scan.nextLine();
System.out.println("What is the short string that will be looked for in the long string? ");
String subString = scan.nextLine();
// using the 'contain' operator to move check to false or positive.
// used toLowerCase to remove false negatives
check = mString.toLowerCase().contains(subString.toLowerCase());
// if statement to reveal resutls to user
if (check = true)
{
System.out.println(subString + " is in " + mString);
}
else
{
System.out.println("No, " + subString + " is not in " + mString);
}
}
}
Is there a way to make that check field work properly to return a value in the if-else statement?
if (check = true){
should be:
if (check == true){
Normally you would write:
if(check)
to check for true
and:
if(!(check))
or:
if(!check)
to check for false.
the trivial mistake:
change if(check = true) to if(check == true) or just if (check)
by doing check = true you are assigning true to check so the condition if(check = true) will always be true.
The preferred way to use a boolean variable in an if statement is
if (check)
Note that you don't need to use an equality operator, which avoids the error which you made.
Try it
if (check) {
System.out.println(subString + " is in " + mString);
} else {
System.out.println("No, " + subString + " is not in " + mString);
}

Categories