I need to make a program that reads hours in this format (934:9h34) or 1835 (18h35). How can I make my program print an error if somebody writes 966 (the 2 last digits over 59? (66>59)
Given a String str:
String str = getTheString();
String lastTwoDigits = str.length() > 2 ? str.substring(str.length() - 2) : str;
int result = 0;
try {
result = Integer.parseInt(lastTwoDigits);
} catch (NumberFormatException e) {
System.err.println("Cannot parse string!");
System.exit(1);
}
if (result > 59) {
System.err.println("Number was over 59!");
System.exit(1);
}
By the way, System.err.println() just prints to standard error rather than standard output, and exit(1) exits the program with a failing error code.
Hope this helps!
This solution will parse the string first, then get the last two digits of the number through result % 100.
private static void timeFormat(String text) {
int result = 0;
if (text.length() < 2) {
System.err.println("String was too short");
return;
}
try {
result = Integer.parseInt(text);
} catch (NumberFormatException e) {
System.err.println("Failed to parse string");
}
if (result % 100 > 59) {
System.err.println("Number was over 59");
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
timeFormat(scan.nextLine());
scan.close();
}
Since the title asks "How to evaluate the 2 last digit of a Int?", we can assume that you already have the value in an int variable.
To examine the last 2 digits, calculate the remainder when dividing by 100, i.e. use the % remainder operator:
int value = /*assigned elsewhere*/;
int lastTwoDigits = value % 100;
if (lastTwoDigits > 59) {
System.out.println("ERROR: Invalid value: " + value);
// value is invalid
}
Of course, you should probably also validate that value is not negative.
If, however, a value of -934 is valid, and -966 is not, just eliminate the sign by calling Math.abs():
int lastTwoDigits = Math.abs(value) % 100;
if (lastTwoDigits > 59) {
System.out.println("ERROR: Invalid value: " + value);
// value is invalid
}
This will work. Ensures that last 2 digits are <= 59.
String[] test = { "934:9h34", "1835", "1994", "iwiwiwiw45", "18h45"
};
// match 2 digits at end of string
Pattern p = Pattern.compile("(\\d\\d)$");
for (String t : test) {
Matcher m = p.matcher(t);
if (m.find()) {
// valid integer so convert and compare
if (Integer.valueOf(m.group(1)) <= 59) {
System.out.println("Passes test: " + t);
continue;
}
}
System.out.println("Fails test: " + t);
}
Learn more about Java and regular expressions
here.
First convert user given input into String
String hourInString = Integer.toString(userInput);
Then check if the input is valid or not. Minimum length of the input should be at least 3.
if (hourInString.length() < 3) {
System.out.println("invalid input");
System.exit(1);
}
Then retrieve the last two digit using substring
String lastTwoDigit = hourInString.substring(hourInString.length() - 2,
hourInString.length());
Finally you can validate the number-
if (Integer.parseInt(lastTwoDigit) > 59) {
System.out.println("Error");
}
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 am desperately trying to figure out a way of stopping "String index out of range: 0" errors... It happens whenever I don't enter anything and then continue execution:
static String getRef(Scanner Keyboard)
{
Scanner keyboard = new Scanner(System.in);
String ref= "";
boolean valid = false;
int errors = 0;
boolean problem = false;
while(valid==false)
{
System.out.println("Please enter a reference number which is two letters followed by three digits and a letter(B for business accounts and N for non business accounts)");
ref = keyboard.nextLine();
for (int i=0; i<6; i++)
{
if (ref.charAt(i)=='\0')
{
problem = true;
}
}
if(problem == true)
{
System.out.println("The reference must consist of 6 Characters");
}
else
{
if ((Character.isDigit(ref.charAt(0))== true) || (Character.isDigit(ref.charAt(1))== true))
{
System.out.println("The first 2 characters must be letters");
errors = errors + 1;
}
if ((Character.isDigit(ref.charAt(2))== false) || (Character.isDigit(ref.charAt(3))== false)||(Character.isDigit(ref.charAt(4))== false))
{
System.out.println("The 3rd,4th and 5th characters must be numbers");
errors = errors + 1;
}
if ((!ref.toUpperCase().endsWith("B"))&&(!ref.toUpperCase().endsWith("N")))
{
System.out.println("The 6th character must be either B(for business accounts) or N(for non business accounts) ");
errors = errors + 1;
}
if (errors==0)
{
valid=true;
}
}
}
return ref;
}
What I want is to be able to output an error message if the string does not contain a character at a certain index e.g. ref.charAt(0).
This will help (example):
if(ref.charAt(aNumber)==null) {
// display error message
}
Your problem is here:
ref.charAt(i)=='\0'
What happens if ref is a zero length string? In that case, trying to access the character at index 0 (where the first character would normally be) will give you your index out of range: 0 error. Make sure you test the string length first:
if (ref != null && !ref.isEmpty() &&ref.charAt(i)=='\0') { .. }
Adding a length() check
ref is empty (that is "") when you don't enter anything. So you can't get the character at 0 (or 1, 2, 3 ...). You can add an if check on the length, something like
if (ref.length() > 5) {
for (int i = 0; i < 6; i++) {
if (ref.charAt(i) == '\0') {
problem = true;
}
}
} else {
System.out.println("Please enter at least 6 characters");
}
Regular Expression
It might be simpler to compile a (reusable) Pattern with a regular expression to validate your reference criteria (2 letters, followed by 3 digits, followed b or n). Something like,
String ref; // <-- get input
Pattern p = Pattern.compile("([a-zA-Z]{2})(\\d{3})([B|N|b|n])");
Matcher m = p.matcher(ref);
if (m.matches()) { // <-- valid = m.matches();
System.out.println("ref is valid");
} else {
System.out.println("ref is not valid");
}
Could someone tell me why this bit of code keeps telling me Number Format Exception and not print my error message when I'm trying to convert from a binary number to a decimal?`
public static void readAndConvertBinaryValue()
{
Scanner kbd = new Scanner(System.in);
boolean valid = false;
do
{
System.out.print("\nEnter a binary value containing up to 16"
+ " digits: ");
bAction = kbd.nextLine();
int result = bAction.compareTo(BINARY_NUM);
if (result > 1 || result < -9 || bAction.length() > 16)
{
System.out.print("Error: Invalid binary value."
+ "\nTry again.\nPress Enter to continue ...");
kbd.nextLine();
} else
{
char value;
int charlim = 0;
value = bAction.charAt(charlim);
if (value == '1' || value == '0')
{
binary = Integer.parseInt(bAction, 2);
valid = true;
} else
{
System.out.print("Error: Invalid binary value."
+ "\nTrya again.\nPress Enter to continue ...");
kbd.nextLine();
}
}
} while (!valid);
}
Using regular expressions:
boolean isABinNumber = bAction.matches("^[01]+$");
matches is defined in the String class and returns true if and only if the string matches the regular expression provided. The regular expression above (^[01]+$) covers all strings that from beginning (^) to end ($) is a sequence of one or more (+) 0 or 1s '[01]'.
If you are not familiar with regular expressions there is plenty of information on the web (e.g. a tutorial)
This all seems too complicated, just use Integer.parseInt() and catch the NumberFormatException if it occurs. You can then check the value is within the desired range.
Scanner kbd = new Scanner(System.in);
System.out.print("\nEnter a binary value containing up to 16" + " digits: ");
String bAction = kbd.nextLine();
try {
int binary = Integer.parseInt(bAction, 2);
if (binary >= (1 << 16)) {
System.err.println("Binary value out of range");
}
} catch (NumberFormatException e) {
System.out.print("Error: Invalid binary value.");
}
import java.util.Scanner;
import java.util.regex.Pattern;
public class CheckBinary {
public static void main(String[] args) {
String binaryNumber = new Scanner(System.in).nextLine();
String binaryPattern = "(1*0*)*";
if (Pattern.compile(binaryPattern).matcher(binaryNumber).matches()) {
System.out.println("Binary");
} else {
System.out.println("Not Binary");
}
}
}
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...
}