Can I use switch structures in my Hexadecimal to Binary Converter - java

Im here again to ask question.
Earlier we have to explain our program in some instructor in my school and Thankfully I explained it well. but the problem is the codes that I used is Hashmapping but this was not yet taught to us
So the professor told me that I can use switch structure instead of using Hashmapping but I dont know how i can translate it in switch method..
Can you show me if its possible to create an Switch in my program..
PS: I Know I can used binary built in.. but this is the requirements
thank you
my code:
import java.util.*;
import java.io.*;
class Jasper {
public static void main(String[] args) throws IOException {
BufferedReader input = new BufferedReader(new InputStreamReader(
System.in));
HashMap<Character, String> map = new HashMap<Character, String>();
map.put('0', "0000");
map.put('1', "0001");
map.put('2', "0010");
map.put('3', "0011");
map.put('4', "0100");
map.put('5', "0101");
map.put('6', "0110");
map.put('7', "0111");
map.put('8', "1000");
map.put('9', "1001");
map.put('A', "1010");
map.put('B', "1011");
map.put('C', "1100");
map.put('D', "1101");
map.put('F', "1111");
System.out.print("Input your Hex Number here : ");
String userInput = input.readLine();
String x = userInput.toUpperCase();
String resultx = "";
for (int i = 0; i < userInput.length(); i++) {
char hexVal = x.charAt(i);
String binary = map.get(hexVal);
resultx = resultx + "\n" + hexVal + "-" + binary;
}
System.out.println("The Binary of " + x + ":" + resultx);
}
}

Since you want to use a switch let's extract it into a method like,
public static String charToBin(char ch) {
switch (Character.toUpperCase(ch)) {
case '0': return "0000";
case '1': return "0001";
case '2': return "0010";
case '3': return "0011";
case '4': return "0100";
case '5': return "0101";
case '6': return "0110";
case '7': return "0111";
case '8': return "1000";
case '9': return "1001";
case 'A': return "1010";
case 'B': return "1011";
case 'C': return "1100";
case 'D': return "1101";
case 'E': return "1110";
case 'F': return "1111";
}
return "Unknown";
}
Then you can convert a String from hex to binary with a method like,
public static String hexToBinary(String in) {
if (in == null) {
return null;
}
StringBuilder sb = new StringBuilder();
for (char ch : in.toCharArray()) {
sb.append(charToBin(ch));
}
return sb.toString();
}
Finally, you can test it with something like
public static void main(String[] args) {
for (int i = 0; i < 1000; i++) {
String val = Integer.toHexString(i);
String cust = hexToBinary(val);
assert(Integer.parseInt(cust, 2) == i);
}
}

Or you could do it like this:
/*ToDo - use your favourite parser to convert your string to an integer*/
System.out.println(Integer.toBinaryString(x/*x is type int*/));
Very important in software development not to reinvent things. Standard code is also self-documenting.
(Another approach would be to use >> repeatedly and use operators like %, | and ^ to yank out each bit in turn.)

for (int i = 0; i < userInput.length(); i++) {
char hexVal = x.charAt(i);
String binary;
switch (hexVal) {
case '0':
binary = "0000";
break;
case '1':
binary = "0001";
break;
case '2':
binary = "0010";
break;
case '3':
binary = "0011";
break;
case '4':
binary = "0100";
break;
case '5':
binary = "0101";
break;
case '6':
binary = "0110";
break;
case '7':
binary = "0111";
break;
case '8':
binary = "1000";
break;
case '9':
binary = "1001";
break;
case 'A':
binary = "1010";
break;
case 'B':
binary = "1011";
break;
case 'C':
binary = "1100";
break;
case 'D':
binary = "1101";
break;
case 'E':
binary = "1110";
break;
case 'F':
binary = "1111";
break;
}
resultx = resultx + "\n" + hexVal + "-" + binary;
}

As the previous contributors already wrote, you could use several elegant algorithms to provide a proper result, but using a switch() statement a with minimal changes of your code could look like this:
import java.util.*;
import java.io.*;
class Jasper {
public static void main(String[] args) throws IOException {
BufferedReader input = new BufferedReader(new InputStreamReader(
System.in));
System.out.print("Input your Hex Number here : ");
String userInput = input.readLine();
String x = userInput.toUpperCase();
String resultx = "";
String binVal;
for (char hexChar : x.toCharArray()) {
switch (hexChar) {
case('0') : binVal="0000";
break;
case('1') : binVal="0001";
break;
case('2') : binVal="0010";
break;
....
case('F') : binVal="1111";
break;
default : binVal="invalid input";
}
resultx = resultx + "\n" + hexChar + "-" + binVal;
}
System.out.println("The Binary of " + x + ":" + resultx);
}
}

Related

How do I convert number to a letter in Java? [duplicate]

This question already has answers here:
Switch statement with string wrong output
(2 answers)
Closed 2 years ago.
I want to make a program to convert number to letter, from 0-9 to ABCDEFGHIK.
For example:
with n = 10 the output would be BA as 0 is A is 0 and B is 1.
Here is my code:
String convertNumber(long n) {
String result="";
String strN = Long.toString(n);
for (int i=0; i < strN.length();i++){
char ch = strN.charAt(i);
switch(ch){
case '0':
result = "A";
case '1':
result = "B";
case '2':
result = "C";
case '3':
result = "D";
case '4':
result = "E";
case '5':
result = "F";
case '6':
result = "G";
case '7':
result = "H";
case '8':
result = "I";
case '9':
result = "K";
}
}
return result;
}
However, the results returns only K. Where did I do wrong? Thank you!
There are three mistakes in your program:
Not using break with the case and therefore every case will fall to the last case.
Using = instead of +=
Using the loop in reverse order than the required order. It should be for (int i = strN.length() - 1; i >= 0; i--) instead of for (int i=0; i < strN.length();i++)
Given below is your corrected program:
public class Main {
public static void main(String[] args) {
System.out.println(convertNumber(10));
}
static String convertNumber(long n) {
String result = "";
String strN = Long.toString(n);
for (int i = strN.length() - 1; i >= 0; i--) {
char ch = strN.charAt(i);
switch (ch) {
case '0':
result += "A";
break;
case '1':
result += "B";
break;
case '2':
result += "C";
break;
case '3':
result += "D";
break;
case '4':
result += "E";
break;
case '5':
result += "F";
break;
case '6':
result += "G";
break;
case '7':
result += "H";
break;
case '8':
result = "I";
break;
case '9':
result = "K";
}
}
return result;
}
}
Output:
AB
You can use this one:
static String convertNumber(int n) {
int reminder;
char[] arr = "ABCDEFGHIK".toCharArray();
int len = arr.length;
StringBuilder builder = new StringBuilder();
while (n != 0) {
reminder = (int) n % 10;
n /= 10;
builder.append(arr[(reminder % len)]);
}
return builder.toString();
}
, main
static public void main(String[] args) {
System.out.println(convertNumber(65));
System.out.println(convertNumber(78));
System.out.println(convertNumber(99));
System.out.println(convertNumber(901));
}
, output
FG
IH
KK
BAK
You forgot the break. add break; in every case, like this:
case '0':
result = "A";
break;
case '1':
result = "B";
break;

Calculate Points from Letters in a Switch Case

I am trying to create a scrabble-like program that calculates the points of letters contained in a word. These word are contained in a .txt file. I can get it to read from the file, but unsure how to get it to calculate the value of each word. I have attached what I have done so far, and am wondering if a switch case is the best way to go, and if so, how do I assign a value to a letter with a switch case. Any help is appreciated.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pointsproblem;
/**
*
*/
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class PointsProblem {
/**
* #param args the command line arguments
* #throws java.io.FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
// TODO code application logic here
//create new object//
PointsProblem task1 = new PointsProblem();
File file = new File("dictionary.txt");
// read the file//
Scanner input = new Scanner(file);
//check if file can be found//
if (!file.isFile()) {
System.err.println("Cannot open file: " + input);
System.exit(0);
}
else {
System.out.println("Successfully opened file: " + input + ".");
}
//read all the lines in the file//
{
while (input.hasNext()) {
String word = input.nextLine();
System.out.println(word);
System.out.println("'" + input + "' is worth " + point + " points");
int point = "";
switch(point) {
case 'a': = "1":
case 'e': = "1";
case 'i': = "1";
case 'l': = "1";
case 'n': = "1";
case 'o': = "1";
case 'r': = "1";
case 's': = "1";
case 't': = "1";
case 'u': = "1";
case 'g': = "2";
case 'g': = "2";
case 'b': = "3";
case 'm': = "3";
case 'c': = "3";
case 'p': = "3";
case 'f': = "4";
case 'h': = "4";
case 'v': = "4";
case 'w': = "4";
case 'y': = "4";
case 'k': = "5";
case 'j': = "8";
case 'x': = "8";
case 'q': = "10";
case 'z': = "10";
return score = point + "";
}//end switch
}//end point calculation loop
public int getScore() {
return score;
}
//public boolean containsLetter(Character letter) {
//return points.contains(letter);//
}
I have tried assigning an int of X to the value as well. I would like it to read the word contained in the file and give a total score.
Looks like a Map<Character, Integer> would fit:
public class PointsProblem {
final Map<Character, Integer> pointsMap = Map.of(
'a', 1,
'e', 1,
//.......
'z', 10
);
Then, in your function, simply use the map to find the corresponding point for each character:
int wordPoints = 0;
for(char c : word.toCharArray())
wordPoints += pointsMap.get(c);
Use a map to store the values:
Map<Character, Integer> charValues = new HashMap();
charValues.put('a', 2);
charValues.put('b', 1);
You can use the chars() and collect as sum
int total = word.chars()
.mapToObj(c -> charValues.get((char)c))
.mapToInt(i -> (int)i)
.sum();
But according to your use case you can count the chars first and then multiply
Map<Character, Integer> counter = new HashMap<>();
while (input.hasNext()) {
String word = input.next();
word.chars().forEach(c -> counter.compute(c, (k, v) -> v == null ? 1 : v + 1));
}
counter.entrySet()
.stream()
.mapToInt(e -> charValues.get(e.getKey())*e.getValue())
.sum();
if you are using switch your code will look like:
int total = 0;
switch (c){
case 'a' : total += 1; break;
case 'b' : total += 2; break;
}
I'm not sure that the code you've shown us will compile. There are a few things you need to change;
1) You're setting a String to an int. You'll want to change that to
int point = 0
2) You aren't setting anything in the switch statement
Change case 'a': = "1": to case 'a': point = 1;
3) You will never set a unique value in the switch statement because you aren't using 'break'
Checkout this page for a good tutorial: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Basically without any break statements, your code will go through the of the statements and point will just be assigned to your last case
You want to have something along the lines of
switch(char) {
case 'a': point = 1;
break;
case 'e': point = 1;
break;
// etc.
default: point = 1; // maybe throw an error or add some logging for the default case
break;
}
return point;
I am presuming that you actually have this switch statement in it's own method and not in main as you've shown us above, otherwise the return statement won't help you.
You can also shorten this so that each case simply returns a value (again, if this is in it's own method), i.e.
switch(char) {
case 'a': return 1;
case 'b': return 1;
// etc.
}
edit:
The best way to get the point value of the whole word via a switch statement is:
char[] chars = word.toCharArray();
int point=0;
for (char c: chars) {
switch(c) {
case 'a':
point += 1;
break;
// etc.
}
}
System.out.println("Total point value of word '" + word + "' was " + point);
Instead of assigning individually for each 'case' statement, you can also use the fall through feature of the switch block.
int calcScore(String str)
{
int score = 0;
for(int i=0; i<str.length(); i++)
{
switch(str.charAt(i)) {
case 'a':
case 'e':
case 'i':
case 'l':
case 'n':
case 'o':
case 'r':
case 's':
case 't':
case 'u': score += 1; break;
case 'g': score += 2; break;
case 'b':
case 'm':
case 'c':
case 'p': score += 3; break;
case 'f':
case 'h':
case 'v':
case 'w':
case 'y': score += 4; break;
case 'k': score += 5; break;
case 'j':
case 'x': score += 8; break;
case 'q':
case 'z': score += 10; break;
}
}
return score;
}
This function can be called for each word.
Thanks everyone, I ended up with the following code which gives the output I am after;
System.out.println("Points problem");
File file = new File("dictionary.txt");
// read the file//
Scanner input = new Scanner(file);
//check if file can be found//
if (!file.isFile()) {
System.err.println("Cannot open file: " + file);
System.exit(0);
} else {
System.out.println("Successfully opened file: " + file + ".");
}
//read all the lines in the file//
while (input.hasNext()) {
String word = input.nextLine();
//System.out.println(word);
int l = word.length();
int point = 0;
for (int x = 0; x < l; x++) {
char c = word.charAt(x);
switch (c) {
case 'a':
case 'e':
case 'i':
case 'l':
case 'n':
case 'o':
case 'r':
case 's':
case 't':
case 'u':
point += 1;
break;
case 'd':
case 'g':
point += 2;
break;
case 'b':
case 'c':
case 'm':
case 'p':
point += 3;
break;
case 'f':
case 'h':
case 'v':
case 'w':
case 'y':
point += 4;
break;
case 'k':
point += 5;
break;
case 'j':
case 'x':
point += 8;
break;
case 'q':
case 'z':
point += 10;
break;
}//end switch*/
}//end point calculation loop
System.out.println(word + "is worth " + point + " points." );
}

How can I convert a hexadecimal number into binary without using parse or automatic conversion

Below I have a method named 'hextoBinary' that returns a hexadecimal to binary conversion through type void.
In order for me to continue with my program I need a conversion from hex to binary method that returns and int so I can convert that binary int into a decimal with my 'hextoDecimal' method.
Can anybody help me or guide me on what approach to take, i've been stuck on this for a while now. i am limited to doing this manually instead of using parse or java automatic conversions.
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
public class Main
{
static void hexToBinary(char hexdec[])
{
for (char c: hexdec)
{
switch (c)
{
case '0':
System.out.print("0000");
break;
case '1':
System.out.print("0001");
break;
case '2':
System.out.print("0010");
break;
case '3':
System.out.print("0011");
break;
case '4':
System.out.print("0100");
break;
case '5':
System.out.print("0101");
break;
case '6':
System.out.print("0110");
break;
case '7':
System.out.print("0111");
break;
case '8':
System.out.print("1000");
break;
case '9':
System.out.print("1001");
break;
case 'A':
System.out.print("1010");
break;
case 'B':
System.out.print("1011");
break;
case 'C':
System.out.print("1100");
break;
case 'D':
System.out.print("1101");
break;
case 'E':
System.out.print("1110");
break;
case 'F':
System.out.print("1111");
break;
default:
System.out.print("\nInvalid hexadecimal digit " + hexdec[c]);
}
}
}
public static int hextoDecimal(int n)
{
int decimal = 0, p = 0;
while(n != 0)
{
decimal += ((n % 10) * Math.pow(2,p));
n = n / 10;
p++;
}
return decimal;
}
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(new File("RAMerrors8x4c"));
ArrayList<String> hexValues = new ArrayList<>();
while(sc.hasNext())
{
hexValues.add(sc.nextLine());
}
hexToBinary(hexValues.get(0).toCharArray());
}
}
This code is based on some that came from here but that link no longer seems to be active. Anyway, from a hex string you can get an int like this:
int hexToDecimal(String s){
int result = 0;
int digit = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c >= '0' && c <= '9')
digit = c - '0';
else
if (c >= 'A' && c <= 'F')
digit = 10 + c - 'A';
else
inputError(s);
result = 16 * result + digit;
}
return result
}
I modified your code a little.
a. In your code only the first hex was printed.
Change:
call hexToBinary for every hex String.
b. the binary value was discarded after printing, so it couldn't be reused.
Change:
Changed returntype of hexToBinary from void to String and returned the binary value calculated.
To be able to return a String I add the peaces(nibbles) of the hex/binary to a String in every switch(case) clause.(a Stringbuilder might be better than a String - you can additionally improve that)
in the main: additionally collect all the returned binary values in a arraylist called "binaryValues" in order to have them for the next step.
With the above (little) changes I now have all the binary values that had already been calculated.
So I am able to simply use them in a binaryToDecimal method which just sums up the binary values weighted by their position.
Why not do it again? Because youd need to convert the A-F to numbers what your hexToBinary already did. So storing the values saves you doing that step again. I have a feeling that is what your teacher had in mind when he/she combined the tasks like this.
The resulting code is:
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
public class Main
{
static String hexToBinary(char hexdec[]) {
String hex = "";
for (char c : hexdec) {
switch (c) {
case '0':
System.out.print("0000");
hex += "0000";
break;
case '1':
System.out.print("0001");
hex += "0001";
break;
case '2':
System.out.print("0010");
hex += "0010";
break;
case '3':
System.out.print("0011");
hex += "0011";
break;
case '4':
System.out.print("0100");
hex += "0100";
break;
case '5':
System.out.print("0101");
hex += "0101";
break;
case '6':
System.out.print("0110");
hex += "0110";
break;
case '7':
System.out.print("0111");
hex += "0111";
break;
case '8':
System.out.print("1000");
hex += "1000";
break;
case '9':
System.out.print("1001");
hex += "1001";
break;
case 'A':
System.out.print("1010");
hex += "1110";
break;
case 'B':
System.out.print("1011");
hex += "1111";
break;
case 'C':
System.out.print("1100");
hex += "1100";
break;
case 'D':
System.out.print("1101");
hex += "1110";
break;
case 'E':
System.out.print("1110");
hex += "1110";
break;
case 'F':
hex += "1111";
System.out.print("1111");
break;
default:
System.out.print("\nInvalid hexadecimal digit " + hexdec[c]);
}
}
System.out.println();
return hex;
}
public static int binaryToDecimal(String binary) {
int decimal = 0;
for (int i = 1; i < binary.length()-1; i++) {
decimal += Math.pow(2, i-1) * (binary.charAt(binary.length()-i) - '0');
}
return decimal;
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(new File("RAMerrors8x4c"));
ArrayList<String> hexValues = new ArrayList<>();
ArrayList<String> binaryValues = new ArrayList<>();
while (sc.hasNext()) {
hexValues.add(sc.nextLine());
}
for (String hex : hexValues) {
String binary = hexToBinary(hex.toCharArray());
binaryValues.add(binary);
System.out.println(binary);
}
for (String binary : binaryValues) {
int decimal = binaryToDecimal(binary);
System.out.println(decimal);
}
}
}
}
Besides using a Stringbuilder another idea could be to do all the printing of the binary values in the main. The hexToBinary returns the String - so you can print it in the loop - if you want.

How to convert an input of 3 octal numbers into CHMOD permissions into Binary?

I am trying to create a program that takes input from the user using the command line of 3 octal number, for example 5, 2, 6 or 5,2,6 and convert them into 3 sets of 3 digit binary numbers, like 101 010 110, and also print out those corresponding CHMOD permissions like r-x -w- rw-.
I am having a lot of trouble splicing these numbers apart with substring into 3 separate numbers of 5 2 and 6.
I also need the program to convert from the set of binary digits into 3 numerical digits and permissions. And from the permissions into digits and binary.
Here is what I have so far:
import java.util.Scanner;
class Test {
public static void main(String cheese[]){
Scanner scan = new Scanner(System.in);
String line1 = scan.nextLine();
//String line2 = scan.nextLine();
//String line3 = scan.nextLine();
//String line4 = scan.nextLine();
//String line5 = scan.nextLine();
System.out.println(line12(line1));
}
public static String line12(String line){
String ownerPermissions = "";
String groupPermissions = "";
String otherPermissions = "";
int comma = 0;
int lineLength = line.length();
if (line.indexOf(" ") != -1){
comma = line.indexOf(",");
}else{
comma = 1;
}
String firstNumber = line.substring(0, 1);
line = line.substring(comma + 1, lineLength);
int comma2 = line.indexOf(",");
String secondNumber = line.substring(comma + 1, comma2);
String thirdNumber = line.substring(lineLength);
int firstInt= Integer.parseInt(firstNumber);
int secondInt = Integer.parseInt(secondNumber);
int thirdInt = Integer.parseInt(thirdNumber);
String firstBinary = Integer.toBinaryString(firstInt);
String secondBinary = Integer.toBinaryString(secondInt);
String thirdBinary = Integer.toBinaryString(thirdInt);
switch(firstInt){
case 0:
ownerPermissions = "---";
break;
case 1:
ownerPermissions = "--x";
break;
case 2:
ownerPermissions = "-w-";
break;
case 3:
ownerPermissions = "-wx";
break;
case 4:
ownerPermissions = "r--";
break;
case 5:
ownerPermissions = "r-x";
break;
case 6:
ownerPermissions = "rw-";
break;
case 7:
ownerPermissions = "rwx";
break;
}
switch(secondInt){
case 0:
groupPermissions = "---";
break;
case 1:
groupPermissions = "--x";
break;
case 2:
groupPermissions = "-w-";
break;
case 3:
groupPermissions = "-wx";
break;
case 4:
groupPermissions = "r--";
break;
case 5:
groupPermissions = "r-x";
break;
case 6:
groupPermissions = "rw-";
break;
case 7:
groupPermissions = "rwx";
break;
}
switch(thirdInt){
case 0:
otherPermissions = "---";
break;
case 1:
otherPermissions = "--x";
break;
case 2:
otherPermissions = "-w-";
break;
case 3:
otherPermissions = "-wx";
break;
case 4:
otherPermissions = "r--";
break;
case 5:
otherPermissions = "r-x";
break;
case 6:
otherPermissions = "rw-";
break;
case 7:
otherPermissions = "rwx";
break;
}
String output = firstBinary + " " + secondBinary + " " + thirdBinary + " and " + ownerPermissions + " " + groupPermissions + " " + otherPermissions;
return output;
}
}
You will find it easier if you make your code much simpler. I suggest something like
public static void main(String[] args) {
System.out.println(line12("5, 2, 6"));
}
public static String line12(String line) {
String[] nums = line.trim().split(" *, *");
StringBuilder sb = new StringBuilder();
for (String s : nums) {
if (sb.length() > 0) sb.append(" ");
int num = Integer.parseInt(s);
sb.append((num & 4) == 0 ? '-' : 'r');
sb.append((num & 2) == 0 ? '-' : 'w');
sb.append((num & 1) == 0 ? '-' : 'x');
}
return sb.toString();
}
prints
r-x -w- rw-

How to convert phonetic phone number to numeric phone number?

public class Driver
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String phoneNumber;
System.out.print("Enter a phonetic phone number: ");
phoneNumber = input.nextLine();
int i = 0;
while (i != phoneNumber.length())
{
char c = phoneNumber.charAt(i);
i++;
if (Character.isDigit(c) == true)
{
phoneNumber = String.valueOf(c);
}
else if (Character.isLetter(c) == true)
{
decode(c);
}
else
{
System.out.println("Improper input");
}
}
System.out.println("Numeric version of phone number: " + phoneNumber);
}
private static String decode(char c)
{
switch (c)
{
case 'A':
case 'B':
case 'C':
return "2";
case 'D':
case 'E':
case 'F':
return "3";
case 'G':
case 'H':
case 'I':
return "4";
case 'J':
case 'K':
case 'L':
return "5";
case 'M':
case 'N':
case 'O':
return "6";
case 'P':
case 'Q':
case 'R':
case 'S':
return "7";
case 'T':
case 'U':
case 'V':
return "8";
case 'W':
case 'X':
case 'Y':
case 'Z':
return "9";
}
return " ";
}
}
Right now my output is only showing the numeric value for the first digit. I'm not exactly sure what I need to do to display the whole string once it is converted from phonetic to numeric. Help would be much appreciated.
You are not changing your phone number actually, you can declare other variable to add changed characters which should be declared outside the loop.
String changedNumber="";//declare outside loop
//...
if (Character.isDigit(c) == true) {
changedNumber += String.valueOf(c);
} else if (Character.isLetter(c) == true) {
changedNumber += String.valueOf(decode(c));
} else {
System.out.println("Improper input");
}
Right now you are directly assigning digit to phoneNumber and you are just calling decode but you are not using returned value.
phoneNumber = String.valueOf(c);
String temp=""
while (i != phoneNumber.length()) {
char c = phoneNumber.charAt(i);
i++;
if (Character.isDigit(c) == true) {
temp += String.valueOf(c);
} else if (Character.isLetter(c) == true) {
temp += decode(c);
} else {
System.out.println("Improper input");
}
}
phoneNumber = temp;
System.out.println("Numeric version of phone number: " + phoneNumber);
The phoneNumber is never changed. You can create a new string called numericPhoneNumber and manipulate it instead.
And the next issue is this line.
phoneNumber = String.valueOf(c);
You are assigning the phoneNumber to the single character. You need to append that. A fixed version would be this.
String numericPhoneNumber = "";
for (char ch : phoneNumber.toCharArray())
{
if (Character.isLetter(ch))
numericPhoneNumber += decode(ch);
else
numericPhoneNumber += ch;
}
There is no need to check for digit, they will be handled by the else block. Hope this helps.
Okay, a couple things. First off, you are not assigning the changes to a new string. Add a temporary string and use += to assign the new changes, or, an even better approach, create a new StringBuilder object and append the changes using the .append() method:
Scanner input = new Scanner(System.in);
String phoneNumber;
System.out.print("Enter a phonetic phone number: ");
phoneNumber = input.nextLine();
StringBuilder sb = new StringBuilder(); //StringBuilder Object
for (int i = 0; i < phoneNumber.length(); i++)
{
if (Character.isLetter(phoneNumber.charAt(i)))
{
sb.append(decode(phoneNumber.charAt(i))); //Nice, easy-to-use append() method, which takes objects of most types
}
else if (Character.isDigit(phoneNumber.charAt(i)))
{
sb.append(phoneNumber.charAt(i));
}
else
{
System.out.println("Improper input");
}
}
System.out.println("Numeric version of phone number: " + sb.toString());
Second thing I should mention, your decode(char c) function, while well written, should convert the parameter to upper case when you use it, just in case someone enters a lowercase letter:
switch (Character.toUpperCase(c))
{
//case statements
}

Categories

Resources