Math tutor program wont display "incorrect" - java

package chapter5;
import java.util.Scanner;
public class Exercise5 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int min = 1;
int max = 10;
int one = (int) (Math.random() * (max - min)) + min;
int two = (int) (Math.random() * (max - min)) + min;
int num = (int) (4* Math.random()+1);
char operator = 0;
switch (num)
{
case 1: operator = '+';
break;
case 2: operator = '-';
break;
case 3: operator = '*';
break;
case 4: operator = '/';
break;
}
System.out.println("What is " + one + " " + operator + " " + two + "?");
double ans = 0;
double ans1 = 0;
ans = input.nextDouble();
if (num == 1) {
ans1 = one + two;
} else {
if (num == 2) {
ans1 = one - two;
} else {
if (num == 3 ) {
ans1 = one * two;
} else {
if (num == 4) {
ans1 = one / two;
}
}
}
if (ans == ans1) {
System.out.println("Correct!");
} else {
if (ans != ans1) {
System.out.println("incorrect");
}
}
}
}
}
So I am trying to create an application that generates a question, and calculates if your input is correct or incorrect, so far from all my tests, when it is correct it displays the correct thing, but when it is incorrect the app terminates.

I cleared your code up a little bit, it seems to run fine either way though. Perhaps you should check your editor settings to see if the output console doesn't clear when the program is finished executing.
package chapter5;
import java.util.Scanner;
public class Excercise5 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int min = 1;
int max = 10;
int one = (int) (Math.random() * (max - min)) + min;
int two = (int) (Math.random() * (max - min)) + min;
int num = (int) (4 * Math.random());
char operator = "+-/*".charAt(num);
System.out.println("What is " + one + " " + operator + " " + two + "?");
double ans = 0;
double ans1 = 0;
ans = input.nextDouble();
switch(num) {
case 0:
ans1 = one + two;
break;
case 1:
ans1 = one - two;
break;
case 2:
ans1 = one / two;
break;
case 3:
ans1 = one * two;
break;
}
if (ans == ans1) {
System.out.println("Correct!");
} else {
System.out.println("Incorrect");
}
}
}

Related

I need to make this java code repeat based on the user input and I cannot make it repeat using the code that I do have so far

I need to make this java code repeat based on the user input, and I cannot make it repeat using the code that I do have so far. I am not supposed to use any other imports besides the scanner and use class main. This is because we are using the https://repl.it/languages/java10 as our compiler because we are an elementary class. When I run the code, it is supposed to ask ten random addition and subtraction and should ask if the user wants to continue or not. When entering 1 for continue, it should ask another ten questions. however, upon running this code, it stops after the first question.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
System.out.println("Answer the following questions.");
Scanner in = new Scanner(System.in);
int A = 0;
int N = 10;
int n = 0;
int H = 0;
boolean p = true;
while (p){
int R1 = (int)(Math.random() * 50 + 1);
int R2 = (int)(Math.random() * 999 + 1);
int R3 = (int)(Math.random() * 999 + 1);
if(R1>25){
System.out.println( "" + R2 + " + " + R3);
A = in.nextInt();
if (A == (R2 + R3))
System.out.println("Correct");
else
System.out.println("Incorrect");
}
if(R1<25){
System.out.println( "" + R2 + " - " + R3);
A = in.nextInt();
if (A == (R2 - R3))
System.out.println("Correct");
else
System.out.println("Incorrect");}
N--;
if (N==0)
p = false;
continue;
}System.out.println("Do you want ot continue? Put 1 for yes, 2 for no.");
H = in.nextInt();
if (H==1)
p=true;
else
p=false;
while (N>0);
}
}
That's why you put the question System.out.println("Do you want ot continue? Put 1 for yes, 2 for no."); out of the while.
I recommend use do while instead of while. So you just need to put the question inside of loop do while.
System.out.println("Answer the following questions.");
Scanner in = new Scanner(System.in);
int A = 0;
int N = 10;
int H = 0;
boolean p = true;
do{
int R1 = (int) (Math.random() * 50 + 1);
int R2 = (int) (Math.random() * 999 + 1);
int R3 = (int) (Math.random() * 999 + 1);
if (R1 > 25) {
System.out.println("" + R2 + " + " + R3);
A = in.nextInt();
if (A == (R2 + R3)) {
System.out.println("Correct");
} else {
System.out.println("Incorrect");
}
}
if (R1 < 25) {
System.out.println("" + R2 + " - " + R3);
A = in.nextInt();
if (A == (R2 - R3)) {
System.out.println("Correct");
} else {
System.out.println("Incorrect");
}
}
N--;
System.out.println("Do you want ot continue? Put 1 for yes, 2 for no.");
H = in.nextInt();
if (H == 1) {
p = true;
} else {
p = false;
}
if (N == 0) {
p = false;
System.out.println("You have reached your max attempts.")
}
}while (N > 0 && p);

Fraction calculator input error [duplicate]

This question already has answers here:
What is a NumberFormatException and how can I fix it?
(9 answers)
Closed 6 years ago.
I am working on a fraction calculator program for my AP Computer Science class. This code compiles and runs, however when I put in any input, besides quit, there is an error. With an input 8_9/4 + 3/7 there is an error of:
Exception in thread "main" java.lang.NumberFormatException: For input string: "4 + 3/7".
Can someone please help me figure out what's wrong?
import java.util.*;
public class FracCalc {
public static void main(String[] args) {
typeEquation();
}
public static void typeEquation() {
System.out.print("Enter an equation, or \"quit\" : ");
Scanner scan = new Scanner(System.in);
String fraction = scan.nextLine();
String secondOperator;
if (fraction.equalsIgnoreCase("quit")) {
finish();
}
else {
produceAnswer(fraction);
}
}
public static void produceAnswer(String fraction) {
int whole2;
int numerator2;
int denominator2;
int whole1;
int numerator1; //all caps identifier thing?
int denominator1;
String operator = fraction.substring((fraction.indexOf(" ")) + 1);
if (fraction.contains("_")) {
whole2 = Integer.parseInt(fraction.substring(0, fraction.indexOf("_")));
numerator2 = Integer.parseInt(fraction.substring(fraction.indexOf("_") + 1, fraction.indexOf("/")));
denominator2 = Integer.parseInt(fraction.substring(fraction.indexOf("/") + 1));
numerator2 = whole2 * denominator2 + numerator2;
}
else if (fraction.contains("/")) {
numerator2 = Integer.parseInt(fraction.substring(0,fraction.indexOf("/")));
denominator2 = Integer.parseInt(fraction.substring(fraction.indexOf("/") + 1));
}
else {
whole2 = Integer.parseInt(fraction.substring(0));
numerator2 = whole2;
denominator2 = 1;
}
if (fraction.contains("_")) {
whole1 = Integer.parseInt(fraction.substring(0, fraction.indexOf("_")));
numerator1 = Integer.parseInt(fraction.substring(fraction.indexOf("_") + 1, fraction.indexOf("/")));
denominator1 = Integer.parseInt(fraction.substring(fraction.indexOf("/") + 1));
numerator1 = (whole1*denominator1) + numerator1;
}
else if (fraction.contains("/")) {
numerator1 = Integer.parseInt(fraction.substring(0, fraction.indexOf("/")));
denominator1 = Integer.parseInt(fraction.substring(fraction.indexOf("/") + 1));
}
else {
whole1 = Integer.parseInt(fraction.substring(0));
numerator1 = whole1;
denominator1 = 1;
}
if (fraction.contains("_")) {
whole2 = Integer.parseInt(fraction.substring(0, fraction.indexOf("_")));
numerator2 = Integer.parseInt(fraction.substring(fraction.indexOf("_") + 1, fraction.indexOf("/")));
denominator2 = Integer.parseInt(fraction.substring(fraction.indexOf("/") + 1));
numerator2 = whole2 * denominator2 + numerator2;
}
else if (fraction.contains("/")) {
numerator2 = Integer.parseInt(fraction.substring(0, fraction.indexOf("/")));
denominator2 = Integer.parseInt(fraction.substring(fraction.indexOf("/") + 1));
}
else {
whole2 = Integer.parseInt(fraction.substring(0));
numerator2 = whole2;
denominator2 = 1;
}
if (operator.equals("+")) {
System.out.println(addingFractions(numerator1, numerator2, denominator1, denominator2));
}
else if (operator.equals("*")) {
System.out.println(multiplyingFractions(numerator1, numerator2, denominator1, denominator2));
}
else {
int x = numerator2;
int y = denominator2;
denominator2 = x;
numerator2 = y;
System.out.println(multiplyingFractions(numerator1, numerator2, denominator1, denominator2));
}
int dividend = (denominator1 * numerator2) + (numerator1 * denominator2);
int divisor = denominator1 * denominator2;
int remainder = dividend % divisor;
while (remainder != 0){
dividend = divisor;
divisor = remainder;
remainder = dividend % divisor;
}
}
public static String multiplyingFractions(int numerator1, int numerator2, int denominator1, int denominator2) {
int newNumerator = numerator1 * numerator2;
int newDenominator = denominator1 * denominator2;
int divisor = reducingFractions(newNumerator, newDenominator);
newNumerator /= divisor;
newDenominator /= divisor;
int integerComponent = 0;
while (newNumerator >= newDenominator) {
integerComponent++;
newNumerator -= newDenominator;
}
String answer = "";
if (integerComponent > 0) {
answer += integerComponent + "_";
}
if (newNumerator != 0) {
answer += reducingFractions(newNumerator, newDenominator);
}
return answer;
}
public static String addingFractions(int numerator1, int numerator2, int denominator1, int denominator2) {
int newNumerator = (numerator1 * denominator2) + (numerator2 * denominator1);
int newDenominator = denominator1 * denominator2;
int divisor = reducingFractions(newNumerator, newDenominator);
newNumerator /= divisor;
newDenominator /= divisor;
int integerComponent = 0;
while (newNumerator >= newDenominator) {
integerComponent++;
newNumerator -= newDenominator;
}
String answer = "";
if (integerComponent > 0) {
answer += integerComponent + "_";
}
if (newNumerator != 0) {
answer += newNumerator + "/" + newDenominator;
}
return answer;
}
public static int reducingFractions(int newNumerator, int newDenominator) {
int newNumerator_abs = Math.abs (newNumerator);
int newDenominator_abs = Math.abs (newDenominator);
int minimumNumber = Math.min (newNumerator_abs, newDenominator_abs);
int divisor = 1;
for (int i = 1; i <= minimumNumber; i++) {
if (newNumerator % i == 0 && newDenominator % i == 0){
divisor = 1;
}
}
return divisor;
}
public static void finish() {
System.out.println("Goodbye!");
}
}
You are getting this error, because you try to parse a String as integer, even if it isn't an integer. This is the problematic line:
denominator2 = Integer.parseInt(fraction.substring(fraction.indexOf("/") + 1));
for this input 8_9/4 + 3/7.
This fraction.indexOf("/") returns you the first occurrence of the slash. So, the following expression fraction.substring(fraction.indexOf("/") + 1) returns 4 + 3/7 which is not an integer, so it cannot be parsed using Integer.parseInt.
If you want to get only 4 instead of 4 + 3/7, you can replace your line with:
denominator2 = Integer.parseInt(fraction.substring(fraction.indexOf("/") + 1, fraction.indexOf(" ")));
You did not extract the "fraction" string correctly. Be careful when you do Integer.parseInt(). It doesn't take in equation.
In the code that you wrote:
else if (fraction.contains("/")) {
numerator2 = Integer.parseInt(fraction.substring(0,fraction.indexOf("/")));
denominator2 = Integer.parseInt(fraction.substring(fraction.indexOf("/") + 1));
}
The fraction.substring(0,fraction.indexOf("/") will return "8_9" as string. Which is not recognisable by Integer.parseInt.
Try to run in debug and set the breakpoint to break at Interger.parseInt for visualising the values.

Invoking Void Method to print an integer as text

I'm confused on what to put in the parameter of the oneDigit method and what to put in the main method where I invoke the oneDigit method in order to print out the four digit integer 4321 in words (Four Three Two One). Any help would be much appreciated!
import javax.swing.JOptionPane;
public class ToEnglish {
public static void oneDigit(int n1, int n2, int n3, int n4){
}//end oneDigit
public static void main(String[] args) {
int number;
int n1;
int n2;
int n3;
int n4;
String input;
JOptionPane.showMessageDialog(null,
"Welcome to the ToEnglish program by Josh Higgins!",
"ToEnglish",
JOptionPane.PLAIN_MESSAGE);
input = JOptionPane.showInputDialog(null,
"Please enter a four-digit integer",
"ToEnglish",
JOptionPane.QUESTION_MESSAGE);
number = Integer.parseInt(input);
//breaking integer up into 4 digits
n1 = number / 1000;
int n1Remainder = number % 1000;
n2 = n1Remainder / 100;
int n2Remainder = number % 100;
n3 = n2Remainder / 10;
int n3Remainder = number % 10;
n4 = number % 10;
if
(number < 0000 || number > 9999) {
System.out.println("Invalid input");
}
else {
n1 = number / 1000;
n1Remainder = number % 1000;
n2 = n1Remainder / 100;
n2Remainder = number % 100;
n3 = n2Remainder / 10;
n3Remainder = number % 10;
n4 = number % 10;
}
if ((number > 0000) && (number < 9999)) {
System.out.println(n1 + " " + n2 + " " + n3 + " " + n4 + " ");
}
else {
System.out.println("Invalid input");
}
//invoking oneDigit Method in order to print the four digit integer in text
oneDigit(n1);
oneDigit(n2);
oneDigit(n3);
oneDigit(n4);
System.out.println("All done for now!");
System.exit(0);
}//end of the main method
}//end of the class
#Vishal, this is my improved code, but when I run it, I only get 4 3 2 1, not the text. Any suggestions?
import javax.swing.JOptionPane;
public class ToEnglish {
public void oneDigit(int digit){
}//end oneDigit
public static void main(String[] args) {
int digit=0;
int number;
int n1;
int n2;
int n3;
int n4;
String input;
JOptionPane.showMessageDialog(null,
"Welcome to the ToEnglish program by Josh Higgins!",
"ToEnglish",
JOptionPane.PLAIN_MESSAGE);
input = JOptionPane.showInputDialog(null,
"Please enter a four-digit integer",
"ToEnglish",
JOptionPane.QUESTION_MESSAGE);
number = Integer.parseInt(input);
//breaking integer up into 4 digits
n1 = number / 1000;
int n1Remainder = number % 1000;
n2 = n1Remainder / 100;
int n2Remainder = number % 100;
n3 = n2Remainder / 10;
int n3Remainder = number % 10;
n4 = number % 10;
if
(number < 0000 || number > 9999) {
System.out.println("Invalid input");
}
else {
n1 = number / 1000;
n1Remainder = number % 1000;
n2 = n1Remainder / 100;
n2Remainder = number % 100;
n3 = n2Remainder / 10;
n3Remainder = number % 10;
n4 = number % 10;
}
if ((number > 0000) && (number < 9999)) {
System.out.println(n1 + " " + n2 + " " + n3 + " " + n4 + " ");
}
else {
System.out.println("Invalid input");
}
switch (digit) {
case 1 : System.out.print("One");
break;
case 2 : System.out.print("Two");
break;
case 3 : System.out.print("Three");
break;
case 4 : System.out.print("Four");
break;
case 5 : System.out.print("Five");
break;
case 6 : System.out.print("Six");
break;
case 7 : System.out.print("Seven");
break;
case 8 : System.out.print("Eight");
break;
case 9 : System.out.print("Nine");
break;
}
System.out.println("All done for now!");
System.exit(0);
}//end of the main method
}//end of the class
According to your method prototype, the oneDigit method accepts four integers and you have called the method with only one integer.
You could write the method with one parameter. Inside the method use a switch case with the parameter to print the number in words.
For example:
This code should be written inside the oneDigit method
public static void oneDigit(int digit) {
switch(digit) {
case 1 : System.out.print("One");
break;
//Other cases followed
}
You could follow this with all the digits.
Or you could write an if-else if blocks to check which integer is passed to the method and print the digit in words in that block.
EDIT : The code block
try this:
public static String oneDigit(int digit){
switch(digit){
case 0:
return "zero";
case 1:
return "one";
//add missing cases
default:
return "not in range"; //you can throw an exception here if you prefer
}
}

Error: reached end of file while parsing

I am getting this error:
Error: reached end of file while parsing
I know it means I need to close the curly bracket somewhere, but I have tried everything. I figured line 45 is the brace that needs to be closed, but I'm not sure how. This is a program for helping find the smallest number of coins needed to make the integer inputted by the user. For example, 37 would yield 2 Quarters, 1 Dime, and 2 pennies.
import java.util.Scanner;
public class Change {
public static void main(String[] args){
Scanner sc = new Scanner (System.in);
Int n = sc.nextInt("Enter a positive integer" );
int number1, number2; // Division operands
int quotient; // Result of division
{if (QtrCnt > 0)
if (QtrCnt > 1)
System.out.println(QtrCnt + " quarters");
else
System.out.println(QtrCnt + " quarter");
}
if (DimeCnt > 0)
{
if (DimeCnt > 1)
System.out.println(DimeCnt + " dimes");
else
System.out.println(DimeCnt + " dime");
}
if (NicklCnt > 0)
{
if (NicklCnt > 1)
System.out.println(NicklCnt + " nickles");
else
System.out.println(NicklCnt + " nickle");
}
if (PennyCnt > 0);
{
if (PennyCnt > 1);
System.out.println(PennyCnt + " pennies");
System.out.println(PennyCnt + " penny");
}
int q = 25;
int d = 10;
int n = 5;
int p = 1;
if (a < 0);
System.out.println("ERROR");
{
String (money >=25); { int numQuarters = money/ 25; }
money -= numQuarters * 25;
QtrCnt = (num1 - num1 % 25) / 25;
num1 = num1 - QtrCnt * 25;
String(money >=10); { int numDimes = money/ 10; }
money -= numDimes * 10;
DimeCnt = (num1 - num1 % 10) / 10;
num1 = num1 - DimeCnt * 10;
String (money >=5); { int numNickles = money/ 5; }
money -= numNickles * 5;
NicklCnt = (num1 - num1 % 5) / 5;
num1 = num1 - NicklCnt * 5;
String (money >=1); { int numPennies = money/ 1; }
money -= numPennies * 1;
PennyCnt = (num1 - num1 % 1) / 1;
num1 = num1 - PennyCnt * 1;
}
}
Yes, you are in fact missing the closing bracket for the class.
You also have a lot of brackets that basically don't do anything. Remember that if you don't put a { immediately after the () of an if, it won't belong to the if statement.
I cleaned up your code a little and got this:
import java.util.Scanner;
public class Change
{
public static void main(String[] args)
{
Scanner sc = new Scanner (System.in);
Int n = sc.nextInt("Enter a positive integer" );
int number1, number2; // Division operands
int quotient; // Result of division
{ // <- Won't do anything
if (QtrCnt > 0)
if (QtrCnt > 1)
System.out.println(QtrCnt + " quarters");
else
System.out.println(QtrCnt + " quarter");
}
if (DimeCnt > 0)
{
if (DimeCnt > 1)
System.out.println(DimeCnt + " dimes");
else
System.out.println(DimeCnt + " dime");
}
if (NicklCnt > 0)
{
if (NicklCnt > 1)
System.out.println(NicklCnt + " nickles");
else
System.out.println(NicklCnt + " nickle");
}
if (PennyCnt > 0);
{
if (PennyCnt > 1);
System.out.println(PennyCnt + " pennies");
System.out.println(PennyCnt + " penny");
}
int q = 25;
int d = 10;
int n = 5;
int p = 1;
if (a < 0);
System.out.println("ERROR");
{ // <- Won't do anything
String (money >=25); { int numQuarters = money/ 25; }
money -= numQuarters * 25;
QtrCnt = (num1 - num1 % 25) / 25;
num1 = num1 - QtrCnt * 25;
String(money >=10); { int numDimes = money/ 10; }
money -= numDimes * 10;
DimeCnt = (num1 - num1 % 10) / 10;
num1 = num1 - DimeCnt * 10;
String (money >=5); { int numNickles = money/ 5; }
money -= numNickles * 5;
NicklCnt = (num1 - num1 % 5) / 5;
num1 = num1 - NicklCnt * 5;
String (money >=1); { int numPennies = money/ 1; }
money -= numPennies * 1;
PennyCnt = (num1 - num1 % 1) / 1;
num1 = num1 - PennyCnt * 1;
}
}
// <- This is where you're missing the class bracket
Please try to improve the way you're formating your code because it really helps finding these kinds of mistakes very quickly.
Keep in mind that I only reformated the code, I did not change what it does or check if it even works.

Converting some hexadecimal string to a decimal integer

I wrote some code to convert my hexadecimal display string to decimal integer. However, when input is something like 100a or 625b (something with a letter) I got an error like this:
java.lang.NumberFormatException: For input string: " 100a" at
java.lang.NumberFormatException.forInputString(Unknown Source) at
java.lang.Integer.parseInt(Unknown Source)
How can I convert my string with letters to a decimal integer?
if(display.getText() != null)
{
if(display.getText().contains("a") || display.getText().contains("b") ||
display.getText().contains("c") || display.getText().contains("d") ||
display.getText().contains("e") || display.getText().contains("f"))
{
temp1 = Integer.parseInt(display.getText(), 16);
temp1 = (double) temp1;
}
else
{
temp1 = Double.parseDouble(String.valueOf(display.getText()));
}
}
It looks like there's an extra (leading) space character in your string (" 100a"). You can use trim() to remove leading and trailing whitespaces:
temp1 = Integer.parseInt(display.getText().trim(), 16);
Or if you think the presence of a space means there's something else wrong, you'll have to look into it yourself, since we don't have the rest of your code.
public static int hex2decimal(String s) {
String digits = "0123456789ABCDEF";
s = s.toUpperCase();
int val = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
int d = digits.indexOf(c);
val = 16*val + d;
}
return val;
}
That's the most efficient and elegant solution I have found on the Internet. Some of the other solutions provided here didn't always work for me.
//package com.javatutorialhq.tutorial;
import java.util.Scanner;
/* Java code to convert hexadecimal to decimal */
public class HexToDecimal {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.print("Hexadecimal Input: ");
// Read the hexadecimal input from the console
Scanner s = new Scanner(System.in);
String inputHex = s.nextLine();
try {
// Actual conversion of hexadecimal 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 hexadecimal number
System.out.println("Invalid Input");
}
finally {
s.close();
}
}
}
My way:
private static int hexToDec(String hex) {
return Integer.parseInt(hex, 16);
}
This is my solution:
public static int hex2decimal(String s) {
int val = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
int num = (int) c;
val = 256*val + num;
}
return val;
}
For example to convert 3E8 to 1000:
StringBuffer sb = new StringBuffer();
sb.append((char) 0x03);
sb.append((char) 0xE8);
int n = hex2decimal(sb.toString());
System.out.println(n); //will print 1000.
You can use this method to get the digit:
public int digitToValue(char c) {
(c >= '&' && c <= '9') return c - '0';
else if (c >= 'A' && c <= 'F') return 10 + c - 'A';
else if (c >= 'a' && c <= 'f') return 10 + c - 'a';
return -1;
}
void htod(String hexadecimal)
{
int h = hexadecimal.length() - 1;
int d = 0;
int n = 0;
for(int i = 0; i<hexadecimal.length(); i++)
{
char ch = hexadecimal.charAt(i);
boolean flag = false;
switch(ch)
{
case '1': n = 1; break;
case '2': n = 2; break;
case '3': n = 3; break;
case '4': n = 4; break;
case '5': n = 5; break;
case '6': n = 6; break;
case '7': n = 7; break;
case '8': n = 8; break;
case '9': n = 9; break;
case 'A': n = 10; break;
case 'B': n = 11; break;
case 'C': n = 12; break;
case 'D': n = 13; break;
case 'E': n = 14; break;
case 'F': n = 15; break;
default : flag = true;
}
if(flag)
{
System.out.println("Wrong Entry");
break;
}
d = (int)(n*(Math.pow(16,h))) + (int)d;
h--;
}
System.out.println("The decimal form of hexadecimal number "+hexadecimal+" is " + d);
}
Since there is no brute-force approach which (done with it manualy). To know what exactly happened.
Given a hexadecimal number
KₙKₙ₋₁Kₙ₋₂....K₂K₁K₀
The equivalent decimal value is:
Kₙ * 16ₙ + Kₙ₋₁ * 16ₙ₋₁ + Kₙ₋₂ * 16ₙ₋₂ + .... + K₂ * 16₂ + K₁ * 16₁ + K₀ * 16₀
For example, the hex number AB8C is:
10 * 16₃ + 11 * 16₂ + 8 * 16₁ + 12 * 16₀ = 43916
Implementation:
//convert hex to decimal number
private static int hexToDecimal(String hex) {
int decimalValue = 0;
for (int i = 0; i < hex.length(); i++) {
char hexChar = hex.charAt(i);
decimalValue = decimalValue * 16 + hexCharToDecimal(hexChar);
}
return decimalValue;
}
private static int hexCharToDecimal(char character) {
if (character >= 'A' && character <= 'F')
return 10 + character - 'A';
else //character is '0', '1',....,'9'
return character - '0';
}
You could take advantage of ASCII value for each letter and take off 55, easy and fast:
int asciiOffset = 55;
char hex = Character.toUpperCase('A'); // Only A-F uppercase
int val = hex - asciiOffset;
System.out.println("hexadecimal:" + hex);
System.out.println("decimal:" + val);
Output:
hexadecimal:A
decimal:10
A much simpler way is to use BigInteger, like so:
BigInteger("625b", 16)
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value");
String s = sc.next();
//String s = "AD";
String s1 = s.toUpperCase();
int power = 0;
double result = 0;
char[] c = s1.toCharArray();
for (int i = c.length-1; i >=0 ; i--) {
boolean a = true;
switch(c[i]){
case 'A': c[i] = 10; a = false; break;
case 'B': c[i] = 11; a = false; break;
case 'C': c[i] = 12; a = false; break;
case 'D': c[i] = 13; a = false; break;
case 'E': c[i] = 14; a = false; break;
case 'F': c[i] = 15; a = false; break;
}
if(a==true){
result = result + (c[i]-48) * Math.pow(16, power++);
}else {
result = result + (c[i]) * Math.pow(16, power++);
}
}
System.out.println(result);
This is a little library that should help you with hexadecimals in Java: https://github.com/PatrykSitko/HEX4J
It can convert from and to hexadecimals. It supports:
byte
boolean
char
char[]
String
short
int
long
float
double (signed and unsigned)
With it, you can convert your String to hexadecimal and the hexadecimal to a float/double.
Example:
String hexValue = HEX4J.Hexadecimal.from.String("Hello World");
double doubleValue = HEX4J.Hexadecimal.to.Double(hexValue);
Use:
public class Hex2Decimal {
public static void hexDec(String num)
{
int sum = 0;
int newnum = 0;
String digit = num.toUpperCase();
for(int i=0; i<digit.length(); i++)
{
char c = digit.charAt(digit.length()-i-1);
if(c == 'A')
{
newnum = 10;
}
else if(c == 'B')
{
newnum = 11;
}
if(c == 'C')
{
newnum = 12;
}
if(c == 'D')
{
newnum = 13;
}
if(c == 'E')
{
newnum = 14;
}
if(c == 'F')
{
newnum = 15;
}
else
{
newnum = Character.getNumericValue(c);
}
sum = (int) (sum + newnum*Math.pow(16, i));
}
System.out.println(" HexaDecimal to Decimal conversion is" + sum);
}
public static void main(String[] args) {
hexDec("9F");
}
}

Categories