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){
Related
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;
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." );
}
Im very new to java, newbee in short. I want to make a program that checks if the number is hexidecimal, binary, octal, decimal. And if its Hexdecimal/binary/octal convert it to decimal but if it is a decimal not convert it. in my case i made a jbutton that if its clicked it will first check the number then convert it to decimal if it is not a decimal. Now the problem is i don't know what to add to my code, at present i can only check if it is a hexidecimal and then convert it to decimal if it meets the requirements and if not it will just stay. here is my code.
private void del1ActionPerformed(java.awt.event.ActionEvent
evt) {
String hex=prime1.getText();
long dec=0;
int r=0,c=0,b,con,er;
con=(int)Math.round(inb);
String co2, tra=prime1.getText();
boolean valid;
if(valid=true){for (int i = 0; i < hex.length(); i++ ) {
int digit = hexValue( hex.charAt(i) );
if (digit == -1) {
return;
}dec = 16*dec + digit;
prime1.setText(String.valueOf(dec));
}
static int hexValue(char ch) {
switch (ch) {
case '0':
return 0;
case '1':
return 1;
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
case 'a': // Note: Handle both upper and lower case letters.
case 'A':
return 10;
case 'b':
case 'B':
return 11;
case 'c':
case 'C':
return 12;
case 'd':
case 'D':
return 13;
case 'e':
case 'E':
return 14;
case 'f':
case 'F':
return 15;
default:
return -1;
}
} // end hexValue
here prime1 is a jtextfield.
If I got you correctly, this should be what you are looking for:
int getBaseAndConvertToDecimal(String input) {
int output = -1;
for(int i=0; i<input.length(); i++) {
if(Character.isAlphabetic(input.charAt(i)) && Character.toUpperCase(input.charAt(i))<='F') {
output = 16;
}
else {
if(Character.isDigit(input.charAt(i)) && Integer.parseInt(String.valueOf(input.charAt(i)))>=8) {
output = 10;
}
else {
if(Character.isDigit(input.charAt(i)) && Integer.parseInt(String.valueOf(input.charAt(i)))>=2) {
output = 8;
}
else {
if(input.charAt(i)=='0' || input.charAt(i)=='1') {
output = 2;
}
else {
output = -1;
}
}
}
}
}
if(output != -1) {
//int this case, the output object represents the base of the input string
//Integer.parseInt(inputToConvert, destinationBase);
return Integer.parseInt(input, output);
}
return output;
}
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
}
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.