Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have to keep it in the case 'A' Format i just don't understand what I should have in the (char c) because that seems to be where the error is coming from. If anyone has any suggestions it would be greatly appreciated.
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) {
//not complete
}
public String toString() {
//not complete
}
}
Here is the error:
G:\CIS260\Assignments>javac PhoneNumber.java
PhoneNumber.java:53: error: <identifier> expected
private String decode(place) {
^
1 error
You have one error that jump out at me. Note that if you have a syntax error, most compilers will freak out and mark everything past the actual error as errors. The best way to debug accidental syntax errors is to look at the first error :)
boolean = b1, b2;
Makes no sense. a variable declaration is as follows
[Type] [Variable Name] | ,[Additional Vars];
so it should be boolean b1, b2;
private 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";
default: return "";
}
}
I suggest you use a lookup table(hashmap) to do this set of code, it looks much less ugly and is easier on sore eyes.
An example of that would be
private static final Map<Char, String> myDecodeLookup = new Hashmap<Char,String>();
static{ //initializer block
myDecodeLookup.put('A', "2");
myDecodeLookup.put('B', "2");
//and so and and so forth
}
private String decode(char c) throws KeyNotFoundException{
return MyClassName.myDecodeLookup.get(c); //you should code this to support the keynotfoundexception that this might throw, or not.
}
If you ever find yourself debugging a syntax error for 5 hours, you should probably take a step back and look up the syntax of the language constructs themselves... that's good advice to take going forward.
Related
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." );
}
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.
Am trying to create a method to encrypt a word with Caesar cipher
here is the code:
public static void main (String [] args)
{
String s = "ahmed";
int k = 2;
char[] c = new char[5];
int[] a = new int[s.length()];
for (int i = 0; i<s.length();i++){
a[i] = Secret_Code_Library.getDigit(s.charAt(i));
a[i] = i + k ;
c[i] = Secret_Code_Library.getLetter(a[i]);
}
String ss = String.valueOf(c);
}
Secret_Code_Library is a class that contains the two methods
(getDigit(char): returns the number of the character a =0, b= 1...etc, and
getLetter(int): returns the letter corresponding to the number).
my problem is when ever i try to encrypt a word it encrypts only
the first letter correctly and save it in to the array a.
P.S: I have to use those two methods.
the output of the above code is: cdefg
while it should be: cjogf
this is the class :
public class Secret_Code_Library {
public static final char [] LETTERS={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z' };
public static char getLetter(int digit){
return LETTERS[digit]; }
public static int getDigit(char ch){
int digit=0;
switch (ch){
case 'A': digit=0; break; case 'B': digit=1; break; case 'C': digit=2; break;
case 'D': digit=3; break; case 'E': digit=4; break; case 'F': digit=5; break;
case 'G': digit=6; break; case 'H': digit=7; break; case 'I': digit=8; break;
case 'J': digit=9; break; case 'K': digit=10; break; case 'L': digit=11; break;
case 'M': digit=12; break; case 'N': digit=13; break; case 'O': digit=14; break;
case 'P': digit=15; break; case 'Q': digit=16; break; case 'R': digit=17; break;
case 'S': digit=18; break; case 'T': digit=19; break; case 'U': digit=20; break;
case 'V': digit=21; break; case 'W': digit=22; break; case 'X': digit=23; break;
case 'Y': digit=24; break; case 'Z': digit=25; break;
}// switch
return digit;
}}
a[i]= i + k ;
should be
a[i] = a[i] + k;
because you're not adding the key to the position of the current encrypted character, but the integer value of the character itself.
But that is not enough. What happens when you're encrypting 'z' with k = 2? You should wrap around in the alphabet, if the Secret_Code_Library.getLetter(a[i]); doesn't already do this for you.
If your alphabet is 26 characters long, then this should do it:
a[i] = (a[i] + k) % 26;
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
Question
Write a method that returns a number, given an uppercase letter, as follows.
int getNumber (char uppercaseLetter)
Write a test program that prompts the user to enter a phone number as a string. The input number may contain letters. The program translates a letter (uppercase or lowercase) to a digit and leaves all other characters intact.
Sample run from textbook
Enter a string: 1-800-Flowers
1-800-3569377
Enter a string: 1800flowers
18003569377
Here is what I have so far
import java.util.Scanner;
public class Assignment {
public static int correspondingNumber(char uppercaseLetter){
int correspondingNumber=0;
switch (uppercaseLetter)
{
case 'A':
case 'B':
case 'C': correspondingNumber=2; break;
case 'D':
case 'E':
case 'F': correspondingNumber=3; break;
case 'G':
case 'H':
case 'I': correspondingNumber=4; break;
case 'J':
case 'K':
case 'L': correspondingNumber=5; break;
case 'M':
case 'N':
case 'O': correspondingNumber=6; break;
case 'P':
case 'Q':
case 'R':
case 'S': correspondingNumber=7; break;
case 'T':
case 'U':
case 'V': correspondingNumber=8; break;
case 'W':
case 'X':
case 'Y':
case 'Z': correspondingNumber=9; break;
}
return correspondingNumber;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String num;
char num1 = 0;
System.out.print("Enter a string: ");
num = input.next();
num.toUpperCase();
int i=0;
while(i!=num.length()){
num1=num.charAt(i);
}
System.out.print(correspondingNumber(num1));
}
}
steps need tobe done
scan input let's say as String
Convert string to character array (srcArray)
change method return of correspondingNumber to Char
default return to input and apply switch case
call method correspondingNumber, store return char in stringbuilder or Array of Char array
repeat step-5 until character array(srcArray) is completely processed
print the output
import java.util.Scanner;
public class Assignment {
// changed return type
public static char correspondingNumber(char uppercaseLetter) {
char correspondingNumber = uppercaseLetter;// default the return value
// to input
switch (uppercaseLetter) {
case 'A':
case 'B':
case 'C':
correspondingNumber = '2';
break;
case 'D':
case 'E':
case 'F':
correspondingNumber = '3';
break;
case 'G':
case 'H':
case 'I':
correspondingNumber = '4';
break;
case 'J':
case 'K':
case 'L':
correspondingNumber = '5';
break;
case 'M':
case 'N':
case 'O':
correspondingNumber = '6';
break;
case 'P':
case 'Q':
case 'R':
case 'S':
correspondingNumber = '7';
break;
case 'T':
case 'U':
case 'V':
correspondingNumber = '8';
break;
case 'W':
case 'X':
case 'Y':
case 'Z':
correspondingNumber = '9';
break;
}
return correspondingNumber;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String num;
char num1 = 0;
System.out.print("Enter a string: ");
num = input.next();
num.toUpperCase();
int i = 0;
while (i != num.length()) {
num1 = num.charAt(i);
System.out.print(correspondingNumber(num1)); // moved print
// statement to
// appropriate place
i++; // iterate loop
}
input.close();
}
}
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){