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
}
Related
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.
I have been working on a utility to parse text files in the format used by Paradox Interactive in their grand strategy games to be used with a visual-based modding tool I am also developing. I have a mostly-implemented, crude, early version of the parser written out and it is mostly working as intended. This is my second attempt at writing a text parser (the first, which ended up working just fine, parsed a subset of XML).
I speed-wrote my parser on the 9th and have spent all weekend trying to debug it, but all my efforts have failed. I have tracked the issue down to the 3rd line of nextChar(). It was throwing an ArrayIndexOutOfBounds error with a crazy small number (in the -2 millions). After I added a bounds check the program just... continues. It reads all the information as needed, it just doesn't ever exit the parse loop.
The format is basically this:
car = {
model_year = 1966
model_name = "Chevy"
components = {
"engine", "frame", "muffler"
}
}
though I have yet to add support for nested lists like I plan, so my test string is:
car = {
model_year = 1966
model_name = "Chevy"
}
For both my understanding and anybody who would see my code, I tried to generously comment my code where I thought it might be necessary, though if any clarification is needed I would be happy to provide it.
My code:
/**
* Parses text files in the format used by Paradox Interactive in their computer games EUIV, CK2, and Stellaris.
*
* #author DJMethaneMan
* #date 12/9/2016
*/
public class Parser
{
private int pos, line, len, depth;
public String text;
private char[] script; //TODO: Initialize in the parse method
public Parser()
{
pos = 0;
line = 1;
len = 0;
depth = 0;
text = "car = {\n" +
" model_year = 1966 \n" +
" model_name = \"Chevy\"\n" +
"}\u0003";
//text = "Hello World";
//Car c = new Car();
//parse(text, c);
}
public static void main()
{
Car c = new Car();
Parser p = new Parser();
p.parse(p.text, c);
System.out.println("The model name is " + c.model_name);
System.out.println("The model year is " + c.model_year);
}
//TODO: Work
public void parse(String text, Parseable parsed)
{
char[] script = text.toCharArray();
this.script = script;
boolean next_char = false;
PARSE_LOOP:while(true)
{
char c;
if(next_char)
{
c = nextChar();
}
else
{
c = script[0];
next_char = true;
}
switch(c)
{
case 'A':
case 'a':
case 'B':
case 'b':
case 'C':
case 'c':
case 'D':
case 'd':
case 'E':
case 'e':
case 'F':
case 'f':
case 'G':
case 'g':
case 'H':
case 'h':
case 'I':
case 'i':
case 'J':
case 'j':
case 'K':
case 'k':
case 'L':
case 'l':
case 'M':
case 'm':
case 'N':
case 'n':
case 'O':
case 'o':
case 'P':
case 'p':
case 'Q':
case 'q':
case 'R':
case 'r':
case 'S':
case 's':
case 'T':
case 't':
case 'U':
case 'u':
case 'V':
case 'v':
case 'W':
case 'w':
case 'X':
case 'x':
case 'Y':
case 'y':
case 'Z':
case 'z':
case '_'://TODO: HERE
if(depth > 0) //
{
parsed.parseRead(buildWordToken(true), this);//Let the class decide how to handle this information. Best solution since I do not know how to implement automatic deserialization.
}
continueUntilChar('=', false); //A value must be assigned because it is basically a key value pair with {} or a string or number as the value
skipWhitespace();//Skip any trailing whitespace straight to the next token.
break;
case '{':
depth++;
break;
case '}':
depth--;
break;
case '\n':
line++;
break;
case ' ':
case '\t':
skipWhitespace();
break;
case '\u0003': //End of Text Character... Not sure if it will work in a file...
break PARSE_LOOP;
}
}
}
//Returns a string from the next valid token
public String parseString()
{
String retval = "";
continueUntilChar('=', false);
continueUntilChar('"', false);
retval = buildWordToken(false);
continueUntilChar('"', false); //Don't rewind because we want to skip over the quotation and not append it.
return retval;
}
//Returns a double from the next valid token
public double parseNumber()
{
double retval = 0;
continueUntilChar('=', false); //False because we don't want to include the = in any parsing...
skipWhitespace(); //In case we encounter whitespace.
try
{
retval = Double.parseDouble(buildNumberToken(false));
}
catch(Exception e)
{
System.out.println("A token at line " + line + " is not a valid number but is being passed as such.");
}
return retval;
}
/**********************************Utility Methods for Parsing****************************************/
protected void continueUntilChar(char target, boolean rewind)
{
while(true)
{
char c = nextChar();
if(c == target)
{
break;
}
}
if(rewind)
{
pos--;
}
}
protected void skipWhitespace()
{
while(true)
{
char c = nextChar();
if(!Character.isWhitespace(c))
{
break;
}
}
pos--;//Rewind because by default parse increments pos by 1 one when fetching nextChar each iteration.
}
protected String buildNumberToken(boolean rewind)
{
StringBuilder token = new StringBuilder();
String retval = "INVALID_NUMBER";
char token_start = script[pos];
System.out.println(token_start + " is a valid char for a word token."); //Print it.
token.append(token_start);
while(true)
{
char c = nextChar();
if(Character.isDigit(c) || (c == '.' && (Character.isDigit(peek(1)) || Character.isDigit(rewind(1))))) //Makes sure things like 1... and ...1234 don't get parsed as numbers.
{
token.append(c);
System.out.println(c + " is a valid char for a word token."); //Print it for debugging
}
else
{
break;
}
}
return retval;
}
protected String buildWordToken(boolean rewind)
{
StringBuilder token = new StringBuilder(); //Used to build the token
char token_start = script[pos]; //The char the parser first found would make this a valid token
token.append(token_start); //Add said char since it is part of the token
System.out.println(token_start + " is a valid char for a word token."); //Print it.
while(true)
{
char c = nextChar();
if(Character.isAlphabetic(c) || Character.isDigit(c) || c == '_')//Make sure it is a valid token for a word
{
System.out.println(c + " is a valid char for a word token."); //Print it for debugging
token.append(c); //Add it to the token since its valid
}
else
{
if(rewind)//If leaving the method will make this skip over a valid token set this to true.
{
//Rewind by 1 because the main loop in parse() will still check pos++ and we want to check the pos of the next char after the end of the token.
pos--;
break; //Leave the loop and return the token.
}
else //Otherwise
{
break; //Just leave the loop and return the token.
}
}
}
return token.toString(); //Get the string value of the token and return it.
}
//Returns the next char in the script by amount but does not increment pos.
protected char peek(int amount)
{
int lookahead = pos + amount; //pos + 1;
char retval = '\u0003'; //End of text character
if(lookahead < script.length)//Make sure lookahead is in bounds.
{
retval = script[lookahead]; //Return the char at the lookahead.
}
return retval; //Return it.
}
//Returns the previous char in the script by amount but does not decrement pos.
//Basically see peek only this is the exact opposite.
protected char rewind(int amount)
{
int lookbehind = pos - amount; //pos + 1;
char retval = '\u0003';
if(lookbehind > 0)
{
retval = script[lookbehind];
}
return retval;
}
//Returns the next character in the script.
protected char nextChar()
{
char retval = '\u0003';
pos++;
if(pos < script.length && !(pos < 0))
{
retval = script[pos]; //It says this is causing an ArrayIndexOutOfBoundsException with the following message. Shows a very large (small?) negative number.
}
return retval;
}
}
//TODO: Extend
interface Parseable
{
public void parseRead(String token, Parser p);
public void parseWrite(ParseWriter writer);
}
//TODO: Work on
class ParseWriter
{
}
class Car implements Parseable
{
public String model_name;
public int model_year;
#Override
public void parseRead(String token, Parser p)
{
if(token.equals("model_year"))
{
model_year = (int)p.parseNumber();
}
else if(token.equals("model_name"))
{
model_name = p.parseString();
}
}
#Override
public void parseWrite(ParseWriter writer)
{
//TODO: Implement along with the ParseWriter
}
}
Use of the labeled break statement break PARSE_LOOP; is generally considered bad practice. You are essentially writing a "goto" statement: whenever the break PARSE_LOOP; condition is hit, it jumps back to the beginning of the while loop (because that's where you wrote PARSE_LOOP:). This is probably the reason for your infinite loop. I also don't understand why you would restart a while loop that is already infinite (while true).
Change your code to:
public void parse(String text, Parseable parsed)
{
char[] script = text.toCharArray();
this.script = script;
boolean next_char = false;
boolean parsing = true;
while(parsing)
{
char c;
if(next_char)
{
c = nextChar();
}
else
{
c = script[0];
next_char = true;
}
switch(c)
{
case 'A':
case 'a':
case 'B':
case 'b':
case 'C':
case 'c':
case 'D':
case 'd':
case 'E':
case 'e':
case 'F':
case 'f':
case 'G':
case 'g':
case 'H':
case 'h':
case 'I':
case 'i':
case 'J':
case 'j':
case 'K':
case 'k':
case 'L':
case 'l':
case 'M':
case 'm':
case 'N':
case 'n':
case 'O':
case 'o':
case 'P':
case 'p':
case 'Q':
case 'q':
case 'R':
case 'r':
case 'S':
case 's':
case 'T':
case 't':
case 'U':
case 'u':
case 'V':
case 'v':
case 'W':
case 'w':
case 'X':
case 'x':
case 'Y':
case 'y':
case 'Z':
case 'z':
case '_'://TODO: HERE
if(depth > 0) //
{
parsed.parseRead(buildWordToken(true), this);//Let the class decide how to handle this information. Best solution since I do not know how to implement automatic deserialization.
}
continueUntilChar('=', false); //A value must be assigned because it is basically a key value pair with {} or a string or number as the value
skipWhitespace();//Skip any trailing whitespace straight to the next token.
break;
case '{':
depth++;
break;
case '}':
depth--;
break;
case '\n':
line++;
break;
case ' ':
case '\t':
skipWhitespace();
break;
case '\u0003': //End of Text Character... Not sure if it will work in a file...
parsing = false;
break;
}
}
}
Put a debug statement in to prove that it's hitting your break, I'm guessing it's not (Although it could be the break label--I haven't had reason to look into that construct since I first learned java a couple decades ago). I have a couple suggestions though...
I'd use isAlpha instead of that part of the switch. Cleaner, shorter, probably about as efficient and language-agnostic.
Instead of using the break label (Which is very uncommon), You might want to use boolean parsing=true;while(parsing)... instead. It's not really wrong to use the break label, but... Anything that causes the next guy to spend a minute or two scratching his head is a few minutes wasted.
I'm trying to get a program to encrypt a message using Cesar's Cypher, which involves replacing every character of a string with the letter, whose code is the code of the replaced letter plus 3. For e.g., if the letter is A, then it has to be replaced with D, because the code of D is the code of A plus 3. The letters are case-sensitive. The code I thought of uses a really heavy switch construct, I was wondering, if you could help me to make it more straight forward.
Here's the code I use for the encryption method:
public class Util
{
public static String Encript(String stringa)
{
char[] stringaArray=stringa.toCharArray();
for (int i =0; i<stringaArray.length; i++)
{
switch (stringaArray[i])
{
case 'a':
stringaArray[i]=('D');
break;
case 'b':
stringaArray[i]='E';
break;
case 'c':
stringaArray[i]='F';
case 'd':
stringaArray[i]='G';
break;
case 'e':
stringaArray[i]='H';
break;
case 'f':
stringaArray[i]='I';
break;
case 'g':
stringaArray[i]='J';
break;
case 'h':
stringaArray[i]='K';
break;
case 'i':
stringaArray[i]='L';
break;
case 'j':
stringaArray[i]='M';
break;
case 'k':
stringaArray[i]='N';
break;
case 'l':
stringaArray[i]='O';
break;
case 'm':
stringaArray[i]='P';
break;
case 'n':
stringaArray[i]='Q';
break;
case 'o':
stringaArray[i]='R';
break;
case 'p':
stringaArray[i]='S';
break;
case 'q':
stringaArray[i]='T';
break;
case 'r':
stringaArray[i]='U';
break;
case 's':
stringaArray[i]='V';
break;
case 't':
stringaArray[i]='W';
break;
case 'u':
stringaArray[i]='X';
break;
case 'v':
stringaArray[i]='Y';
break;
case 'w':
stringaArray[i]='Z';
break;
case 'x':
stringaArray[i]='A';
break;
case 'y':
stringaArray[i]='B';
break;
case 'z':
stringaArray[i]='C';
break;
}
}
String encripted= new String(stringaArray);
return encripted;
}
}
Then I use this method in the graphical interface class so that it acts when a button is pressed like this:
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
String stringa=messageTxt.getText();
encriptedTxt.setText(Util.Encript(stringa, encriptedTxt));
}
Here is an example of test-case:
Test case:
aBxyE //Input
dEabH //Output
Thank you in advance!
Khoor/#Zruog
You could iterate the characters in the String, and I would also pass in the key offset. Create a StringBuilder and append each character after performing integer addition and casting. Something like,
public static String encrypt(String msg, int key) {
StringBuilder sb = new StringBuilder();
for (char ch : msg.toCharArray()) {
char c = (char) (ch + key);
sb.append(c);
}
return sb.toString();
}
Decryption is trivial with a Caesar cipher; you can call encrypt with the negative value of the key
public static String decrypt(String msg, int key) {
return encrypt(msg, -key);
}
And I tested my example with
public static void main(String[] args) {
String msg = encrypt("Hello, World", 3);
System.out.println(msg);
System.out.println(decrypt(msg, 3));
}
Finally, as others have noted, the Caesar cipher is terribly insecure (because letter frequency is not perturbed, it's trivial in a modern sense).
This code will sawp a char with another one three chars apart, as defined in ALPHABET :
public class Util
{
private final static String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
public static String encript(String stringa)
{
char[] stringaArray = stringa.toCharArray();
for (int i =0; i<stringaArray.length; i++) {
char c = stringaArray[i];
int index = ALPHABET.indexOf(c);
if(index <0)
{
continue ; //if c does not appear in ALPHABET
}
// for example c is *, leave it unchanged
if((index +3) >= ALPHABET.length() ) {
index = index - ALPHABET.length();
}
stringaArray[i] = ALPHABET.charAt(index+3);
}
String encripted= new String(stringaArray);
return encripted;
}
}
If it is not clear, do not hesitate to ask.
Here is my Short and Efficient code for your program:
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//N is length of string
int N = Integer.parseInt(br.readLine());
//Reading string Input
String str = br.readLine();
//K is the key to rotate characters in the string
//In your case K = 3
int K = Integer.parseInt(br.readLine());
K %= 26; //Incase K is greater than 25
//Main [tag:algorithm]
for(int i = 0; i < N; i++){
char c = str.charAt(i);
if(c >= 65 && c <= 90){
c += K;
if(c > 90){
c = (char)(c - 90 + 64);
}
}
if(c >= 97 && c <= 122){
c += K;
if(c > 122){
c = (char)(c - 122 + 96);
}
}
System.out.print(c);
}
}
}
I am doing k = k % 26 because if the k = 26 then it will print the same letter, if k = 27 the character will rotate only 1 time and so on.
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);
}
}
The program is to write a calss PhoneNumber.java
I understand that I am supposed to test if the string is a digit or a letter and then if it is a letter its supposed to be decoded by decode(char c);
However, I dont think char c should be in between the ( ) If any one has suggestions thatd be great thanks!! The toString is left unreturned intentionally because i have not gotten that far in the program yet. Also, have to keep it in the case 'A' format Thanks
public class PhoneNumber {
private int areacode;
private int number;
private int ext;
PhoneNumber() {
areacode = 0;
number = 0;
ext = 0;
}
PhoneNumber(int newnumber) {
areacode = 216;
number = newnumber;
ext = 0;
}
PhoneNumber(int newarea, int newnumber, int newext) {
areacode = newarea;
number = newnumber;
ext = newext;
}
PhoneNumber(String newnumber) {
String areacode = str[0];
String number = str[1];
String[] str = newnumber.split("-");
String[] number = newnumber;
boolean b1, b2;
int i = 0;
int place = 0;
for (int x: newnumber){
newnumber.charAt[i] = place;
b1 = Character.isDigit(place);
if (b1 == true){
number = place;
i++;
} else {
b2 = Character.isLetter(place);
} if (b2 == true) {
number = decode(place);
i++;
} else {
System.out.print("invalid phone number!");
}
}
System.out.print(areacode.concat(number));
return newnumber;
}
private String decode(place) {
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";
default: return "";
}
}
public boolean equals(PhoneNumber pn) {
}
public String toString() {
}
}
G:\CIS260\Assignments>javac PhoneNumber.java
PhoneNumber.java:53: error: <identifier> expected
private String decode(place) {
^
1 error
In the constructor, you need to declare the array before you put things in it. You also can't say String[] number = newnumber because number is a String[] and newnumber is a String. equals() and toString() need to return something. And, to answer your question, just say
private String decode(char c){