Convert Binary to Hex in Java using loop and switch - java

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

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

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

How do I define multiple variables within a switch by random?

I'm a noob in Java and need some help with this. I wonder how to get a random name for each of the nameOne, nameTwo and NameThree strings without duplicating the whole switch statement. Can someone please give me an advice on how to do this without bloating up my code? My actual name list is very long.
public class multipleNamesPicker {public static void main(String[] args) {
String nameOne = null;
String nameTwo = null;
String nameThree = null;
char gender1 = 'a';
char gender2 = 'a';
char gender3 = 'a';
byte randomNumber1 = (byte)(Math.random()*2+1);
switch(randomNumber1) {
case 1: gender1 = 'w';
case 2: gender1 = 'm';
}
byte randomNumber2 = (byte)(Math.random()*5+1);
if(gender1 == 'w'){
switch(randomNumber2) {
case 1: nameOne = "Edna";
case 2: nameOne = "Martha";
case 3: nameOne = "Berta";
case 4: nameOne = "Margaret";
case 5: nameOne = "Anna";
}
}
else{
switch(randomNumber2) {
case 1: nameOne = "Peter";
case 2: nameOne = "Paul";
case 3: nameOne = "Pablo";
case 4: nameOne = "Henry";
case 5: nameOne = "George";
}
}
System.out.println(nameOne + ", " + nameTwo + " and " + nameThree);}
}
One easy way would be to put them in two Array's (One for female names and one for male names) and then have something like
if(gender1 == 'w'){
nameOne = femaleNames[randomNum];
}
Where femaleNames is your Array of female names and randomNum is your random number. Just make sure randomNum is within bounds of your Array

'Error: Expected' when creating switch

import java.util.Scanner;
public class lab05a
{
public static void main (String[] args)
{
String statement;
Scanner scan = new Scanner(System.in);
int vowela;
int vowele;
int voweli;
int vowelo;
int vowelu;
int nonvowel;
int vowela = 0;
int vowele = 0;
int voweli = 0;
int vowelo = 0;
int vowelu = 0;
statement = scan.nextString();
statement = statement.toLowerCase();
for (int i = 0; i <= statement.length(); count++)
{
char c = examplestring.charAt(i);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
switch (c)
{
case 'a':
vowela += 1;
break;
case 'e':
vowele += 1;
break;
case 'i';
voweli += 1;
break;
case 'o';
vowelo += 1;
break;
case 'u';
vowelu += 1;
break;
}
else
nonvowel +=1;
}
System.out.prinln("a: " + vowela);
System.out.prinln("e: " + vowele);
System.out.prinln("i: " + voweli);
System.out.prinln("o: " + vowelo);
System.out.prinln("u: " + vowelu);
System.out.prinln("nonvowel: " + novowel);
}
}
I thought of doing it this way:
First I create a for loop to iterate through every character of String statement.
Then I put an if statement in the for loop that checks if c(declared as statement.charAt(i)) is a vowel.
If c is a vowel I use a switch to increase the count for that particular vowel by one and then break.
If c is not a vowel, it gets added to the count of consonants.
After the for loop is done it prints the count of each character.
The switch is where I am having problems. Case 'a' and case 'e' have cause no errors, but cases 'i' through 'u' cause an error('Error: : Expected').
I don't understand what this means or why, as cases 'i' through 'u' are written the same way as cases 'a' and 'e'. Can someone help me out?
3 errors found:
[line: 38] Error: : expected
[line: 41] Error: : expected
[line: 44] Error: : expected
Sorry if this post is poorly formatted I am new to Stack Overflow.
There are many errors in your code, I have modified it (posted at the bottom) and pointed out some of your mistakes:
Change statement = scan.nextString().toLowerCase(); to statement = scan.nextLine().toLowerCase();
I don't understand what this means or why, as cases 'i' through 'u' are written the same way as cases 'a' and 'e'.
Your switch is wrong because cases i, o, and u have a semi-colon(;) instead of a colon(:). Just that small difference is causing the error there. Change your switch statement to this:
switch(c) {
case 'a':
vowela++;
break;
case 'e':
vowele++
break;
case 'i':
voweli++
break;
case 'o':
vowelo++
break;
case 'u':
vowelu++;
break;
}
Here's your modified code. Now it is correct, and it works:
import java.util.Scanner;
public class lab05a {
public static void main (String[] args) {
String statement;
Scanner scan = new Scanner(System.in);
int vowela = 0;
int vowele = 0;
int voweli = 0;
int vowelo = 0;
int vowelu = 0;
int nonvowel = 0;
statement = scan.nextLine().toLowerCase();
for (int i = 0; i < statement.length(); i++) {
char c = statement.charAt(i);
switch (c) {
case 'a':
vowela++;
break;
case 'e':
vowele++;
break;
case 'i':
voweli++;
break;
case 'o':
vowelo++;
break;
case 'u':
vowelu++;
break;
default:
nonvowel++;
break;
}
}
System.out.println("a: " + vowela);
System.out.println("e: " + vowele);
System.out.println("i: " + voweli);
System.out.println("o: " + vowelo);
System.out.println("u: " + vowelu);
System.out.println("nonvowel: " + nonvowel);
}
}
You may have noticed some changes such as removing the if statement that checks for a vowel. Rather than doing all of that, I just added a default case. If none of the other conditions are true, than whatever is in the default case is executed. I also initialized your variables vowela, vowele, voweli, etc., and rather than doing vowela += 1 I just changed it to vowela++, which produces the same effect(same with the other letters).

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/

Categories