Java number format exception error in number systems code - java

I'm doing a java number converter and whenever I try my hexadecimal to decimal converter it always gives me a java.lang.NumberFormatException for whatever I type that I want to convert. The console displays this error whenever I type in a string value for example ABC. How would I go about fixing this error? The error occurs at this line: int intNum = Integer.valueOf(numHexadecimal); in the code.
public static void hexToDecimal() {
System.out.println("Enter your hexadecimal number");
numHexadecimal = input.next();
hexArray = numHexadecimal.toCharArray();
int intNum = Integer.valueOf(numHexadecimal);
int counter = 0;
String hexVal = "";
int digit;
digit = intNum % 16;
switch (digit) {
case 1:
hexVal+="F"; break;
case 2:
hexVal+="E"; break;
case 3:
hexVal+="D"; break;
case 4:
hexVal+="C"; break;
case 5:
hexVal+="B"; break;
case 6:
hexVal+="A"; break;
default:
hexVal+=Integer.toString(digit);
}
intNum = intNum/16;
for (counter = hexVal.length()-1; counter >= 0; counter--)
System.out.print(hexVal.charAt(counter));
}
}

If you want to parse hexadecimal numbers you have to use the two-parameters version of valueOf, specifying the radix (16 for hexadecimal) as the second parameter
int intNum = Integer.valueOf(numHexadecimal, 16);

Related

Is there way to display number in exponent format

I have a large number and I don't want to display it in EditText as for example 1.1E12. I want to display it in format like this: 1.1 x 10^12 (see image). Is there way to do this?
I think you are asking how to generate a string that represents a number in “math textbook” scientific notation, like 6.02214076×10²³.
You can split the number into its base and exponent using Math.log10, then convert the exponent’s digits to Unicode superscript characters:
public static String formatInScientificNotation(double value) {
NumberFormat baseFormat = NumberFormat.getInstance(Locale.ENGLISH);
baseFormat.setMinimumFractionDigits(1);
if (Double.isInfinite(value) || Double.isNaN(value)) {
return baseFormat.format(value);
}
double exp = Math.log10(Math.abs(value));
exp = Math.floor(exp);
double base = value / Math.pow(10, exp);
String power = String.valueOf((long) exp);
StringBuilder s = new StringBuilder();
s.append(baseFormat.format(base));
s.append("\u00d710");
int len = power.length();
for (int i = 0; i < len; i++) {
char c = power.charAt(i);
switch (c) {
case '-':
s.append('\u207b');
break;
case '1':
s.append('\u00b9');
break;
case '2':
s.append('\u00b2');
break;
case '3':
s.append('\u00b3');
break;
default:
s.append((char) (0x2070 + (c - '0')));
break;
}
}
return s.toString();
}

Cannot be resolved error in java, any fixes? [duplicate]

This question already has answers here:
Java: Unresolved compilation problem
(10 answers)
Closed 3 years ago.
This is the error I am getting and I cant seem to figure out how to fix it.
I was trying to make it so that once you have finished your calculations, the program asks you if you want to perform them again.
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
retry cannot be resolved
yes cannot be resolved to a variable
My code(don't judge, this is my first program in java):
package calculatorpls;
import java.util.Scanner;
public class calc {
public static void main(String[]Args)
{
do {
Scanner num = new Scanner(System.in);
System.out.println("Please enter the first number."+"\n");
int no1 = num.nextInt();
System.out.println("\n"+"The number you have entered is "+no1+"."+"\n"+"\n"+"Please enter the second number now."+"\n");
int no2 = num.nextInt();
System.out.println("\n"+"The number you have entered is "+no2+"."+"\n"+"\n"+"Please choose what you would like to do from the following options:"+"\n"+
"1)Addition"+"\n"+"2}Subtraction(1st Number-2nd Number)"+"\n"+"3)Subtraction(2nd Number-1st Number)"+"\n"+"4)Multiplication"+"\n"+"5)Division(1st Number divided by 2nd Number)"+"\n"+"6)Division(2nd Number divided by 1st Number)"
+ ""+"\n"+"7)Multiply by an exponent(1st Number)"+"\n"+"8)Multiply by an exponent(2nd Number)"+"\n"+"\n"+"Type any number from 1-8 to select your option."+"\n");
//String Addition;
//String Subtraction(1st Number-2nd Number);
//String Subtraction(2nd Number-1st Number);
//String Multiplication;
//String Division(1st Number divided by 2nd Number);
//String Division(2nd Number divided by 1st Number);
//String Multiply by an exponent(1st Number);
//String Multiply by an exponent(2nd Number);
int choice = num.nextInt();
System.out.println("\n"+"You have chosen "+choice +"\n");
switch (choice)
{
case 1:
float addition = no1+no2;
System.out.println("\n"+ addition);
break;
case 2:
float subtraction1 = no1-no2;
System.out.println("\n"+ subtraction1);
break;
case 3:
float subtraction2 = no2-no1;
System.out.println("\n"+ subtraction2);
break;
case 4:
float multiplication = no1*no2;
System.out.println("\n"+ multiplication);
break;
case 5:
double division1 = no1/no2;
System.out.println("\n"+ division1);
break;
case 6:
double division2 = no2/no1;
System.out.println("\n"+ division2);
break;
case 7:
System.out.println("\n"+ "Please enter the power."+"\n");
int exponent = num.nextInt();
double exponent1 = (int) Math.pow(no1, exponent);
System.out.println("\n"+ exponent1);
break;
case 8:
System.out.println("\n"+ "Please enter the power."+"\n");
int exponenttwo = num.nextInt();
double exponent2 = (int) Math.pow(no2, exponenttwo);
System.out.println("\n"+ exponent2);
break;
default:
System.out.println("\n"+ "There isnt any such option matching your entry!"+"\n");
break;
}
System.out.println("\n"+ "Would you like to perform more calculations? Respond with yes or no."+"\n");
String retry = num.nextLine();
String again = "yes";
}while(retry.equalsIgnoreCase(again));
}
}
I fixed it for you.
String retry;
String again;
do {
Scanner num = new Scanner(System.in);
System.out.println("Please enter the first number."+"\n");
int no1 = num.nextInt();
System.out.println("\n"+"The number you have entered is "+no1+"."+"\n"+"\n"+"Please enter the second number now."+"\n");
int no2 = num.nextInt();
System.out.println("\n"+"The number you have entered is "+no2+"."+"\n"+"\n"+"Please choose what you would like to do from the following options:"+"\n"+
"1)Addition"+"\n"+"2}Subtraction(1st Number-2nd Number)"+"\n"+"3)Subtraction(2nd Number-1st Number)"+"\n"+"4)Multiplication"+"\n"+"5)Division(1st Number divided by 2nd Number)"+"\n"+"6)Division(2nd Number divided by 1st Number)"
+ ""+"\n"+"7)Multiply by an exponent(1st Number)"+"\n"+"8)Multiply by an exponent(2nd Number)"+"\n"+"\n"+"Type any number from 1-8 to select your option."+"\n");
//String Addition;
//String Subtraction(1st Number-2nd Number);
//String Subtraction(2nd Number-1st Number);
//String Multiplication;
//String Division(1st Number divided by 2nd Number);
//String Division(2nd Number divided by 1st Number);
//String Multiply by an exponent(1st Number);
//String Multiply by an exponent(2nd Number);
int choice = num.nextInt();
System.out.println("\n"+"You have chosen "+choice +"\n");
switch (choice)
{
case 1:
float addition = no1+no2;
System.out.println("\n"+ addition);
break;
case 2:
float subtraction1 = no1-no2;
System.out.println("\n"+ subtraction1);
break;
case 3:
float subtraction2 = no2-no1;
System.out.println("\n"+ subtraction2);
break;
case 4:
float multiplication = no1*no2;
System.out.println("\n"+ multiplication);
break;
case 5:
double division1 = no1/no2;
System.out.println("\n"+ division1);
break;
case 6:
double division2 = no2/no1;
System.out.println("\n"+ division2);
break;
case 7:
System.out.println("\n"+ "Please enter the power."+"\n");
int exponent = num.nextInt();
double exponent1 = (int) Math.pow(no1, exponent);
System.out.println("\n"+ exponent1);
break;
case 8:
System.out.println("\n"+ "Please enter the power."+"\n");
int exponenttwo = num.nextInt();
double exponent2 = (int) Math.pow(no2, exponenttwo);
System.out.println("\n"+ exponent2);
break;
default:
System.out.println("\n"+ "There isnt any such option matching your entry!"+"\n");
break;
}
System.out.println("\n"+ "Would you like to perform more calculations? Respond with yes or no."+"\n");
retry = num.next();
again = "yes";
}while(retry.equalsIgnoreCase(again));
I'm answering just to expand on nusaK's answer.
You should declare utilities like Scanner which may be used multiple times outside of for loops.
When you put the Scanner num = new Scanner(System.in); inside a loop, a new Scanner Object will be created every time the loop runs. Since we're always scanning from System.in, we can use the same object to scan for all iterations.
Since Java manages memory by itself, it isn't much of a problem but it might be in other languages.
Scanner num = new Scanner(System.in);
String again = "yes"; // you can initialize again here
String retry=""; // always initialize in languages like Java to avoid errors.
do {
...
}
while((retry=num.next()).equalsIgnoreCase(again));
// u can also use this, i.e. assign and evaluate at the same time but it's harder to read.

JAVA - How can I make sure program only continues with a scanned int? [duplicate]

This question already has answers here:
How to loop user input until an integer is inputted?
(5 answers)
Closed 4 years ago.
I'm learning to program in Java and I'm working on a pizza-ordering console program.
I've gotten the entire program to work, but I want to fool-proof it. Three places I ask for an int input, but when I type a char or a string, the program crashes.
What I hoped to achieve:
When the user enters a valid number, the program continues - Done
When the user enters a char or a string they get an error message and the loop starts over.
Here's an example from my code:
do {
correctInput = true;
System.out.println("Step 1: Look through the menu below and type in the NUMBER of the pizza you want.\n");
pizzaMenu();
System.out.print("\nType in your pizza number here: ");
pizzaNumber = pizza.nextInt();
pizza.nextLine();
switch (pizzaNumber) {
case 1:
pizzaChoice = "Napoli";
pizzaPrice = 50;
break;
case 2:
pizzaChoice = "Hawaii";
pizzaPrice = 50;
break;
case 3:
pizzaChoice = "Quattro Stagioni";
pizzaPrice = 60;
break;
case 4:
pizzaChoice = "Sicillia";
pizzaPrice = 75;
break;
case 5:
pizzaChoice = "Turbo";
pizzaPrice = 60;
break;
case 6:
pizzaChoice = "Jamaica";
pizzaPrice = 75;
break;
case 7:
pizzaChoice = "Romano";
pizzaPrice = 60;
break;
case 8:
pizzaChoice = "Vulcano";
pizzaPrice = 75;
break;
case 9:
pizzaChoice = "Vegetariana";
pizzaPrice = 60;
break;
case 10:
pizzaChoice = "Salame";
pizzaPrice = 60;
break;
default:
System.out.println("You've entered a wrong number. Try again");
correctInput = false;
break;
}
} while (!correctInput);
Could you please help pointing me towards a possible solution?
You can read a string from the scanner and then manually try to convert it to required number (either Integer or Double):
String str = scan.next();
if (isNumeric(str))
System.out.println("Numeric value: " + Double.parseDouble(str));
else
System.out.println("Not a numeric");
And method that checks if given string a numeric or not:
private static boolean isNumeric(String str) {
try {
Double.parseDouble(str);
return true;
} catch(NumberFormatException e) {
return false;
}
}

Number Conversion System in Java

import java.util.Scanner;
public class NumberConversionSystems {
public static void main(String[] args) {
//String binary = toBinaryString(number);
Scanner input = new Scanner(System.in);
System.out.println("Number Conversion Systems \n");
// Display the menu
System.out.println("1.\t Decimal to Binary");
System.out.println("2.\t Decimal to Hexadecimal");
System.out.println("3.\t Binary to Decimal");
System.out.println("4.\t Hexadecimal to Decimal \n");
System.out.println("Your choice?");
//Get user's choice
int choice = input.nextInt();
switch (choice) {
case 1: System.out.println("\nEnter Decimal Number");
break;
case 2: System.out.println("\nEnter Decimal Number");
break;
case 3: System.out.println("\nEnter Binary");
break;
case 4: System.out.println("\nEnter Hexadecimal");
break;
default:
System.out.println("\nInvalid choice. Please choose a number between 1 and 4.");
choice = input.nextInt();
break;
}
if (choice == 1) {
int number = input.nextInt();
String binary = toBinaryString(number);
binary = recursive(number);
System.out.printf("Decimal to Binary (%d) = %s", number, binary);
}
else if (choice == 2) {
int number2 = input.nextInt();
String hexadecimal = toHexString(number2);
hexadecimal = recursiveDecHex(number2);
System.out.printf("Decimal to Hexadecimal (%d) = %s ", number2, hexadecimal);
}
else if (choice == 3 ) {
String binary2 = input.next();
int decimal = toDecimalUsingParseInt(binary2);
decimal = recursiveBin(binary2);
System.out.printf("\n2. Binary to decimal - recursive(%s) = %d ", binary2, decimal);
}
else {
String hex = input.next();
int decimal = toHexUsingParseInt(hex);
decimal = recursiveHexDec(hex);
System.out.printf("Hexadecimal to Decimal (%s) = %d ", hex, decimal);
}
input.close();
}
private static String toBinaryString(int number) {
return Integer.toBinaryString(number);
}
private static String toHexString(int number) {
return Integer.toHexString(number);
}
private static int toDecimalUsingParseInt(String binaryNumber) {
return Integer.parseInt(binaryNumber, 2);
}
private static int toHexUsingParseInt(String number) {
return Integer.parseInt(number, 16);
}
private static String recursive(int number) {
StringBuilder builder = new StringBuilder();
if (number > 0) {
String binaryNumber = recursive(number / 2);
int digit = number % 2;
builder.append(binaryNumber + digit);
}
return builder.toString();
}
private static String recursiveDecHex(int number) {
StringBuilder builder = new StringBuilder();
if (number > 0) {
String hexNumber = recursiveDecHex(number / 16);
String hexCode = "0123456789ABCDEF";
int hexDigit = number % 16;
builder.append(hexNumber + hexCode.charAt(hexDigit));
}
return builder.toString();
}
private static int recursiveBin(String binaryNumber) {
int decimal = 0;
int length = binaryNumber.length();
if (length > 0) {
String substring = binaryNumber.substring(1);
int digit = Character.getNumericValue(binaryNumber.charAt(0));
decimal = digit * (int) Math.pow(2, length - 1) + recursiveBin(substring);
}
return decimal;
}
private static int recursiveHexDec(String hexNumber) {
int decimal = 0;
String hexCode = "0123456789ABCDEF";
hexNumber = hexNumber.toUpperCase();
int length = hexNumber.length();
if (length > 0) {
char ch = hexNumber.charAt(0);
int digit = hexCode.indexOf(ch);
String substring = hexNumber.substring(1);
decimal = digit * (int) Math.pow(16, length - 1) + recursiveHexDec(substring);
}
return decimal;
}
}
When I choose an invalid number (Number that is not in between 1 and 4), the programme will then show "Invalid choice. Please choose a number between 1 and 4", and when I enter a valid number after that, the programme just stops running.
It does not ask me to enter a decimal number if, for example, I choose '1'. What am I missing?
You have no loop, where you try it again and again until a vaild number is entered.
Try this one:
int choice = -1;
while (choice < 0 || choice > 4) {
choice = input.nextInt();
switch (choice) {
case 1:
System.out.println("\nEnter Decimal Number");
break;
case 2:
System.out.println("\nEnter Decimal Number");
break;
case 3:
System.out.println("\nEnter Binary");
break;
case 4:
System.out.println("\nEnter Hexadecimal");
break;
default:
System.out.println("\nInvalid choice. Please choose a number between 1 and 4.");
break;
}
}
But keep in mind, that there is no escape from the loop beside enterin a correct number.
You are waiting for a new entry in the default of the switch. So it just sits there until you put one in.
You could do that part before the switch more easily:
boolean badEntry = true;
do{
System.out.println("Your choice?");
int choice = input.nextInt();
if (( choice<1 )|| (choice>4)) {
System.out.println("\nInvalid choice. Please choose a number between 1 and 4.");
} else {
badEntry = false;
}
}
while (badEntry);
Your program doesn't stop. It's actually waiting for input after you enter the valid number. If you don't believe me, try entering another number after you enter the valid choice. For me, it worked something like this.
Number Conversion Systems
1. Decimal to Binary
2. Decimal to Hexadecimal
3. Binary to Decimal
4. Hexadecimal to Decimal
Your choice?
5
Invalid choice. Please choose a number between 1 and 4.
1
23
Decimal to Binary (23) = 10111
However, by the time you've reached the point in your program where you enter a valid choice, the part that prints out the message such as "Enter decimal number" has already passed; which is why you're not getting that message.

Convert Binary to Hex in Java using loop and switch

public static void main(String[] args) {
Scanner ms = new Scanner(System.in);
String binary = ms.nextLine();
binary=binary.trim();
//add leading zeroes if length divided by 4 has remainder.
while (binary.length() % 4 != 0) binary = "0" + binary;
String number = "";
for (int i = 0; i < binary.length(); i += 4) {
String num = binary.substring(i, i + 3);
switch(num)
{
case "0000" : number = "0"; break;
case "0001" : number = "1"; break;
case "0010" : number = "2"; break;
case "0011" : number = "3"; break;
case "0100" : number = "4"; break;
case "0101" : number = "5"; break;
case "0110" : number = "6"; break;
case "0111" : number = "7"; break;
case "1000" : number = "8"; break;
case "1001" : number = "9"; break;
case "1010" : number = "A"; break;
case "1011" : number = "B"; break;
case "1100" : number = "C"; break;
case "1101" : number = "D"; break;
case "1110" : number = "E"; break;
case "1111" : number = "F"; break;
}
System.out.println(number);
}
}
I need to use loop and a switch op to do the conversion. After making those changes. I get my result of binary 1111 1110 as F then E on the next line. How can I fix that? I don't want to use stringbuilder because I haven't learn that. Is there any other simple code to do that?
Your return statement is inside your for loop, so after the first iteration you will return from the function. Also, you are overwriting number at every itteration. You should instead replace number with a StringBuilder and user append().
public static void main(String[] args) {
Scanner ms = new Scanner(System.in);
String binary = ms.nextLine();
binary.trim();
//add leading zeroes if length divided by 4 has remainder.
while (binary.length() % 4 != 0) binary = "0" + binary;
StringBuilder number = new StringBuilder();
for (int i = 0; i < binary.length(); i += 4) {
String num = binary.substring(i, i + 4);
switch(num)
{
case "0000" : number.append("0"); break;
case "0001" : number.append("1"); break;
case "0010" : number.append("2"); break;
case "0011" : number.append("3"); break;
case "0100" : number.append("4"); break;
case "0101" : number.append("5"); break;
case "0110" : number.append("6"); break;
case "0111" : number.append("7"); break;
case "1000" : number.append("8"); break;
case "1001" : number.append("9"); break;
case "1010" : number.append("A"); break;
case "1011" : number.append("B"); break;
case "1100" : number.append("C"); break;
case "1101" : number.append("D"); break;
case "1110" : number.append("E"); break;
case "1111" : number.append("F"); break;
}
System.out.println(number.toString());
}
return;
}
Also, others have also mentinoed, your binary.trim() does not work as expected, it needs to be binary = binary.trim().
Strings are immutable
binary = binary.trim(); //not just binary.trim();
Also, you'd want to get the string from index 0 to 3, not 0 to 4. So it's (i, i+3)
So in here it should be:
for (int i = 0; i < binary.length(); i += 4) {
String num = binary.substring(i, i + 3);
Also, take out the return statement at the bottom, because it exits the method when you do one iteration
Its because you're returning from the first iteration of the loop.
Anyways, here's the piece of code that does just what you want , convert binary string to hexadecimal
static String binToHex(String binStr){
while(binStr.length() % 4 != 0){
binStr = "0" + binStr;
}
String hexString = "";
binStr = new StringBuilder(binStr).reverse().toString();
for(int index = 0, len = binStr.length(); index < len;){
int num = 0;
for(int indexInQuad = 0; indexInQuad < 4; indexInQuad++, index++){
int bit=Integer.parseInt(String.valueOf(binStr.charAt(index)));
num += (bit * Math.pow(2,indexInQuad));
}
hexString += Integer.toHexString(num).toUpperCase();
}
hexString = new StringBuilder(hexString).reverse().toString();
return hexString;
}
it also saves you the switch statements
just pass it the binary string value and it works seamlessly :D
The immediate problem with your code is that you return right after printing the first number! Remove the return, and it will print the other numbers, too.
Also, as noted by Josh, you have to do binary = binary.trim();, as trim() will not alter the string in-place but return a trimmed version of the string.
And finally, note that you could replace most of your code with just this...
int n = Integer.parseInt(binary, 2);
String s = Integer.toString(n, 16);
System.out.println(s.toUpperCase());

Categories