Is there way to display number in exponent format - java

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

Related

Java number format exception error in number systems code

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

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.

How to format a converted phone number in java? [duplicate]

This question already has answers here:
How do format a phone number as a String in Java?
(17 answers)
Closed 7 years ago.
My program converts an alphanumeric phone number into only numbers. For example 1-800-FLOWERS to 18003569377. However, I'm trying to format my output to show 1-800-356-9377.
Heres my code so far:
public static void main(String[] args)
{
System.out.println ("Enter phone number:");
Scanner scanInput = new Scanner (System.in);
String initialPhoneNumber;
initialPhoneNumber = scanInput.nextLine ();
initialPhoneNumber = initialPhoneNumber.toUpperCase();
long convertedPhoneNumber = phoneNumber (initialPhoneNumber);
System.out.println ("Converted: " + convertedPhoneNumber);
}
public static long phoneNumber (String initialPhoneNumber)
{
long number = 0;
int stringLength = initialPhoneNumber.length();
for (int digitNum = 0 ; digitNum < stringLength ; digitNum++ )
{
char ch = initialPhoneNumber.charAt(digitNum);
if (Character.isLetter(ch))
{
switch(ch)
{
case 'A' : case 'B' : case 'C' : number *= 10; number += 2; break;
case 'D' : case 'E' : case 'F' : number *= 10; number += 3; break;
case 'G' : case 'H' : case 'I' : number *= 10; number += 4; break;
case 'J' : case 'K' : case 'L' : number *= 10; number += 5; break;
case 'M' : case 'N' : case 'O' : number *= 10; number += 6; break;
case 'P' : case 'Q' : case 'R' : case 'S' : number *= 10; number += 7; break;
case 'T' : case 'U' : case 'V' : number *= 10; number += 8; break;
case 'W' : case 'X' : case 'Y' : case 'Z' : number *= 10; number += 9; break;
}
}
else if (Character.isDigit(ch))
{
number *= 10; number += Character.getNumericValue(ch);
}
}
return number;
}
Any help would be greatly appreceiated!
Adding below mentioned in your main method will resolve you issue.
long subString = (convertedPhoneNumber%10000000);
String updatedStringPhone = initialPhoneNumber.substring(0,6)+subString/10000+"-"+subString%10000;
Overall method will be:
public static void main(String[] args)
{
System.out.println ("Enter phone number:");
Scanner scanInput = new Scanner (System.in);
String initialPhoneNumber;
initialPhoneNumber = scanInput.nextLine ();
initialPhoneNumber = initialPhoneNumber.toUpperCase();
long convertedPhoneNumber = phoneNumber (initialPhoneNumber);
long subString = (convertedPhoneNumber%10000000);
String updatedStringPhone = initialPhoneNumber.substring(0,6)+subString/10000+"-"+subString%10000;
System.out.println("Updated: "+updatedStringPhone);
System.out.println ("Converted: " + convertedPhoneNumber);
}
Description:
Converted to strings and added the following strings. For Example
"1-800-"
"356"
"-"
"9377"
You could use a StringBuilder and something like
StringBuilder sb = new StringBuilder(
String.valueOf(convertedPhoneNumber));
sb.insert(7, '-');
sb.insert(4, '-');
sb.insert(1, '-');
System.out.println("Converted: " + sb);
It's probably better to store the phone number as a string but if you store as an integer you can proceed as follows. You can drop digits on the right with / 10 or / 100 or / 1000 ... (integer division). You can drop digits on the left with % 10 or % 100 or % 1000 ... (remainder/modulus). Some combination of those operations will isolate the digits you want.
There is standart format method for Strings. In this example I took substrings and formatted as %s-%s-%s-%.
%s - shows substrings, first %s is first substring, second %s is second substring and etc.
String number = "18003569377";
String formattedNumber = String.format("%s-%s-%s-%s", number.substring(0, 1), number.substring(1, 4), number.substring(4, 7),number.substring(7, 11));
For more details about String.format you can read in this links:
http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html
http://examples.javacodegeeks.com/core-java/lang/string/java-string-format-example/

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

Can't detect 2 digit numbers when converting from RPN to Infix

i am trying to implement a java method which accepts an input in RPN (Reverse Polish Notation) and through use of a stack converts it into an infix notation and calculates it. I have built the stack and a working converter but i am finding problems when it comes to accepting multiple digit numbers (such as 10), my idea to solve this was to enter each separate entity separated by a space, 10+20 would be entered as "10 20 +" but this is resulting in an out of bounds error. Without the section marked below the program works fine for equations such as "12+" (1+2) and more complex ones as long as they involve single digit values. The stack is fully functiopnal too with push and pop methods
public static void stackRPN(){
Stack myStack = new Stack();
Scanner sc = new Scanner(System.in);
System.out.println("Enter an equation: ");
String eq = sc.nextLine();
int len = eq.length();
for (int i = 0; i < len; i++){
String car1 = String.valueOf(eq.charAt(i));
if ("+".equals(car1) || "-".equals(car1) || "/".equals(car1) || /*"car1"*/"x".equals(car1)){
String a = myStack.pop();
String b = myStack.pop();
//This handlws all the digits
double bI = Double.parseDouble(b);
double aI = Double.parseDouble(a);
double finalNo = 0;
switch (car1) {
case "+": finalNo = bI + aI;
break;
case "-": finalNo = bI - aI;
break;
case "/": finalNo = bI / aI;
break;
case "x": finalNo = bI * aI;
break;
}
myStack.push(finalNo+"");
String finEq = b+car1+a;
System.out.println(finEq + " = " +finalNo);
} else {
This bit does not work
while (len < i+1 && eq.charAt(i+1) != ' '){
car1 = car1+eq.charAt(i+1);
i++;
}
Till here
myStack.push(car1);
}
}
mainMenu();
}
This was fixed using the split method in the string class as so
public static void stackRPN(){
Stack myStack = new Stack();
Scanner sc = new Scanner(System.in);
System.out.print("Enter an equation: ");
System.out.println();
String eq = sc.nextLine();
//This Bit splits up the string where it meets a space
String[] eqS = eq.split(" ");
int len = eqS.length;
for (int i = 0; i < len; i++){
String car1 = eqS[i];
if ("+".equals(car1) || "-".equals(car1) || "/".equals(car1) || /*"car1"*/"x".equals(car1)){
String a = myStack.pop();
String b = myStack.pop();
//This handlws all the digits
double bI = Double.parseDouble(b);
double aI = Double.parseDouble(a);
double finalNo = 0;
switch (car1) {
case "+": finalNo = bI + aI;
break;
case "-": finalNo = bI - aI;
break;
case "/": finalNo = bI / aI;
break;
case "x": finalNo = bI * aI;
break;
}
myStack.push(finalNo+"");
String finEq = b+car1+a;
System.out.println(finEq + " = " +finalNo);
} else {
myStack.push(car1);
}
}
mainMenu();
}

Categories