I am doing a homework assignment for my Java class. My instructor has some very defined requirements about what method calls and variables to use. One of the requirements is to write a method called public void initalizeSymbols(String inputFileName) that reads from an input file each letter of the alphabet and their morse code equivalent. I am trying to insure the variables are being passed to the arraylist, which we have to use, but can't get my System.out.println(input.toString()); to output anything which leads me to believe my variables arent being saved into the arrayList. The arrayList will be storing a-z, 1-0, ? / and all of their equivalent Morse code symbols which are made up of ... and ---. So it will be storing both strings and integers. Any help would be appreciated. I apologize if this is not in the right format since it is the first time I've posted here. Here is what I have:
public class MorseCodeTranslator
{
private String sentence;
private String translation;
private ArrayList<MorseCodeSymbol> morseCodeSymbols;
Scanner scannerIn;
public void initializeSymbols(String inputFileName)
{
String inputLine = "";
String letter = "";
String symbol = "";
try
{
scannerIn = new Scanner(new File(inputFileName));
while (scannerIn.hasNext())
{
inputLine = scannerIn.nextLine();
letter = inputLine.substring(0, inputLine.indexOf(' '));
symbol = inputLine.substring(inputLine.indexOf(' ') + 1);
MorseCodeSymbol input = new MorseCodeSymbol(letter, symbol);
morseCodeSymbols.add(input);
System.out.println(input.toString()); //this doesnt work
//System.out.println(letter + symbol); //this works
}
//MorseCodeSymbol input = new MorseCodeSymbol(" "," ");
//morseCodeSymbols.add(input);
}
catch (Exception ex)
{
}
//displayMorse();
}
}
public class MorseCodeSymbol
{
private String letter;
private String symbol;
public MorseCodeSymbol()
{
setLetter("");
setSymbol("");
}
public MorseCodeSymbol(String letter, String symbol)
{
this.letter = letter;
this.symbol = symbol;
}
public String getLetter()
{
return letter;
}
public String getSymbol()
{
return symbol;
}
public void setLetter(String letter)
{
this.letter = letter;
}
public void setSymbol(String symbol)
{
this.symbol = symbol;
}
public String toString()
{
return String.format("Letter: %s Symbol: %s", letter, symbol);
}
}
Figured it out, I needed to initialize the arrayList under the method initialzeSymbols. I knew it was something super simple I was overlooking
Related
Hi I am unable to know what I am doing wrong.
I have a string which is pass as an argument to a my class.
I have to split that string and assign the respective values to the member variable but it is not working properly.
Here is my class.
package virtusa;
public class pratice {
String getName;
Double getPrice;
int getQuantity;
String temp[] = null;
public pratice()
{
}
public pratice(String rawInput)
{
temp = rawInput.split("$$##",2);
getName = temp[0];
getPrice = Double.parseDouble(temp[1]);
getQuantity =Integer.parseInt( temp[2]);
}
public String getGetName() {
return getName;
}
public Double getGetPrice() {
return getPrice;
}
public int getGetQuantity() {
return getQuantity;
}
}
here is my main class
package virtusa;
import java.util.Scanner;
public class demo {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String stub = in.nextLine();
pratice temp = new pratice(stub);
System.out.println(temp.getName);
System.out.println(temp.getQuantity);
System.out.println(temp.getPrice);
}
}
My Input = apple$$##12.5$$##9
error i am having -
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
at virtusa.pratice.<init>(pratice.java:17)
at virtusa.demo.main(demo.java:12)
String::split take regex as a parameter, so the $ has special meaning. You will need to escape it with a \
One of problems in your code in not escaping special characters as some comments are mentioning. In my opinion clearest solution is to use Patter quote
rawInput.split(Pattern.quote("$$##"), 3);
Other problem is that you clearly need to get there elements since you are trying to get temp[0], temp[1] and temp[2]
So the final code should look something like this
String getName;
Double getPrice;
int getQuantity;
String temp[] = null;
public Practice() {
}
public Practice(final String rawInput) {
temp = rawInput.split(Pattern.quote("$$##"), 3);
getName = temp[0];
getPrice = Double.parseDouble(temp[1]);
getQuantity = Integer.parseInt(temp[2]);
}
public String getGetName() {
return getName;
}
public Double getGetPrice() {
return getPrice;
}
public int getGetQuantity() {
return getQuantity;
}
I am currently trying to complete this program and I'm having trouble with this error. I've done many things trying to fix it so I can compile it but it won't work. It seems that the "String alphabet" is getting the error. Can someone help me solve this please?
import java.util.Scanner;
public class Period
{
private static String phrase;
private static String alphabet;
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
String userInput;
int[] letter = new int [27];
int number = keyboard.nextInt();
System.out.println("Enter a sentence with a period at the end.");
userInput = keyboard.nextLine();
userInput.toLowerCase();
}
public void Sorter(String newPhrase)
{
phrase=newPhrase.substring(0,newPhrase.indexOf("."));
}
private int charToInt(char currentLetter)
{
int converted=(int)currentLetter-(int)'a';
return converted;
}
private void writeToArray()
{
char next;
for (int i=0;i<phrase.length();i++)
{
next=(char)phrase.charAt(i);
sort(next);
}
}
private String cutPhrase()
{
phrase=phrase.substring(0,phrase.indexOf("."));
return phrase;
}
private void sort(char toArray)
{
int placement=charToInt(toArray);
if (placement<0)
{
alphabet[26]=1;
}
else
{
// here is one spot that mainly the error pops up?
alphabet[placement]=alphabet[placement]+1;
}
}
public void entryPoint()
{
writeToArray();
displaySorted();
}
private void displaySorted()
{
for (int q=0; q<26;q++)
{
System.out.println("Number of " + (char)('a'+q) +"'s: "+alphabet[q]);
}
}
}
Your sort method is treating alphabet (the String) as an array. String is not a char[] but you can call String.toCharArray() like
private void sort(char toArray)
{
char[] alpha = alphabet.toLowerCase().toCharArray();
int placement=charToInt(toArray);
if (placement<0)
{
alpha[26]=1;
}
else
{
alpha[placement]=alpha[placement]+1;
}
alphabet = new String(alpha, "UTF-8");
}
But modifying a String is not possible, because they are immutable. For the same reason your raw call alphabet.toLowerCase() doesn't modify the alphabet in your other method.
The variable alphabet is defined as a String data type, but you need to define it as an array if you want to reference it using the bracket notation [] you have in your code. The error message is pretty clear in this case.
String[] example = new String[3];
example[0] = "Hello";
example[1] = "ETC...";
This is my code and it compiles fine but when I try to create a string it says
Error: cannot find symbol - variable racer
public class Word {
private String original;
public Word(String s) {
original = s;
}
public String reverse () {
String reverse= "";
int x = 1;
int length = original.length();
while (length - x >= 0) {
reverse = reverse + original.substring(length -x);
x++;
}
return reverse;
}
public boolean isPalindrome() {
if(original.equals(reverse()))
return true;
else
return false;
}
}
The stated problem is not in the code posted - my guess is irrelephant's comment is correct, ie change new Word(racer) --> new Word("racer").
But I offer this to eliminate any chance of any errors in your code by basically eliminating your code:
public class Word {
private String original;
public Word(String s) {
original = s;
}
public boolean isPalindrome()
return new StringBuilder(original).reverse().toString().equals(original);
}
}
or if you must expose a reverse() method:
public class Word {
private String original;
public Word(String s) {
original = s;
}
public String reverse () {
return new StringBuilder(original).reverse().toString();
}
public boolean isPalindrome()
return reverse().equals(original);
}
}
I don't see the variable racer anywhere, but since you're using reverse inside a method, I'd recommend making it
Most likely, racer was never defined
Either that or the method was called w/o quotes
isPalindrome(racer)//note the lack of quotes
change reverse() to this
private() String reverse () {
String reverse= "";
int x = 1;
int length = original.length();
while (length - x >= 0) {
reverse = reverse + original.substring(length -x);
x++;
}
return reverse;
Switch back to the Phrase class. Add a new method guessLetter that returns a boolean
and takes a char as an argument. This will be used to see if a player guesses a letter
correctly. This method should:
● Convert the char to a local variable of type Letter called guessed
● Return true if guessed is in letters, otherwise return false
public class Phrase {
private String phrase;
public Phrase(String phrase) {
phrase = phrase.toUpperCase();
for(char c : phrase.toCharArray()) {
letters.add(new Letter(c));
}
}
public String getPhrase() {
return phrase;
}
// public String phrase;
ArrayList<Letter> letters = new ArrayList<Letter>();
public ArrayList<Letter> getLetters() {
return letters;
}
public boolean guessLetter(char c) {
char c = new char(Letter);
c = guessed;
return false;
}
}
Thanks. I can't figure this one out.
package edu.htc.java1.phrasegame.model;
public class Letter {
private char letter;
private boolean isHidden;
public int getLetter() {
return letter;
}
public boolean isHidden() {
return isHidden;
}
public void unhide() {
isHidden = false;
}
public Letter(char letter) {
this.letter = letter;
if (String.valueOf(letter).matches("[A-Z]")) {
isHidden = true;
}
}
}
char c = new char(Letter); should probably be Letter guessedLetter = new Letter(c);
I'm not sure what c = guessed; is supposed to be doing.
Then you'll need to see if guessedLetter is in letters. How you go about that depends on the implementation of Letter.
EDIT: Now that I see the Letter implementation, the correct solution is to override equals()in Letter, probably comparing letter. You can get away without implementing hashCode() in this exercise, but you really should override it too. Then your guessLetter() method can be:
public boolean guessLetter(char c) {
return letters.contains(new Letter(c));
}
Or to meet the constraints in the problem:
public boolean guessLetter(char c) {
Letter guessed = new Letter(c);
return letters.contains(guessed);
}
My current assumption is this
public boolean guessLetter(char c)
{
// convert received character to letter
Letter letter = new Letter(c);
// loop through your list of letters
for(Letter l : letters)
{
// if list of letters contains same letter as the one you received then return true
if(l.getLetter() == letter.getLetter())
return true;
}
// we did not find the letter, so we return false
return false;
}
Please do make sure that you read this code and understand it. No one is going to cry if you fail the class because you chose to copy paste the answer.
public class Main {
public static void main(String[] args) {
java.util.ArrayList<StudentDataArray> info = new java.util.ArrayList<StudentDataArray>();
int amountOfPeople = KeyboardInput.promptForInt("Enter how many people you plan to enter into the list.");
for(int a=0;a<amountOfPeople;a++) {
try {
double[] grade = new double[5];
grade[0]=KeyboardInput.promptForDouble("Enter the First grade");
grade[1]=KeyboardInput.promptForDouble("Enter the Second grade");
grade[2]=KeyboardInput.promptForDouble("Enter the Third grade");
grade[3]=KeyboardInput.promptForDouble("Enter the Fourth grade");
grade[4]=KeyboardInput.promptForDouble("Enter the Fifth grade");
info.add(new StudentDataArray(KeyboardInput.promptForString("Enter the First Name"),KeyboardInput.promptForString("Enter the Last Name"),grade,KeyboardInput.promptForChar("Enter the Final Grade")));
}catch(IllegalArgumentException e){
System.out.println("Hello World :)");
}
}
for(int b=0;b<amountOfPeople;b++) {
System.out.printf("%-10s %-10s %-3f %-3s",info.get(b).getFN(),info.get(b).getLN(),info.get(b).getTS(),info.get(b).getFG());
}
}
}
public class StudentDataArray {
private String firstName;
private String lastName;
private double[] testScore;
private char finalGrade;
public StudentDataArray(String FN, String LN, double[] TS, char FG) {
firstName = FN;
lastName = LN;
testScore = TS;
finalGrade = FG;
}
public void setFN(String FN) {firstName = FN;};
public void setLN(String LN) {lastName = LN;}
public void setTS(double[] TS) {testScore = TS;}
public void setFG(char FG) {finalGrade = FG;}
public String getFN() {return firstName;};
public String getLN() {return lastName;}
public String getTS() {
for(int a=0;a<testScore.length;a++) {
return testScore[a]+" ";
}
return null;
}
public char getFG() {return finalGrade;}
}
Hey guys, this is my code for all to look at. What im trying to do is to return multiple doubles into one spot in the code. what it will look like is...
Ethan Michael 10 20 30 40 50 A
where this is all displayed in one statement
[10 20 30 40 50]
Since I am using a double[] i wasnt sure how to go about this.
Thanks guys!
you can use a for statement to concatenate all the info into one variable and then print it.
Here's how you do it in one neat line:
String s = Arrays.toString(testScores).replaceAll("[\\[\\],]", "");
You can use this expession (ie everything to the right of the equals dign) in-line wherever you need the string.
The key points of this are to use [Arrays.toString()][1], which produces a string like "[10, 20, 30, 40, 50]", then calling String.replaceAll() to strip out all the punctuation.
Lots of answers but none use a StringBuilder, which is recommended instead of concatenation in loops. It doesn't create a new String object in each iteration, so it is a lot easier on resources. As such:
public String getTS() {
StringBuilder sb = new StringBuilder();
for(int a=0;a<testScore.length;a++) {
sb.append(testScore[a]+" ");
}
return sb.toString();
}
It seems you would need something like this:
public String getTS() {
returnString := "";
for(int a=0;a<testScore.length;a++) {
returnString += testScore[a]+" ";
}
return returnString;
}
public String getTS() {
yourString:= "";
for(int a=0;a<testScore.length;a++) {
yourString+= testScore[a]+" ";
}
return ts;
}
I think the simplest thing would be to convert GetTS() to something like this:
public String getTS() {
String ts = "";
for(int a=0;a<testScore.length;a++) {
ts += testScore[a]+" ";
}
return ts;
}
Note that your format string in Main.java should then change to "%-10s %-10s %-3s %-3s".