limiting user input for hexadecimal numbers - java

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();
}

Related

Java question for scan a binary number using while loops

I'm new to java, got an assignment about converting binary to decimal.
here's my code
public static void main(String[] args) {
int num, decimal = 0, i=0;
Scanner in = new Scanner(System.in);
System.out.println("Enter a Binary Number");
String binary = in.nextLine();
num = Integer.parseInt(binary);
while(num != 0){
decimal += (num%10)*Math.pow(2, i);
num = num /10;
i++;
}
System.out.println("Decimal Number : "+ decimal);
}
It's already done but the teacher request "Use scanner class inside a while loop for users to enter the binary number one by one. A “-1” would stop the loop."
Does anyone know how to change my code?
Use another while loop and keep iterating until the user inputs -1.If user inputs -1 use break to come out of while loop
public static void main(String[] args) {
int num, decimal = 0, i=0;
Scanner in = new Scanner(System.in);
while(true) {
System.out.println("Enter a Binary Number");
String binary = in.nextLine();
num = Integer.parseInt(binary);
if(num ==-1){
break;
}
while(num != 0){
decimal += (num%10)*Math.pow(2, i);
num = num /10;
i++;
}
System.out.println("Decimal Number : "+ decimal);
}
}
Your task consists of two parts: iterated input-check-process cycle and the process itself.
The former is simply solved with a loop:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true) {
// input
System.out.println("Enter a Binary Number");
String inputStr = in.nextLine();
// check
if (inputStr.equals("-1")) {
break;
}
// process
// TODO
}
}
This repeats asking for input data, reading it, testing for a special 'terminate' value and exits eventually if one is found.
The second part can be solved as follows: scan input digits one by one; each new digit found becomes a new least-significant bit of a number being constructed, while all preceding digits become one position more significant than they were.
That means, whenever you find a new digit, the number gets doubled and the value of a new digit gets added:
// process
int result = 0;
int position;
for (position = 0; position < inputStr.length(); ++position) {
char digit = inputStr.charAt(position);
int val = Character.digit(digit, 2);
result = 2*result + val;
}
System.out.println("Decimal Number : "+ result);
Together they make:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true) {
// input
System.out.println("Enter a Binary Number");
String inputStr = in.nextLine();
// check
if (inputStr.equals("-1")) {
break;
}
// process
int result = 0;
int position;
for (position = 0; position < inputStr.length(); ++position) {
char digit = inputStr.charAt(position);
int val = Character.digit(digit, 2);
result = 2*result + val;
}
System.out.println("Decimal Number : "+ result);
}
}
Of course, for a real-life program we should also validate input, ie. test if it consists of digits 0 and 1 only, whether it's not empty or not too long (so that the result of conversion fits the values range of type int).

How do i do with java to fetch two to two numbers in a string and convert them

I have a problem with convention of a String to dec of hex. I have to take the String in input and convert the numers two to two for example:
string in input = FFCF6781.
I have to take FF and convert, after take CF and convert and so on.
My code is:
import java.util.Scanner;
/*
* Sample java source code convert hexadecimal to decimal
*/
public class HexToDecimal {
public static void main(String[] args) {
System.out.print("Hexadecimal Input:");
// read the hexadecimal input from the console
Scanner s = new Scanner(System.in);
String inputHex = s.nextLine();
String str = inputHex;
try{
for (int i=0;i<str.length();i++)
inputHex = str.substring (i,i+2);
// actual conversion of hex to decimal
Integer outputDecimal = Integer.parseInt(inputHex, 16);
System.out.println("Decimal Equivalent : "+outputDecimal);
}
catch(NumberFormatException ne){
// Printing a warning message if the input is not a valid hex number
System.out.println("Invalid Input");
}
finally{
s.close();
}
}
}
There are a few things.
First of all, if you want to print every hexadecimal number, you need to expand your for loop.
Plus, you need to add 2 to i every iteration.
In case the input length is not dividable by 2, catch the OutOfBoundsException.
This code works:
public static void main(String[] args) {
System.out.print("Hexadecimal Input:");
// read the hexadecimal input from the console
Scanner s = new Scanner(System.in);
String inputHex = s.nextLine();
String str = inputHex;
try {
for (int i = 0; i < str.length() - 1; i+=2) {
inputHex = str.substring(i, i + 2);
// actual conversion of hex to decimal
Integer outputDecimal = Integer.parseInt(inputHex, 16);
System.out.println("Decimal Equivalent : " + outputDecimal);
}
} catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
// Printing a warning message if the input is not a valid hex number
System.out.println("Invalid Input");
}
finally {
s.close();
}
}

Why this program repeats answers according to how many digits user inputs?

The output is supposed to be the conversion of binary to decimal. When I run this program and input (for example) 101, it will print the answers 3 times because 101 is 3 digits. How do I fix this? I only need one answer. please help
import java.util.Scanner;
public class Bin2Dec {
public static void main (String[] args){
//Convert the input string to their decimal equivalent.
//Open scanner for input.
Scanner input = new Scanner(System.in);
//Declare variable s.
String s;
//Prompt user to enter binary string of 0s and 1s.
System.out.print("Enter a binary string of 0's and 1's: ");
//Save input to s variable.
s = input.nextLine();
//Create a loop using the length of user input as the maximum number.
for (int i=0;i< s.length();i++){
try {
System.out.println("The decimal value of the binary number "+ s +" is "+error(s));
} catch (BinaryFormatException e) {
System.out.println("There is an error in the entered binary string:"+e.getMessage());
}
}
}
public static int error(String parameter) throws BinaryFormatException {
int tot = 0;
for (int i = parameter.length(); i > 0; i--) {
char c = parameter.charAt(i - 1);
if (c == '1') tot += Math.pow(2, parameter.length() - i);
else if (c != '0') throw new BinaryFormatException("'"+c+"' is not a binary digit");
}
return tot;
}
}
You are invoking the method in a for loop:
for (int i=0;i< s.length();i++){
try {
System.out.println("The decimal value of the binary number "+ s +" is "+error(s));
} catch (BinaryFormatException e) {
System.out.println("There is an error in the entered binary string:"+e.getMessage());
}
}
so of course it will execute as many times as the number of characters in the input. Move the call to error(s) out of the for loop.
You shouldn't try and reinvent something that has already been done. Simply using Integer#parseInt(String s, int radix) should be enough:
public class Bin2Dec {
public static void main (String[] args){
System.out.print("Enter a binary string of 0's and 1's: ");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
int decoded = Integer.parseInt(input, 2);
System.out.println(decoded);
}
}
Just remove the 'for' loop as shown:
//Create a loop using the length of user input as the maximum number.
//for (int i=0;i< s.length();i++){
try {
System.out.println("The decimal value of the binary number "+ s +" is "+error(s));
} catch (Exception e) {
System.out.println("There is an error in the entered binary
string:"+e.getMessage());
}
}
//}

How to properly check if an input is only binary number?

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");
}
}
}

Validating 7 digit phone number

What I'm trying to accomplish is the following...
Asks user for number and check to see if number provided by user input is a 7 digit integer.
If it's a string, throw InputMismatchException and ask again for the number. Is there an easy way to accomplish this other than using regex and provided that the number is in the form 1234567? The other problem is if I input a value such as 12345678, it gets rounded due to int, so how do avoid this.
int number = 0;
try {
number = scan.nextInt(); // Phone Number is 7 digits long - excludes area code
} catch(InputMismatchException e) {
System.out.println("Invalid Input.");
number = validateNumber(number, scan);
} finally {
scan.nextLine(); // consumes "\n" character in buffer
}
// Method checks to see if the phone number provided is 7 digits long
// Precondition: the number provided is a positive integer
// Postcondition: returns a 7 digit positive integer
public static int validateNumber(int phoneNumber, Scanner scan) {
int number = phoneNumber;
// edited while((String.valueOf(number)).length() != 7) to account for only positive values
// Continue to ask for 7 digit number until a positive 7 digit number is provided
while(number < 1000000 || number > 9999999) {
try {
System.out.print("Number must be 7 digits long. Please provide the number again: ");
number = scan.nextInt(); // reads next integer provided
} catch(InputMismatchException e) { // outputs error message if value provided is not an integer
System.out.println("Incorrect input type.");
} finally {
scan.nextLine(); // consumes "\n" character in buffer
}
}
return number;
}
A valid telephone number is not necessarily an integer (Containing a + sign for country codes for example). So use a String instead.
Simple example with basic regex (7 digits, not validating country codes etc.):
public class Test {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
String telephoneNumber = stdin.nextLine();
System.out.println(Pattern.matches("[0-9]{7}", telephoneNumber));
}
}
Here is working example along the lines of your original idea.
public int GetvalidNumber(Scanner scan) {
int number = 0;
while(true) {
try {
System.out.print("Enter a 7 digit number: ");
number = scan.nextInt();
if (number > 0 && Integer.toString(number).length() == 7)
break;
} catch(InputMismatchException e) {
scan.nextLine();
System.out.println("Invalid input: Use digits 0 to 9 only");
continue;
}
System.out.println("Invalid input: Not 7 digits long");
}
return number;
}

Categories