I have to create a scrabble word search for my data structures class. I haven't reached the actual search yet. First, I need to create a bag of scrabble tiles. However, I keep getting errors when trying to add ScrabbleTile objects to my bag.
I have four classes: ScrabbleTile, ScrabbleBag, ScrabbleHand, and WordFinder.
Here is ScrabbleTile:
public class ScrabbleTile {
private char letter;
private int points;
ScrabbleTile (char letter)
{
this.letter = letter;
switch (letter)
{
case '_':
points = 0;
case 'e':
case 'a':
case 'i':
case 'o':
case 'n':
case 'r':
case 't':
case 'l':
case 's':
case 'u':
points = 1; break;
case 'd':
case 'g':
points = 2; break;
case 'b':
case 'c':
case 'm':
case 'p':
points = 3; break;
case 'f':
case 'h':
case 'v':
case 'w':
case 'y':
points = 4; break;
case 'k':
points = 5; break;
case 'j':
case 'x':
points = 8; break;
case 'q':
case 'z':
points = 10; break;
default: System.out.println("Incorrect character. Please enter a lowercase letter, a-z.");
break;
}
}
public char getLetter()
{
return letter;
}
public int getPoints()
{
return points;
}
}
Here is my ScrabbleBag class:
import DSLib.*;
public class ScrabbleBag {
private BagADT<ScrabbleTile> letterBag;
ScrabbleBag()
{
letterBag = new Bag<>();
for (int i = 0; i < 12; i++) {letterBag.add(ScrabbleTile('e'));}
}
}
In the ScrabbleBag constructor, I'm trying to add the correct number of each letter tile, starting with "e". Netbeans had a few suggestions which I tried, but then it was telling me the line syntax was wrong, after creating a few more instance variables in the ScrabbleBag class. How can I properly add ScrabbleTile objects to the bag?
My professor was very clear that we cannot use methods ahead of what we've gone over in class. Thanks in advance!
I think you missed new when create ScrabbleTitle object
for (int i = 0; i < 12; i++) {
letterBag.add(new ScrabbleTile('e'));
}
To create a ScrabbleTile you need the new keyword:
for (int i = 0; i < 12; i++) {
ScrabbleTile tile = new ScrabbleTile('e');
letterBag.add(tile);
}
Related
This question already has answers here:
In a switch statement, why are all the cases being executed?
(8 answers)
Closed last year.
I am working on the game where the columns of the board are represented by the characters but i would like to assign them an index.
I have decided to use the switch statement in that case, however it does produce the wrong result.
With the current code I attach, it gives me 14 as an index, however since the string is 7h, and it takes h as a char, it should give an index of 7. What Could be an issue? Thanks in advance!
public class Check {
public int columnToInt(char c) {
int index=0;
switch(c) {
case 'a':
index=0;
case 'b':
index=1;
case 'c':
index=2;
case 'd':
index=3;
case 'e':
index=4;
case 'f':
index=5;
case 'g':
index=6;
case 'h':
index=7;
case 'i':
index=8;
case 'j':
index=9;
case 'k':
index=10;
case 'l':
index=11;
case 'm':
index=12;
case 'n':
index=13;
case 'o':
index=14;
}
return index;
}
public static void main(String[] args) {
String myStr = "7h";
char c =myStr.charAt(1);
System.out.println("the char at position 1 is "+c);
Check check = new Check();
int result = check.columnToInt(c);
System.out.println(result);
}
}
Java switch statements can be a bit annoying to use. You need to use break or all the cases after the expected one will be executed as well.
switch(c) {
case 'a':
index=0;
break;
Alternatively you can use a return.
switch(c) {
case 'a':
return 0;
You must add the break keyword for each case.
For example:
case 'a':
index=0;
break;
otherwise next assignments are applied.
I'm trying to transpose a note, but the result it returns is not what it should be. Could you please check my code and tell me where I am wrong?
public int changeTone(String chord) {
int changeTone = 0;
switch(chord) {
case "I":
changeTone = 0;
break;
case "II":
changeTone = 1;
break;
case "III":
changeTone = 2;
break;
case "IV":
changeTone = 3;
break;
case "V":
changeTone = 4;
break;
case "VI":
changeTone = 5;
break;
case "VII":
changeTone = 6;
break;
case "i":
changeTone = 0;
break;
case "ii":
changeTone = 2;
break;
case "iii":
changeTone = 4;
break;
case "iv":
changeTone = 5;
break;
case "v":
canviDeTo = 7;
break;
case "vi":
changeTone = 9;
break;
case "vii":
changeTone = 11;
break;
default:
System.out.println("Vaya");
break;
}
return changeTone ;
}
public String getChord(int interval) {
String chord = "";
switch(interval) {
case "0":
chord = "C";
break;
case "2":
chord = "D";
break;
case "4":
chord = "E";
break;
case "5":
chord = "F";
break;
case "7":
chord = "G";
break;
case "9":
chord = "A";
break;
case "11":
chord = "B";
}
return chord;
}
public String WriteChord(String chords, String tone) {
String finalChord;
String[] chordArray = chords.split("-");
for(int i=0; i < chordArray.length; i++){
String chord = chordArray[i];
int interval = changeTone(chord);
chord = getChord(interval);
Note note = new Note(chord);
finalChord += note.changeValue(interval).toString() += "-";
}
return finalChord;
}
OK, so what this tries to do is to change the value of a chord given a chord progession with intervals. Like I-III-IV-iv. The user would choose a tone (the tonical, I note) and the chord would be changed taking the note as a reference. So, for example, running the code should do the following:
The user chooses a tone, say "E".
The code generates a chord progression, say "I-III-IV-iv".
The code gets the interval between I and III, I and IV, and I and iv.
The initial note, "E", changes its value with the interval.
The expected output is:
E-G#-A#-A#
The actual output is:
C-G#-G#-Bb
Why doesn't this work? I have simplified my code, so if you need a bit more let me know! Thanks in advance.
Edit: I have corrected the code and added the expected/gotten output.
JFugue already has support for intervals and chord progressions. I hope the following code satisfies your needs:
import org.jfugue.theory.ChordProgression;
public static void main(String[] args) {
ChordProgression cp = new ChordProgression("I-III-IV-iv").setKey("E");
System.out.println(cp);
}
The output from this code is:
E4MAJ G#4MAJ A4MAJ A4MIN
You can play this directly in a Player:
Player player = new Player(); // Don't forget to import org.jfugue.player.Player
player.play(cp);
If that's playing a little too fast for you because of the default duration of a quarter note, you can play each chord as something longer, say a whole note:
player.play(cp.eachChordAs("$!w"));
If you just want the roots, which in this case are [E, G#, A, A] (if you see an error with my music theory, please let me know), you can use:
cp.eachChordAs("$0");
There are several Chord Progression examples at http://www.jfugue.org/examples.html
I am working on a rather unique coding situation in Java. The purpose of the program I am trying to write is to take an Amateur Radio call sign, convert the letters in the call sign into numbers as defined by a list or other structure, treat the number as its face integer value, and run these numbers through several mathematical operations to output a unique "User Code" at the end. The length of characters, as well as the number itself, will vary from user to user based on their call sign, which is fine. The biggest obstacle I have encountered is that I do not want the letters to be assigned values in a 1-26 or 0-25 type pattern. I will post my code in a moment to show you. For the moment, the end use of this User Code is unimportant to this example, but suffice it to say that since I will be the only one using this particular code example I am not very concerned with doing validity checks or the like as I will ensure the integrity of the input data manually. With this being said, I do have a working solution which I will post here, but my question is not "it doesn't work" because it does work, my problem is that it is, in my opinion, bloated, and something tells me it could be cut down considerably. Here is the code, and following are some alternatives I considered but rejected:
import java.util.*;
import java.io.*;
public class UserCode
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int baseNumber = 0;
int finalNumber;
String callSign;
System.out.println("Enter CallSign for Code Generation: ");
callSign = in.nextLine();
String s = callSign.toUpperCase();
for (int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
if (Character.isDigit(c))
{
int l = Character.getNumericValue(c);
baseNumber = baseNumber + l;
}
else if (Character.isLetter(c))
{
int letNum = 0;
switch (c)
{
case 'A':
letNum = 23;
break;
case 'B':
letNum = 17;
break;
case 'C':
letNum = 5;
break;
case 'D':
letNum = 11;
break;
case 'E':
letNum = 34;
break;
case 'F':
letNum = 18;
break;
case 'G':
letNum = 13;
break;
case 'H':
letNum = 31;
break;
case 'I':
letNum = 27;
break;
case 'J':
letNum = 25;
break;
case 'K':
letNum = 7;
break;
case 'L':
letNum = 25;
break;
case 'M':
letNum = 33;
break;
case 'N':
letNum = 26;
break;
case 'O':
letNum = 28;
break;
case 'P':
letNum = 16;
break;
case 'Q':
letNum = 14;
break;
case 'R':
letNum = 2;
break;
case 'S':
letNum = 4;
break;
case 'T':
letNum = 6;
break;
case 'U':
letNum = 8;
break;
case 'V':
letNum = 10;
break;
case 'W':
letNum = 37;
break;
case 'X':
letNum = 12;
break;
case 'Y':
letNum = 3;
break;
case 'Z':
letNum = 1;
break;
default:
System.out.println("Call Contains a bad character. Try again. \n");
}
baseNumber = baseNumber + letNum;
}
}
System.out.println("\n");
String baseStr = Integer.toString(baseNumber);
System.out.println("The Base number is: " + baseStr + "\n");
int sMod = baseNumber%7;
String sModStr = Integer.toString(sMod);
System.out.println("The Check Digit is: " + sModStr + "\n");
String combine = baseStr + sModStr;
int nextOp = Integer.parseInt(combine);
finalNumber = nextOp * nextOp;
String finalStr = Integer.toString(finalNumber);
System.out.println("The User Code is: " + finalStr + "\n");
}
}
Okay, as I said this code works, but it is long. I had considered a few alternatives, none of which will really work. The first was Enum, but that obviously is outside my parameters as it produces a 1-26 incremented pattern. There are several variations of this using various for{} loops but the result there is the same. I even considered a new HashMap and map.put statements, but that's only marginally shorter and it would seem to me that creating a hashmap would, in the end, actually use more memory than my current solution. As you can see, I did not .split or use .toCharArray() since these created separate entities in memory that I did not need. All the information I needed was already contained in the string itself, except for my chosen numerical values. Finally, I could have created another class file with this assignment code, but the result is the same: the length itself hasn't been changed it's been spread over two files (and actually increased in calling the method).
Having put this out here, can anyone see any way I can shorten this code, particularly in the area of the switch{} block and still retain the same result with the same numerical values? I would be highly interested in any suggestions that can be made in this regard. BTW I didn't mention this but this is not a school assignment, this is a personal project, though my level of Java knowledge is about at that of a beginner taking my first Java class LOL. Thanks
if you want to stick with this logic then use a HashMap<Character, Integer> and setup only once the values like: map.put('Z', 1); and so on, then u don't need the switch. You can get the values by using: map.get('Z'); which will return every time 1
it is easy to implement and easy to change the code if needed
Create an array of corresponding integers:
int[] letnums = {23, 17, 5, ... };
char c = s.charAt(i);
if (Character.isLetter(c)) {
int letnum = letnums(c);
...
}
So i have created this code to convert words into phone numbers, but when i try to run this code with letters under 7 word it will display string index out of range. But 7 or more is fine. How do i fix this? If so how do i set the string range?
{
System.out.println("Enter a word to be converted: ");
String telLetter = console.next ();
telLetter = telLetter.toUpperCase();
String telNumber="7";
int count=0;
int i=0;
while(count <7)
{switch(telLetter.charAt(i))
{case 'A':case 'B':case 'C': case 'a': case 'b': case 'c':
telNumber += "2";
count++;
break;
case 'D':case 'E':case 'F': case 'd': case 'e': case 'f':
telNumber += "3";
count++;
break;
case 'G':case 'H':case 'I': case 'g': case 'h': case 'i':
telNumber += "4";
count++;
break;
case 'J':case 'K':case 'L': case 'j': case 'k': case 'l':
telNumber += "5";
count++;
break;
case 'M':case 'N':case 'O': case 'm': case 'n': case 'o':
telNumber += "6";
count++;
break;
case 'P':case 'R':case 'S': case 'p': case 'r': case 's':
telNumber += "7";
count++;
break;
case 'T':case 'U':case 'V': case 't': case 'u': case 'v':
telNumber += "8";
count++;
break;
case 'W':case 'X':case 'Y':case 'Z': case 'w': case 'x': case 'y': case 'z':
telNumber += "9";
count++;
break;
}
if( count==3) {
telNumber += "-";
}
i++;
}
System.out.println( telNumber );
}
}}
Fixes in code:
Use while(count < telLetter.length()) in place of while(count <7)...
telLetter.charAt(i) can be removed by (telLetter.charAt(count))... By doing this you don't need to create an extra variable int i = 0;... Its a good practice to keep variable minimum.
Use a scanner to get the input... Like.. Scanner sc = new Scanner(System.in); String telLetter = sc.next();...
After you used your resources do close them by using sc.close();....
Also i can see that you are appending 7 at the begining of every number... if that's a requirement then its ok.. other wise you can use... String telNumber="";
I would recommend using StringBuilder because in one object you can do it all.. While appending a character every time in string you are continuously creating a new string and giving it the reference of telNumber.
Also in your code either remove telLetter = telLetter.toUpperCase(); or remove the cases with lowercase alphabets.. because on making toUpperCase() you are just writing extra lines by writing cases for lowercase characters that are not needed...
System.out.println("Enter a word to be converted: ");
Scanner scan=new Scanner(System.in);
String telLetter = scan.next ();
int stringLength=telLetter.length();
telLetter = telLetter.toUpperCase();
String telNumber="7";
while(count <stringLength)
{
switch(telLetter.charAt(count))
Change your code like this.
But as per your code, the 7 is always prefixed in the converted phone number.
String telNumber=""; telNumber should be declared with empty string.
while(count <7)
Your code won't end until it has run through 7 characters. Try using while(count < telLetter.length())
Your while loop condition needs to check for the length of the telLetter string.
while (count <7 && count < telLetter.length())
Can anyone tell me what's wrong with my code, why am I not getting the correct letter count?
This program reads a text file and count each English letters, A-Z, and a-z, not case sensitive.
Thank you for helping.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class Solution {
private static int 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 void print(){
int[] in = {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};
for (int i = 0; i < in.length; i++){
System.out.println(in[i]);
}
}
public static void main(String[] args) throws FileNotFoundException{
File file = new File("t.txt");
Scanner scan = new Scanner(file);
while (scan.hasNextLine()) {
String line = scan.nextLine();
line = line.toLowerCase();
for (int i = 0; i < line.length(); i++) {
switch(line.charAt(i)) {
case 'a': a++;break;
case 'b': b++;break;
case 'c': c++;break;
case 'd': d++;break;
case 'e': e++;break;
case 'f': f++;break;
case 'g': g++;break;
case 'h': h++;break;
case 'i': i++;break;
case 'j': j++;break;
case 'k': k++;break;
case 'l': l++;break;
case 'm': m++;break;
case 'n': n++;break;
case 'o': o++;break;
case 'p': p++;break;
case 'q': q++;break;
case 'r': r++;break;
case 's': s++;break;
case 't': t++;break;
case 'u': u++;break;
case 'v': v++;break;
case 'w': w++;break;
case 'x': x++;break;
case 'y': y++;break;
case 'z': z++;break;
}
}
}
print();
}
}
The problem is that when you encounter a i, that will increment the variable of the loop, not the one in the array. So you will skip letters.
Change it with :
for (int counter = 0; counter < line.length(); counter++) {
switch(line.charAt(counter)) {
your problem is in the use the variable i
in your for loop the index counter is i and i is also a variable which you are using to count the occurrences of alphabet 'i'. use this main method, it will work.
public static void main(String[] args) throws FileNotFoundException{
File file = new File("t.txt");
Scanner scan = new Scanner(file);
while (scan.hasNextLine()) {
String line = scan.nextLine();
line = line.toLowerCase();
for (int index = 0; index < line.length(); index++) {
switch(line.charAt(index)) {
case 'a': a++;break;
case 'b': b++;break;
case 'c': c++;break;
case 'd': d++;break;
case 'e': e++;break;
case 'f': f++;break;
case 'g': g++;break;
case 'h': h++;break;
case 'i': i++;break;
case 'j': j++;break;
case 'k': k++;break;
case 'l': l++;break;
case 'm': m++;break;
case 'n': n++;break;
case 'o': o++;break;
case 'p': p++;break;
case 'q': q++;break;
case 'r': r++;break;
case 's': s++;break;
case 't': t++;break;
case 'u': u++;break;
case 'v': v++;break;
case 'w': w++;break;
case 'x': x++;break;
case 'y': y++;break;
case 'z': z++;break;
}
}
}
print();
}
also dont forget to close the scanner after you are done.