public Color determineColor(char guessLetter, int index) {
for (int i = 0; i < NUM_LETTERS; i++) {
if (guessLetter == secretWord.charAt(index)) {
return Color.GREEN;
}
else if(guessLetter == secretWord.charAt(i)) {
return Color.YELLOW;
}
else {
return Color.GRAY;
}
}
return Color;
}
I am trying to create a program similar to Wordle. This is one of the helper methods. This specific method loops through all the letters of an input and compares it to the letters of the "secret word." I am a newer coder and I am a bit stuck on how I am supposed to return the color based on the if-else statement within the loop. The method, as of now, is a syntax error. I know it has to do something with the variables scope. I tried defining "Color" as a global variable but the loop doesn't update variables outside of that loop of the same name so that is where I'm a bit stuck.
The comment of jhammon is very relevant.
Here is a piece of code that could help you.
public static Color determineColor(char guessLetter, int index) {
if (guessLetter == secretWord.charAt(index)) {
return Color.GREEN;
} else if (secretWord.contains(guessLetter+"")) {
return Color.YELLOW;
}
return Color.GRAY;
}
The +"" is not necessarily very clean but it allows you to cast the char in string.
I am practicing Objects & Constructors and ended up making this code, however when I run it, the String colorGenerated comes up as null, thus appearing as "The Color Generated was: null". I have tried to change and fix it but failed to do so. Thank you for reading.
public class Color{
int colorValue;
String colorGenerated1;
public Color(String colorGenerated){
System.out.println("The Color Generated was: " + colorGenerated);
}
public void randomizeColor(){
Random randomColor= new Random();
colorValue = randomColor.nextInt(3);
}
public int getColor(){
if(colorValue == 1){
colorGenerated1 = "Red";
} else if(colorValue == 2){
colorGenerated1 = "Blue";
} else if(colorValue == 3){
colorGenerated1 = "Yellow";
}
return colorValue;
}
public static void main(String[] args){
Color color = new Color("colorGenerated");
color.randomizeColor();
color.getColor();
}
}
You are printing the color generated before you set it with randomize color. And you should only get your Random once (instead of once per method invocation). I would do something like
public class Color {
private static Random random = new Random();
int colorValue = random.nextInt(3) + 1; // nextInt excludes 3 and includes 0
#Override
public String toString() {
if (colorValue == 1) {
return "Red";
} else if (colorValue == 2) {
return "Blue";
} else if (colorValue == 3) {
return "Yellow";
}
return "Unknown";
}
public static void main(String[] args) {
Color color = new Color();
System.out.println("The Color Generated was: " + color);
}
}
First you make an instance of the class Color. Actually you run the constructor. The parameter is a string. That is showing up.
After that you initialize colorgenerated. You must after color.getColor() show the colorgenerated, Because then it's actually initialized.
Please have a read . Your code is working fine as expected .
You added print statement in your constructor & you initializing an object very first .
Then you added code for randomize the color & there is no method for print the color .
So , you will get only null when you call the constructor .
I'm pretty new to java and I'm trying to create a program that quizzes users on the difference between 2 random frequencies. Everything works except that when I try to get the difference of 2 frequencies the answer is always 0. How do I get it to display the actual difference? Here is the class I wrote to create the tones ans compute the difference:
public class Quiz{
private PitchPlay one = new PitchPlay();
private PitchPlay two = new PitchPlay();
private int frequencyOne;
private int frequencyTwo;
private int dif = new Integer(Math.abs(frequencyTwo - frequencyOne));
public int run(){
frequencyOne = new Integer((int)(Math.random() * 5000 + 50));
frequencyTwo = new Integer((int)(Math.random() * 5000 + 50));
return this.dif;
}
public int freqDif(){
return this.dif;
}
public void playQuiz(){
one.play(one.note(frequencyOne, 2, 15));//note(frequency, duration, volume)
two.play(two.note(frequencyTwo, 2, 15));
}
}
And here is the class where the quiz class is used:
public class Action implements ActionListener{
Quiz one = new Quiz();
public void actionPerformed (ActionEvent e){
if(e.getSource() == playSoundButton)
{
if(answerResponse.getText().compareTo("Correct!") == 0 || answerResponse.getText().compareTo("Play and Listen...") == 0)
{
one.run();
one.playQuiz();
}
else
{
one.playQuiz();
}
}
if(e.getSource() == submitButton)
{
String responseText = new String(responseField.getText());
if(responseText !=null && !"".equals(responseText)){
try{
Integer responseNumber = Integer.parseInt(responseText);
if(responseNumber == one.freqDif())
{
answerResponse.setText("Correct!");
answerResponse.setVisible(true);
}
else
{
answerResponse.setText("Wrong Answer. The difference is " + one.freqDif() + " hertz.");
answerResponse.setVisible(true);
}
}catch(NumberFormatException f){
f.printStackTrace(System.out);
}
}
}
}
}
private int dif = new Integer(Math.abs(frequencyTwo - frequencyOne));
This is calculated when the variable is created, not when you use the variable. You need to do the calculation after assigning the variables.
There are several issues with your code:
As others have mentioned, the line
private int dif = new Integer(Math.abs(frequencyTwo - frequencyOne));
creates a variable and assigns a value calculated from two other variables. The values of the other variables at the time of creation are used. You need to recalculate every time the values of those two variables changes. This does not happen automatically for you.
new Integer(...) creates an Integer object. When you subsequently assign this object to an int variable, the value is taken out of the object. This adds some unnecessary memory and run-time over head to your code. Instead, you should assign directly to your variables. For example,
frequencyOne = (int)(Math.random() * 5000 + 50);
I am writing a program for my assignment, but for my defaultFan and toString methods I am getting an error stating "invalid method declaration; return type required. However I am unsure what how to resolve this. I tried putting void in front of the two methods and it worked but then I get errors stating I cannot assign variables to final variables slow, medium, and fast. I am not sure if this is correct. How would I fix this?
I also have a hard time using test programs. My professor wants us to use a test program that creates 2 fan objets; the first assign maximum speed, radius 10, color yellow and on status. and the second assign medium speed, radius 5 color blue and off status, and to display the fan objects by invoking their toString methods. Would it be possible for someone to explain how test programs work, and how I would go about creating one for this program. Here is my code:
public class fan {
private final int slow = 1;
private final int medium = 2;
private final int fast = 3;
private int speed;
private boolean fanOn;
private double radius;
private String color;
public void defaultFan( )
{
int speed = 1;
boolean fanOn = false;
double radius = 5;
String color = "blue";
}
public fan(final int slow, final int medium, final int fast, int
speed, boolean fanOn, double radius, String color) {
this.slow = slow;
this.medium = medium;
this.fast = fast;
this.speed = speed;
this.fanOn = fanOn;
this.radius = radius;
this.color = color;
}
public final int getSlow(){
return slow;
}
public final int getMedium() {
return medium;
}
public final int getFast() {
return fast;
}
public int getSpeed() {
return speed;
}
public boolean getfanOn() {
return fanOn;
}
public double getradius() {
return radius;
}
public String getcolor() {
return color;
}
public void setSlow(final int slow) {
this.slow = slow;
}
public void setMedium(final int medium) {
this.medium = medium;
}
public void setFast(final int fast) {
this.fast = fast;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public void setFanOn(boolean fanOn) {
this.fanOn = fanOn;
}
public void setRadius(double radius) {
this.radius = radius;
}
public void setColor(String color) {
this.color = color;
}
public void toString() {
if(fanOn = true ) {
System.out.println("The speed of the fan is " + speed + ", the color
of the the fan is " + color + ", and the radius of the fan is " +
radius + ".");
}
else {
System.out.println("The fan is off but the color is " + color +"
and the radius is " + radius + ".");
}
}
}
The variables slow, medium, and fast are final; you set each of them in their declaration, and you need not and cannot reinitialize them. You need to remove them from your constructor:
public fan(int speed, boolean fanOn, double radius, String color) {
this.speed = speed;
this.fanOn = fanOn;
this.radius = radius;
this.color = color;
}
Now, get rid of the setSlow and getSlow methods, etc. Keep the others.
You would want to invoke the constructor with code like:
fan myFan = new fan(/* medium */ 2, true, 10.0, "blue");
// But see 4 and 5 below.
The variables slow, medium, and fast are not tied to any specific instance of fan. So, you want to declare these like so:
public static final int SLOW = 1;
public static final int MEDIUM = 2;
public static final int FAST = 3;
// The constructor call becomes:
fan myFan = new fan(fan.MEDIUM, true, 10.0, "blue");
Typically, classes in Java have capitalized names. Call the class Fan. Replace all instances of fan with Fan.
The toString method should not be so chatty. Typically, people write these methods to help them debug their code, not to provide friendly access to users. Just report the values of the instance variables, which do not include SLOW, MEDIUM, or FAST. Don't use conditional logic.
Your toString method actually overrides the basic one in Object. Java will nag you until you add the #Override annotation. For fun, write your toString code, use it, and then comment the code out. See what happens to the output. You'll see why you need to override the method in Object.
#Override
public String toString() {
return "Fan" + "[speed: " + speed +
",on: " + fanOn +
",radius: " + radius +
",color: " + color + "]";
}
For future work, consider using Java's own Color class instead of a String. Also, consider writing a Java enum of your own named Speed instead of using those three constants.
Ask yourself what someone using the code would want the code to do, both if everything goes right, and if things go wrong or the class is used incorrectly. For example, perhaps the Fan class should obey these rules:
If I construct a Fan, and I ask it for its speed, I get the speed I put in.
Ditto for whether it's on, its radius, and its color.
If I take a Fan, and call a set method on one of its instance variables, and I then query the variable with a get method, I obtain the value I put in.
If I construct a Fan with a negative radius or with null for its color, the constructor fails, throwing an IllegalArgumentException. Your class may not have covered that yet.
Similarly, if I call myFan.setRadius(-10.0), the set method throws the same exception and myFan is left untouched.
If I try to set the speed of a Fan to something other than SLOW, MEDIUM, or FAST, this should fail too. Remember the advice about enums? This is a good reason why.
There are many frameworks to help with software testing; sadly, people don't do it enough in practice. But look up JUnit; your IDE almost certainly has ways to help you create JUnit tests.
Write your toString method like this
public String toString() {
String description = "";
if (fanOn = true) {
description += "The speed of the fan is " + speed
+ ", the color of the the fan is " + color
+ ", and the radius of the fan is " + radius + ".";
} else {
description += "The fan is off but the color is " + color
+ " and the radius is " + radius + ".";
}
return description;
}
I am not sure what you want to do with slow/medium/fast(seems a redundancy with speed). But if you want to modify it, don't declare it as final.
private int slow = 1;
private int medium = 2;
private int fast = 3;
You need a constructor for your test program. (by the way, you should name your class Fan)
public fan(int speed, double radius, String color, boolean fanOn ) {
this.speed = speed;
this.radius = radius;
this.color = color;
this.fanOn = fanOn;
}
Your test program should look like this.
public static void main(String args[]) {
fan fan1 = new fan(100, 100, "red", true);
fan fan2 = new fan(200, 200, "green", false);
}
public void toString()
This is causing the error. Knowingly or Unknowingly, you're trying to override the Object.toString() method, and that's the reason its showing that error. You either need to change the return type of your toString() method to String or change the method name to something else, to avoid conflict with Object.toString().
Apart from the major issue mentioned above, you've a few other bugs as well in your code, which could be resolved with a good IDE.
And for your final question: there are any number of tutorials on testing in Java. Search for JUnit. Here's an example tutorial.
I just started Computer Science last week, and we got a worksheet called Coins, in which I had to find out how many quarters, dimes, nickels and pennies there are in a set of coins. I am having a lot of trouble, and getting that error. Here's my code
package Coins;
public class Coins
{
private int change;
// two contructors
Change() //default constructor
{
change = 94;
}
Change( int c )
{
change = c;
}
// accessor method - change
public int getChange()
{
return Change;
}
// mutator method - change
public void setChange( int anotherChange)
{
change = anotherChange;
}
public void askUserForChange()
{
Scanner keyIn;
keyIn = new Scanner(System.in);
System.out.print("Please enter the amount of change: ");
String input = keyIn.nextLine();
int nChange = Integer.parseInt (input);
setChange(nChange);
// change = nChange
printChangex();
}
// action method - take accessor figure out coins -> output
// calculating the coins needed for the change
public void printChangeRange(int start, int end)
{
for(int c = start; c <= end; c++
{
setChange(c);
printChangex();
}
}
public void printChangex()
{
int c = change;
int quarter = c / 25;
System.out.println("quarter = " + quarter);
int a = c%25;
int dime = a / 10;
System.out.println("dime = " + dime);
int b = a%10;
int nickel = b / 5;
System.out.println("nickel = " + nickel);
int c = b%5;
int penny = c / 1;
System.out.println("penny = " + penny);
}
// instance variables - replace the example below with your own
private int x;
public Coins()
{
// initialise instance variables
x = 0;
}
public int sampleMethod(int y)
{
// put your code here
return x + y;
}
}
You have a class named Coins and are trying to give it a constructor named Change. The class and constructor must have the same name. Just pick one.
To elaborate on the error in your title, I assume that "Invalid Method Declaration, return type required" refers to the line with Change() //default constructor. Since this is in a class called Coins it is not a constructor as the comment claims. The Java compiler thinks that it is a method. All methods must have a return type, so the compiler complains.
The actual constructors are at the bottom of your code. It is standard practice to put constructors first, so I suggest that you put these poperly-named constructors at the beginning of your Coins class. You probably just need to remove the Change() constructors completely.
Also as a tip for asking questions here, it is extremel critical that you post the complete error message you are getting. My answer is based on some educated guesses and certainly don't solve all the problems in your code. Feel free to come back with more questions as you keep trying to fix your program.
This
// two contructors
Change() //default constructor
{
change = 94;
}
Change( int c )
{
change = c;
}
is unusual. You even have a constructor for the class Coins at the bottom of the file, so you would want to use that. Keep in mind that all Java classes have a constructor that are named the same as the class itself - even if it's the default constructor.
It's even more unusual that it has the magical value of 94 on instantiation...but in all seriousness, pick a class name and stick with it.
This
// accessor method - change
public int getChange()
{
return Change;
}
...is also odd. You may want to return the member variable change instead, so change that to a lower case C.