Add an instance variable called currentPhrase to hold the current round’s Phrase
My error message is "Phrase cannot be resolved to a variable"
I feel like it has something to do with new String()? maybe.
Or could it be something like Phrase phrase = new Phrase();
package edu.htc.java1.phrasegame;
import edu.htc.java1.phrasegame.model.*;
public class PhraseGameController {
public void currentPhrase() {
String p = new String();
p = Phrase;
}
}
and
package edu.htc.java1.phrasegame.model;
import java.util.ArrayList;
public class Phrase {
public void setPhrase(String phrase) {
this.phrase = 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;
}
ArrayList<Letter> letters = new ArrayList<Letter>();
public ArrayList<Letter> getLetters() {
return letters;
}
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()) {
letter.unhide();
// return true;
}
}
// we did not find the letter, so we return false
return false;
}
}
An instance variable is a property of the class.
public class MyClass {
private static String classVariable;
private String instanceVariable;
public String instanceMethod () {
String localVariable = "hey";
}
public static String classMethod {
}
}
To instantiate a variable you have to use the new keyword:
SomeClass someInstance = new SomeClass();
Or if you use generics:
List<SomeType> myList = new ArrayList<SomeType>();
So in your case it should be:
public class PhraseGameController {
private Phrase p = new Phrase();
}
I think that first you will have to import this package:
edu.htc.java1.phrasegame.model;
into your PhraseGameController class. by adding this below the package declaration, but above the class declaration:
import edu.htc.java1.phrasegame.model.*;
Then you will make a new variable in that class called currentPhrase like so:
private Phrase currentPhrase;
What you do with it from there is sort of beyond the scope of your question.
Related
My code:
import java.util.Scanner;
public class PartyTest {
public static void main(String[] args) {
Party party = new Party();
String[] classNames = {"theif","warrior","wizard","steve","bard"};
Hero Carmilla = new Hero("Carmilla");
Hero Alucard = new Hero("Alucard");
Hero Steve = new Hero("steve");
Hero Sypha = new Hero("sypha");
System.out.println("The avaliable classes are:\n" );
for(int i = 0; i < classNames.length; i++) {
System.out.println(classNames[i]);
}
Scanner ask = new Scanner(System.in);
System.out.println("Enter the class for Carmilla\n");
String nameC = ask.next();
Boolean temp;
I was attempting to do a while loop but I was not sure what conditions to use
while(temp = true) {
if(nameC.equalsIgnoreCase("theif")) {
Carmilla.sethClass(nameC);
temp = false;;
break;
} else {
System.out.println("Invalid class try again");
}
}
System.out.println(Carmilla);
Hero class just sets the values for everything, I would use (depending on the name of the person I'm calling) `Carmilla.sethClass(nameC)', which just sets the name of the chosen class to the hero class.
I want to ask the user what class they would like to set for each person(they are the names stated with Hero in front of them)and if the user does not type one of the classNames value then they are told that its an invalid statement and to try again, which will then ask again what class they want for (in this example) Carmilla.
Here is one way to accomplish it.
The class with main method is below. A few notes about it. First, I made the Party class just an ArrayList of Hero objects, since I'm assuming that a party is just a collection of heroes. This makes asking names for each of the four heroes easier because we can loop through the party list.
Next, I moved the instantiation of the Hero objects into the initialization of the party so that the list already contains our Hero objects.
I utilized a for-each loop to check and assign classes to each Hero and a while loop to redirect the user back if they entered an invalid class. I check whether the class is valid using the boolean validClass. The final output of running this is shown at the very bottom.
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class PartyTest {
public static void main(String[] args) {
List<Hero> party = Arrays.asList(new Hero("Carmilla"),
new Hero("Alucard"),
new Hero("steve"),
new Hero("sypha"));
String[] classNames = { "theif", "warrior", "wizard", "steve", "bard" };
Scanner ask = new Scanner(System.in);
for (Hero hero : party) {
if (hero.getHclass()
.equals("Default")) {
boolean validClass = false;
while (!validClass) {
System.out.println("Enter the class for " + hero.getName());
String hClass = ask.nextLine();
for (String name : classNames) {
if (hClass.equals(name)) {
validClass = true;
}
}
if (validClass) {
hero.setHclass(hClass);
}
}
}
}
party.forEach(hero -> {
System.out.println(hero.getName() + " has class " + hero.getHclass());
});
}
}
The Hero class:
public class Hero {
private String name;
private String hclass = "Default";
public Hero(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHclass() {
return hclass;
}
public void setHclass(String hclass) {
this.hclass = hclass;
}
}
Output:
Use for-each loop to match the entered name against the classNames
Code:
import java.util.Scanner;
import java.io.*;
//Hero class replace with your class
class Hero{
String name="";
String className="";
public Hero(){}
public Hero(String name){
this.name=name;
}
public void sethClass(String className){
this.className=className;
}
#Override
public String toString(){
return "Name : "+name+" className : "+className;
}
}
public class PartyTest {
public static void main(String[] args) throws IOException{
//Party party = new Party();
String[] classNames = {"theif","warrior","wizard","steve","bard"};
Hero Carmilla = new Hero("Carmilla");
Hero Alucard = new Hero("Alucard");
Hero Steve = new Hero("steve");
Hero Sypha = new Hero("sypha");
System.out.println("The avaliable classes are:\n" );
for(int i = 0; i < classNames.length; i++) {
System.out.println(classNames[i]);
}
//Scanner ask = new Scanner(System.in);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the class for Carmilla\n");
boolean matched=false;
while(!matched) {
String nameC = br.readLine();
//Use for-each loop to match the entered name
for(String name : classNames){
if(nameC.equalsIgnoreCase(name)) {
Carmilla.sethClass(nameC);
matched=true;//Matched
break;
}
}
if(matched)break;
System.out.println("Invalid class try again\n");
}
System.out.println(Carmilla);
}
}
OUTPUT:
$ javac PartyTest.java && java PartyTest
The avaliable classes are:
theif
warrior
wizard
steve
bard
Enter the class for Carmilla
blaba
Invalid class try again
qwertr
Invalid class try again
Wizard
Name : Carmilla className : Wizard
I have a dog class with name, breed, age and weight.
I also have an arraylist which contains objects with these four attributes. Now I want to create an auction(which also have an own class) and I want to get the name from the dogArraylist and add it to a new Arraylist of auctions.
How can I do this? Is it possible?
private void newAuction(ArrayList<AuctionHouse> auctionHouse) {
boolean foundIt = false;
System.out.println("Enter the name of the dog> ");
String nameOfDog = input.nextLine();
for(int i = 0; i < dog.size(); i++) {
if(dog.get(i).getName().equalsIgnoreCase(nameOfDog)) {
foundIt = true;
if(foundIt) {
auctionHouse.add(i);
}
}
}
if(!foundIt) {
System.out.println("Error: no such dog ");
}
}
AuctionHouse class:
public class AuctionHouse {
private String auctionDog;
public AuctionHouse(String auctionDog) {
this.auctionDog = auctionDog;
}
public String getAuctionDog() {
return auctionDog;
}
public void setAuctionDog(String name) {
this.auctionDog = name;
}
public String toString() {
return String.format("%s", auctionDog);
}
}
Use enhanced for-loop instead and note: foundIt variable and if(foundIt) is redundant. Also newAuction() method should probably takes a list of dog as a parameter and return new list of auction. I guess it is more logical. Try:
private List<AuctionHouse> newAuction(List<Dog> dogs) {
List<AuctionHouse> auctionHouse = new ArrayList<>();
String nameOfDog = new Scanner(System.in).nextLine();
for (Dog d : dogs) {
if (d.getName().equalsIgnoreCase(nameOfDog)) {
auctionHouse.add(new AuctionHouse(d.getName()));
}
}
if (auctionHouse.isEmpty()) {
System.out.println("not found");
}
return auctionHouse;
}
I am trying to write a method that search an ArrayList of a particular word and then prints the location of all of the occurrences of the word.
Here is what I have, it works fine until I enter the word I want to search but then it prints nothing:
import java.util.ArrayList;
import java.util.Scanner;
public class W7E2 {
public static void main(String[]args) {
System.out.println("Please anter words: ");
Scanner sc = new Scanner(System.in);
String []w = sc.nextLine().split(" ");
ArrayList<Words> word = new ArrayList<Words>();
for(int i=0; i<w.length; i++) {
word.add(new Words(w[i]));
}
System.out.println(word);
System.out.println("Please enter the word you want to search: ");
String search = sc.nextLine();
for(Words ws: word) {
if(ws.equals(search)) {
System.out.println(ws.getLocation());
}
}
}
static class Words{
private String wor;
private static int number = -1;
public Words(String wor) {
this.wor = wor;
number++;
}
public int getLocation() {
return number;
}
public String toString() {
return wor;
}
}
}
In your if statement to see if the ArrayList contains the word you have:
if(ws.equals(search)) {
System.out.println(ws.getLocation());
}
But ws is a Word object and unless you override the equals() method, it will never equal the String object. You need to do something like:
if(ws.getwor().equals(search)) {
System.out.println(ws.getLocation());
}
This is assuming that you create a get method for wor.
Besides GBlodgett's answer,the number in class Word is static,so each Word instance will have a same number,you need to use a no-static variable to store the location
static class Words{
private String wor;
private static int number = -1;
private int location;
public Words(String wor) {
this.wor = wor;
number++;
location = number;
}
public int getLocation() {
return location;
}
public String toString() {
return wor;
}
}
Your code should be like this :
for(Words ws: word) {
if(ws.toString().equals(search)) { //to change
System.out.println(ws.getLocation());
}
}
ws is the object of Words class, you have to change it to toString()
What you should do is instead of
ws.equals(search)
you need to add
ws.toString().equals(search)
as you return the word from the
toString()
method in the Words Class.
So the code should look something like this,
for(Words ws: word) {
if(ws.toString().equals(search)) {
System.out.println(ws.getLocation());
}
}
I know why the compatibility error occurs, but I want to know how you can add a String to an ArrayList of type < Word > which is a class in the program.
In OO principles, a "WordContainer" is a type of "Container", and it contains "Words", which is what I'm trying to implement here, but how do you add a String to a WordContainer that has a list of words of type Word?
public class Word {
private String word;
public String getWord() {
return this.word;
}
public void setWord(String word) {
this.word = word;
}
public Word() {
this.word = "";
}
}
Container class which contains a list of words that are of type Word:
import java.util.*;
public class WordContainer {
private List < Word > words = new ArrayList < Word > ();
public List < Word > getWords() {
return this.words;
}
public void setWords(List < Word > words) {
this.words = words;
}
public void addWord(Word word) {
this.words.add(word);
}
public void display() {
words.forEach((word) - > {
System.out.println(word);
});
}
public WordContainer() {
}
}
Main class:
public static void main(String[] args) {
Scanner naughty = new Scanner(System.in);
WordContainer container1 = new WordContainer();
while (true) {
String nextLine = naughty.nextLine();
if (nextLine.equals("")) {
container1.display();
System.exit(0);
}
container1.addWord(nextLine); // this bit doesn't work :(
}
}
The method add from your WordContainer class is expecting a Word as argument not a String so what you should do is
in Main.java
container1.addWord(new Word(nextLine));
And define a constructor in your Word class that accepts a String
In Word.java
public Word(String word) {
this.word = word;
}
Your addWord() method expects a Word as parameter, but you were passing a String to it in this line:
container1.addWord(nextLine);
That's why you got the Exception: Incompatible types: String cannot be converted to Word
Solution:
It needs to be:
container1.addWord(new Word(nextLine));
And you need to implement a constructor with a String argument:
public Word(String word) {
this.word = word;
}
Alternative:
Or you can keep your actual main class code and implement a method that accespts a String and add a new Wordobject to your list:
public void addWord(String text) {
this.words.add(new Word(text));
}
I want to pass a series of the same string using LOOP from a method in Class A to method in Class B. Below is my newbie code but unable to deliver. Thanks!
import java.util.UUID;
public class ClassA {
public String ClassAMethod (String data){
String theString;
StringBuilder builder = new StringBuilder();
ClassA classA = new ClassA();
int k=0;
do {
k++;
String generated = classA.generateString(data);
builder.append(generated);
theString=builder.toString();theString+=theString;
return theString;
} while(k<5);
}
public String generateString(String genText ){
genText = (UUID.randomUUID().toString());
return genText;
}
}
public class ClassB {
private static String data;
public static void main(String arg[]) {
ClassA classA = new ClassA();
String sentString = classA.ClassAMethod(data);
System.out.println(sentString);
}
}
The main error is that you are returning from within your loop, what you want to do is returning after it.
Also as you are in classA you should not instantiate another classA object.
Try
public String ClassAMethod (){
StringBuilder builder = new StringBuilder();
int k=0;
do {
k++;
String generated = this.generateString();
builder.append(generated);
} while(k<5);
return builder.toString ();
}
Edit
As #Andreas metions above, generateString() does not need to be passed any arguments so change to
public String generateString(){
return (UUID.randomUUID().toString());
}