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

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/

Related

How to take multiple data types in single line on java?

I am new at coding and now I am learning Java. I tryed to write something like calculator. I wrote it with switch case but then I realized I must take all inputs in single line. For example in this code I took 3 inputs but in 3 different lines. But I must take 2 input and 1 char in single line. First first number second char and then third number. Can you help me ?
Public static void main(String[] args) {
int opr1,opr2,answer;
char opr;
Scanner sc =new Scanner(System.in);
System.out.println("Enter first number");
opr1=sc.nextInt();
System.out.println("Enter operation for");
opr=sc.next().charAt(0);
System.out.println("Enter second number");
opr2=sc.nextInt();
switch (opr){
case '+':
answer=opr1+opr2;
System.out.println("The answer is: " +answer);
break;
case '-':
answer=opr1-opr2;
System.out.println("The answer is: " +answer);
break;
case '*':
answer=opr1*opr2;
System.out.println("The answer is: " +answer);
break;
case '/':
if(opr2>0) {
answer = opr1 / opr2;
System.out.println("The answer is: " + answer);
}
else {
System.out.println("You can't divide to zero");
}
break;
default:
System.out.println("Unknown command");
break;
}
Try following way
System.out.print("Enter a number then operator then another number : ");
String input = scanner.nextLine(); // get the entire line after the prompt
String[] sum = input.split(" ");
Here numbers and operator separated by "space". Now, you can call them by sum array.
int num1 = Integer.parseInt(sum[0]);
String operator = sum[1]; //They are already string value
int num2 = Integer.parseInt(sum[2]);
Then, you can do as you did than.
You can try something like this:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter number, operation and number. For example: 2+2");
String value = scanner.next();
Character operation = null;
StringBuilder a = new StringBuilder();
StringBuilder b = new StringBuilder();
for (int i = 0; i < value.length(); i++) {
Character c = value.charAt(i);
// If operation is null, the digits belongs to the first number.
if (operation == null && Character.isDigit(c)) {
a.append(c);
}
// If operation is not null, the digits belongs to the second number.
else if (operation != null && Character.isDigit(c)) {
b.append(c);
}
// It's not a digit, therefore it's the operation itself.
else {
operation = c;
}
}
Integer aNumber = Integer.valueOf(a.toString());
Integer bNumber = Integer.valueOf(b.toString());
// Switch goes here...
}
Note: didn't validate input here.

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

how can i put my my binary, octal, and Hexadecimal in one loop

So my goal this week was to find the hexadecimal octal and binary for decimal. I was able to get the hexdecimal, binary, and octal but were individual loops on different public class. So i was wondering how could i make this code one and read the hexadecimal, octal, and binary all in one loop.
decimal to hexadecimal
import java.util.Scanner;
public class uncode {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a decimal number: ");
int decimal = input.nextInt();
String hex = "";
while (decimal != 0 ) {
int hexValue = decimal % 16;
char hexDigit = (hexValue <= 9 && hexValue > 0) ?
(char) (hexValue + '0') : (char)(hexValue - 10 + 'A');
hex = hexDigit + hex;
decimal = decimal / 16;
}
System.out.println("The hex number is " + hex);
}
}
decimal to octal
import java.util.Scanner;
public class octal {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a decimal number: ");
int decimal = input.nextInt();
String octal = "";
while ( decimal > 0 ) {
int remainder = decimal % 8;
octal = remainder + octal;
decimal = decimal / 8;
}
System.out.println("Octal number: " + octal);
}
}
decimal to binary
import java.util.Scanner;
public class GuessNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a decimal number: ");
int decimal = input.nextInt();
String binary = "";
while (decimal > 0) {
int remainder = decimal % 2;
binary = remainder + binary;
decimal = decimal / 2;
}
System.out.println("Binary number: " + binary);
}
}
Easy way would be to use already present converstions, for example
Scanner input = new Scanner(System.in);
System.out.println("Enter a decimal number: ");
int decimal = input.nextInt();
String hex = Integer.toHexString(decimal);
String oct = Integer.toOctalString(decimal);
String bin = Integer.toBinaryString(decimal);
If you need an integer value, not the string, you can use
int h = Integer.parseInt(hex, 16);
int o = Integer.parseInt(oct, 8);
int b = Integer.parseInt(bin, 2);
Assuming you don't want to use these methods (let's say you have your reasons).
First, you need to put your code in a method, not inside main.
Then you can do something like this:
public class Class {
public static void uncode() {
Scanner input = new Scanner(System.in);
System.out.println("Enter a decimal number: ");
int decimal = input.nextInt();
String hex = "";
while (decimal != 0) {
int hexValue = decimal % 16;
char hexDigit = (hexValue <= 9 && hexValue > 0) ? (char) (hexValue + '0')
: (char) (hexValue - 10 + 'A');
hex = hexDigit + hex;
decimal = decimal / 16;
}
System.out.println("The hex number is " + hex);
}
public static void octal() {
Scanner input = new Scanner(System.in);
System.out.println("Enter a decimal number: ");
int decimal = input.nextInt();
String octal = "";
while (decimal > 0) {
int remainder = decimal % 8;
octal = remainder + octal;
decimal = decimal / 8;
}
System.out.println("Octal number: " + octal);
}
public static void GuessNumbers() {
Scanner input = new Scanner(System.in);
System.out.println("Enter a decimal number: ");
int decimal = input.nextInt();
String binary = "";
while (decimal > 0) {
int remainder = decimal % 2;
binary = remainder + binary;
decimal = decimal / 2;
}
System.out.println("Binary number: " + binary);
}
public static void allInOne() {
Scanner input = new Scanner(System.in);
System.out.println("Enter a decimal number: ");
int decimal = input.nextInt();
int hex = decimal;
int oct = decimal;
int bin = decimal;
String hexal = "";
String octal = "";
String binary = "";
while (hex > 0 || oct > 0 || bin > 0) {
if (hex > 0) {
// Get Hexal
int hexValue = hex % 16;
char hexDigit = (hexValue <= 9 && hexValue > 0) ? (char) (hexValue + '0')
: (char) (hexValue - 10 + 'A');
hexal = hexDigit + hexal;
hex = hex / 16;
}
if (oct > 0) {
// Get Octal
int remainder = oct % 8;
octal = remainder + octal;
oct = oct / 8;
}
if (bin > 0) {
// Get Binary
int remainder = bin % 2;
binary = remainder + binary;
bin = bin / 2;
}
}
System.out.println("The hex number is " + hexal);
System.out.println("Octal number: " + octal);
System.out.println("Binary number: " + binary);
}
public static void main(String[] args) {
uncode();
octal();
GuessNumbers();
allInOne();
}
}
I tried to make as little changes to your code as possible.
Here i convert from decimal to octal,bineary,hexadecimal by calling method getEveryFromDeci(param1,param2) where param1 - any decimal number and param2- its base value like 8,2,16.
And also i convert octal,bineary,hexadecimal to decimal by calling method allToDeci(param1,param2) where param1 - value of hexadecimal,bineary,octal in string form and param2- base value of hexadecimal
private String getEveryFromDeci(Integer x,Integer y){
List<String> al = deciBin(x,y,new ArrayList<String>());
StringBuffer buffer = new StringBuffer();
for(String s : al)
buffer.append(s);
return buffer.toString();
}
private List<String> deciBin(Integer a,Integer b,List<String> list){
if(a>=b){
deciBin(a/b,b,list);
list.add(a%b > 9 ? getHexaDecimal(a%b):Integer.toString(a%b));
}else
list.add(Integer.toString(a));
return list;
}
private String getHexaDecimal(int d){
String s= null;
switch(d){
case 10:
s="A";
break;
case 11:
s="B";
break;
case 12:
s="C";
break;
case 13:
s="D";
break;
case 14:
s="E";
break;
case 15:
s="F";
break;
}
return s;
}
private int allToDeci(String applyNum,int type){
int sum =0;
char[] ch = applyNum.toCharArray();
for(int pum=0;pum<ch.length;pum++)
sum += Character.isDigit(ch[pum]) ? getAct(ch.length-(pum+1),type) * Character.getNumericValue(ch[pum]) :getAct(ch.length-(pum+1),type) * getNum(ch[pum]);
return sum;
}
private int getNum(char ch){
int num = 0;
switch(ch){
case 'A':
num =10;
break;
case 'B':
num = 11;
break;
case 'C':
num =12;
break;
case 'D':
num =13;
break;
case 'E':
num =14;
break;
case 'F':
num=15;
break;
default:
num =Character.getNumericValue(ch);
break;
}
return num;
}
private int getAct(int k,int p){
int s=1;
if(k >0){
for(int i=0;i<k;i++)
s *=p;
return s;
}else
return 1;
}

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

I can't restrict my program to accept only binary numbers

I'm creating a program for my gui number converter. I want my program to ask user a binary string and if he does not enter a binary number, the program will show him error message and will ask him to enter again. The problem is that I can add restriction to alphabets but when it comes to numbers then it fails or it keeps showing the error message.
import java.util.*;
public class test {
Scanner key = new Scanner(System.in);
String in;
int b;
public test(){
do{
System.out.println("Enter the binary string of 5 numbers");
in = key.nextLine();
int i,j;
char ch;
for (i=0 ; i<=5 ; i++){
b = 0;
ch = in.charAt(i);
j = ch;
if (Character.isDigit(ch) && ch<=0 && ch>=1)
b = 1;
else
System.out.println("Please enter a binary number (1 , 0)");
break;
//b = 1;
}
}while(b != 1);
int c;
c = Integer.parseInt(in);
System.out.println("your number is: " + c );
}
public static void main (String args[]){
test obj = new test();
}
}
ch<=0 && ch>=1 does not do what you think it does. The character codes for "0" and "1" are 48 and 49, so you should check for those instead. Also, your >= comparators are backwards, but that's not really the clearest way to write this code. And since you're comparing for just those two values, Character.isDigit(ch) is redundant.
Try one of these:
ch == 48 || ch == 49
ch == '0' || ch == '1'
Scanner has an overloaded nextInt method that uses a radix
int binaryNumber = scanner.nextInt(2);
1) First logic error here for (i=0 ; i<=5 ; i++) replace i<=5 to i<5
2) change the if else condition like below
if (Character.isDigit(ch) && (ch == '0' || ch == '1'))
{
b = 1;
}
else
{
System.out.println("Please enter a binary number (1 , 0)");
break;
}

Categories