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");
}
}
}
Related
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");
}
Basically the User needs to input a Hexadecimal number which then converts it to decimal and binary numbers. I created two separate classes for the decimal and binary conversion and they work perfectly. What I wanted to do is to limit the input number making "90" the minimum input and "FF" the maximum one.
public static void main(String[] args) {
ForwardorBack Binary = new ForwardorBack();
Speed Decimal = new Speed();
String Hexadecimal = "";
Scanner input = new Scanner(System.in);
System.out.println("Enter Hexadecimal Number");
Hexadecimal = input.nextLine();
while (Hexadecimal.length() > 2 || Hexadecimal.length() < 2) {
System.out.println("Error Enter different number:");
Hexadecimal = input.nextLine();
}
Decimal.wheels(Hexadecimal);
Binary.move(Hexadecimal);
}
Here is a method to use in the head of the while loop
public static boolean validateInput(String input) {
if (input.length != 2) {
return false;
}
//Replace with own conversion if needed
try {
int decimal = Integer.parseInt(hex, 16);
if (decimal >= 90 && decimal <= 255) {
return true;
}
} catch (NumberFormatException e) {
return false;
}
}
Then use it like so
while(!validateInput(hexadecimal)) {
System.out.println("Error Enter different number:");
hexadecimal = input.nextLine();
}
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.
Here is what my program should be like:
Java: enter a binary number.
No!
Java: Please enter a binary number.
Well maybe.
JAva:can you lease enter a binary number?
101010
Java: The binary number 101010 is 42 in base 10
However, I cant get it to repeatedly ask for the user input if the input is not valid.
Moreover, I cant use Math.pow.
Here is my codings:
import java.util.Scanner;
public class BinaryToDecimal
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String binary = input.nextLine();
int[] powers = new int[16];
int powersIndex = 0;
int decimal = 0;
boolean isCorrect = true;
for(int i = 0; i < powers.length; i++)
powers[i] = (int) Math.pow(2, i);
for(int i = binary.length() - 1; i >= 0; i--)
{
if(binary.charAt(i) == '1')
decimal = decimal + powers[powersIndex];
else if(binary.charAt(i) != '0' & binary.charAt(i) != '1')
{
isCorrect = false;
System.out.println("Wrong input! Please enter a valid binary number");
input.next();
}
powersIndex++;
}
if(isCorrect)
System.out.println(binary + " converted to base 10 is: " + decimal);
else
System.out.println("Wrong input! Please enter a valid binary number");
input.next();
}
}
Problems I'm facing:
Can't use Math.pow
java wont ask for input properly (e.g. When I enter a false input, it ask me to enter a valid input. However, when I enter one, it ignores it. And it doesnt ask until the input is valid.)
If u guys can help me, I will be extremely grateful.
Thanks in advance.
First create a method that checks whether the input string is a valid binary literal or not.
Check whether it is or not. If not, just display the prompt with the text and do a nextLine again to read further input.
Do it again if the user does not enter a valid binary string.
If the user now provides a valid one, convert it to decimal.
However you have not specified what happens otherwise i.e. if the user does not provide a valid binary literal even in the 3rd attempt.
And if possible, always break down the various components of your program into smaller pieces. Something like this :
http://ideone.com/IbcW3b
The methods that do the job are :
private static int convertToBinary(String str) { // returns a decimal representation of the binary string literal }
private static boolean isBinary(String str) { // checks of string is a valid binary number }
The code assumes you loop until the user provides a valid input.
your issue is in last else :
if(isCorrect)
System.out.println(binary + " converted to base 10 is: " + decimal);
else
System.out.println("Wrong input! Please enter a valid binary number");
input.next();
put braces.
code changes are :
import java.util.Scanner;
class BinaryToDecimal
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String binary = input.nextLine();
int[] powers = new int[16];
int powersIndex = 0;
int decimal = 0;
boolean isCorrect = true;
for(int i = 0; i < powers.length; i++)
powers[i] = (int) Math.pow(2, i);
for(int i = binary.length() - 1; i >= 0; i--)
{
if(binary.charAt(i) == '1')
{
decimal = decimal + powers[powersIndex];
isCorrect = true;
}
else if(binary.charAt(i) != '0' & binary.charAt(i) != '1')
{
isCorrect = false;
System.out.println("Wrong input! Please enter a valid binary number");
binary= input.nextLine();
i=binary.length();
}
powersIndex++;
}
if(isCorrect)
System.out.println(binary + " converted to base 10 is: " + decimal);
}
}
Your code is having too many issues check this one as i did some changes.
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...
}