Simpe Objects & Classes issue - java

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 .

Related

How do I return a color method while using loops in java?

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'm trying to add a value to an int in one class and then use it in another, Java

So as the title says im struggling to add a value to an integer and then pass it to another class that uses it, then this class will pass it to the next and then that one will pass it over to the main class. Its an integer that changes the stat template of the enemies in my small game im writing.
I have tried to make constructors in two of my classes as I thought that was the problem, Ive tried to see if they work by passing some messages in them.
The problem seems to be that when I save something in the "private int l" It dosnt actually change the value of that int and I cant figure out why that is.
Here is my code, its probably not very pretty so if you have any suggestions to structure changes that I might wanna do please feel free too let me know!
Thanks in advance!
import java.util.Scanner;
public class Stor {
public static void main(String[] args) {
Scanner user_Input = new Scanner(System.in);
Menu user = new Menu();
EnemyValue monster = new EnemyValue();
user.namn();
user.AnvNamn = user_Input.next();
user.introMeny();
user.difficulty();
System.out.println(“Your enemy has " + monster.HP + " HP and " +
monster.DMG + " Damage" );
user_Input.close();
}
}
class Menu {
Scanner user_Input = new Scanner(System.in);
String AnvNamn;
String difficultySvar;
String nivåSvar;
int svar;
private int i; /
private int l;
public int getL() {
return l;
}
boolean difficultyLoop = true;
boolean felLoop = true;
void introMeny() {
System.out.println(“Welcome " + AnvNamn + "!");
}
void namn() {
System.out.print(“Pick a name: “);
}
void difficulty() {
do {
System.out.println("\nWhat level do you want ?\n1 = Easy.\n2 =
Medium.\n3 = Hard.”);
svar = user_Input.nextInt();
if (svar == 1) {
System.out.println(“Your not very brave are you ? Are you sure
this is how you wanna play ?”);
difficultySvar = user_Input.next();
if (difficultySvar.equalsIgnoreCase(“Yes”)) {
difficultyLoop = false;
l = 1;
} // If ja 1
else if (difficultySvar.equalsIgnoreCase(“Nej”)) {
System.out.println(“Ahh good! I figuerd you would change
your mind.”);
}
else
System.out.println(“I don’t understand….”);
} // if 1
else if (svar == 2) {
System.out.println(“Not to hard or to easy, a good choice! But
maybe you want to go for something harder ? Or maybe easier ?");
difficultySvar = user_Input.next();
if (difficultySvar.equalsIgnoreCase(“Yes”)) {
difficultyLoop = false;
l = 2;
} // if ja 2
else if (difficultySvar.equalsIgnoreCase(“No”)) {
System.out.println(“I sure hope you don’t pick the easy
way…..”);
}
else
System.out.println("I don’t understand….");
} // Else if 2
else if (svar == 3) {
System.out.println(“Damn! We have a big player here! Are you
sure you can handle this ?");
difficultySvar = user_Input.next();
if (difficultySvar.equalsIgnoreCase(“Yes”)) {
difficultyLoop = false;
l = 3;
} // If ja 3
else if (difficultySvar.equalsIgnoreCase(“No”)) {
System.out.println(“Wuss.”);
}
else
System.out.println(“I don’t understand….”);
} // Else if 3
else {
if (i == 0) {
System.out.println(“Ha you thought you could fool the system?!
The system fools you!”);
System.out.println(“Nah but seriously, you can only choose
between 1-3…..“);
i++;
} // if i 0
else if (i == 1) {
System.out.println(“Alright I get that its hard but
COMEON!”);
i++;
} // if i 1
else if (i == 2) {
System.out.println(“OKEY YOU GET ONE LAST CHANCE!!”);
i++;
} // if i 2
else if (i == 3) {
System.out.println(“Alright thats it…. GET OUT!”);
System.exit(0);
} // if i 3
} // Else
} // do while loop
while(difficultyLoop == true);
} //Difficulty metod.
} // Menu class.
class Nivå {
//Menu level = new Menu();
//int levelChoice = level.getL();
int levelChoice;
private int enemyLife;
public int getenemyLife() {
return enemyLife;
}
private int enemyDMG;
public int getenemyDMG() {
return enemyDMG;
}
Nivå(){
Menu level = new Menu();
levelChoice = level.getL();
System.out.println("testNivå");
}
void fiendeLiv() {
if (levelChoice == 1)
enemyLife = 100;
else if (levelChoice == 2)
enemyLife = 150;
else if (levelChoice == 3)
enemyLife = 200;
} // fiendeliv method
void fiendeDMG() {
if (levelChoice == 1)
enemyDMG = 5;
else if (levelChoice == 2)
enemyDMG = 10;
else if (levelChoice == 3)
enemyDMG = 15;
} // fiendeDMG method
} // Nivå class
class EnemyValue {
public int HP;
public int DMG;
int maxLife;
int maxDMG;
EnemyValue(){
Nivå stats = new Nivå();
maxLife = stats.getenemyLife();
maxDMG = stats.getenemyDMG();
System.out.println("TestEnemyValue");
}
void rank1() {
HP = maxLife;
DMG = maxDMG;
} // rank1 easy method
} // EnemyValue class
You say that when you save something in l (poor choice of a variable name, by the way) it does not save the value. How do you know that? Where in the code do you check whether the value is saved?
In the constructor for class Nivå you create a new Menu and then call getL() on that menu before you have ever set the value of that variable.
Everything runs at the start of your public static void main(String[] args) method, and nothing will run if its instructions are not in there. For example, you are not actually creating any Niva objects in the main method, so the Niva constructor is never called. That is one issue. The other is your constructors are creating new instances of objects and then getting their values; this gives you empty values from a brand new object:
Nivå(){
Menu level = new Menu(); // Don't do this. This is an empty menu
levelChoice = level.getL(); // Getting the blank L value from the empty menu
System.out.println("testNivå");
}
Instead, you need to define constructors with parameters to pass the values into the class like this:
Nivå(int level){ // add an int parameter
levelChoice = level; // Direct assignment
fiendeDMG(); // Call this in the constructor to set up your last value
System.out.println("testNivå");
}
Then, when you call the constructor (which you must if you want it to exist), include the parameter. Inside the Stor class:
public static void main(String[] args) {
Scanner user_Input = new Scanner(System.in);
Menu user = new Menu();
user.namn();
user.AnvNamn = user_Input.next();
user.introMeny();
user.difficulty(); // Run this before creating the other classes; you need the l value
Nivå niva = new Nivå(user.getL()); // Creates new Niva while also assigning l to the levelChoice and then getting DMG
EnemyValue monster = new EnemyValue(/*add some parameters for life and dmg*/);
}
There is still more that needs to be done, like modifying the constructor of the EnemyLevel. Just remember that methods are never called unless they connect to something running from main and use parameters in functions and constructors to pass on data to other objects. Hope this helps.

System.out.println doesn't show text in console (IntelliJ)

I am writing a program which part is presented below:
public class Portal {
private String name;
private int[] positions; // positions of "ship"
private static int moves = 0; // moves made by player to sink a ship
public static int shot; // the value of position given by player
private int hits = 0; // number of hits
private int maxSize = 4; // max size of ship (the size will be randomized)
int first; // position of 1st ship block
int size; // real size of ship (randomized in setPortal method)
public void checkIfHit(){
for (int i : positions){
if (i == shot){
System.out.println("Hit confirmed");
hits++;
} else if (hits == positions.length){
System.out.println("Sunk");
} else {
System.out.println("Missed it");
}
}
moves++;
}
public void setPortal(){
size = 1 + (int)Math.random()*maxSize;
for (int i = 0; i < size - 1; i++){
if (i == 0){
positions[i]= 1 + (int)Math.random()*positions.length;
first = positions[i];
System.out.println(positions[i]);
continue;
}
positions[i]= first + 1;
System.out.println(positions[i]);
}
}
}
public class Main{
public static void main(String[] args){
// write your code here
Portal p1 = new Portal();
p1.setPortal();
}
}
code is split in two Java .class files.
The problem I'm dealing with is that using p1.setPortal(); doesn't show up text in IntelliJ console. The program works though and returns 0.
I don't have such problem in another program when I've put System.out.println in method other than main (also in separate class file).
What may be the cause of such issue?
It should properly throw an exception, because you forgot to initialize the integer array.
Have a look at this thread: Do we need to initialize an array in Java?
The Java's default value is null for an integer array. So your for wont even loop trough. The only thing that wonders me is why there is no exception..

Java - I need to print this string of characters to a string I can use out of loop

I have been buried in this assignment for 2 days chasing down rabbit holes for possible solutions. I am beginner Java, so I am sure this shouldn't be as difficult as I am making it.
I trying to program the infamous Java Bean Machine... My professor want the Class Path to return a String Variable that only holds "R" "L" . to represent the path of the dropped ball.
Each ball should have its own Path... I can get the path... but I can not get the path to print in a string outside of the for/if statement.
Here are his instructions... in case you can see if I am interpreting this incorrectly.
Please help!! Thank you in advance for sifting through this....
my code so far ******** i have updated the code to reflect the suggestions.. Thank you... ***************** New problem is it repeats the series of letters in a line... I only need a string of 6 char ....(LRLLRL)
public class Path {
StringBuilder myPath;
public Path() {
myPath = new StringBuilder();
}
void moveRight() {
myPath.append("R");
}
void moveLeft() {
myPath.append("L");
}
public void fallLevels(int levels) {
levels = 6;
for (int i = 0; i < (levels); i++) {
if (Math.random() < 0.5) {
this.moveRight();
} else {
this.moveLeft();
}
}
}
public String getPath() {
System.out.print(myPath.toString());
return myPath.toString();
}
}
}
******Thank you all.. this class now returns the correct string for one ball...***************
here is my code so far for multiple balls... I can get a long continuous string of 6 character sequences... I need each sequence to be a searchable string...I am not sure if I need to alter the Path class or if its something in the simulateGame() method. I think I can take it after this hump... Thank you again....
public class BeanMachine {
int numberOfLevels;
int[] ballsInBins;
Path thePath = new Path();
public BeanMachine(int numberOfLevels) {
this.numberOfLevels = 6;
ballsInBins = new int[this.numberOfLevels + 1];
// this.numberOfLevels +
}
public void simulateGame(int number) {
//looping through each ball
for (int i = 0; i < numberOfLevels -1; i++) {
thePath.fallLevels(0);
}
thePath.getPath().toString();
}
*** this isn't the entire code for this class... I have to get this method correct to continue....
Problem with your code:
if (Math.random() < 0.5) {
**loop = this.myPath = "R";**
} else {
**loop = this.myPath ="L";**
}
Change this to:
if (Math.random() < 0.5) {
**loop = this.myPath + "R";**
} else {
**loop = this.myPath + "L";**
}
Just added ** to highlight where there is wrong in your code

Issue creating a new object in Java and passing it to setMethod

I'm trying to create a new object using the parameters passed in, then use that new object to place in the setCarColor method listed below. But my setCarColor in my constructor is giving an error for my clv variable. It says "Can not find symbol". The clv is my variable from the CarColor class. I'm not sure if it is because the parameters being passed in(rdIn, grnIn, bluIn)are integers or what? Does anyone have any ideas please?
Best Regards,
public abstract class Vehicle
{
private String shapeId;
CarColor carColor;//CarColor data member from the ColorValue.java class
public Shape(String bodyid, int rd, int grn, int ble)
{
CarColor clv = new CarColor(rdIn, grnIn, bluIn);
setCarColor(clv(rd, grn, ble));// <---error here
}
private CarColor getCarColor()
{
return carColor;
}
private void setCarColor(int redIn, int blueIn, int greenIn)
{
if (redIn == 0 || blueIn == 0 || greenIn == 0 )
{
System.out.println("The value entered in is null. Please try again ");
System.exit(-1);
}
}
This line is nearly fine:
ColorValue clv = new ColorValue(rdIn, grnIn, bluIn);
... although it doesn't populate the colorValue field, which is what you might have been expecting, and you don't actually have rdIn, grnIn and bluIn variables. Did you mean rd, grn, ble? (It helps if you don't contract names like this, by the way.)
But this line is broken in two ways:
setColorValue(clv(rd, grn, ble));
Firstly, it's trying to call a method called clv. You don't have such a method. You've got a variable called clv, but you don't "call" a variable.
The second problem is that if you really meant this:
setColorValue(clv);
then you'd be using incorrect arguments - setColorValue doesn't have one parameter of type ColorValue, it has three parameters, all ints.
Unfortunately it's not clear what you're attempting to do, so it's hard to advise you. Perhaps you mean this:
public abstract class Geometry
{
private String shapeId;
private ColorValue colorValue;
public Shape(String shapeId, int red, int green, int blue)
{
this.shapeId = shapeId;
setColorValue(red, green, blue);
}
public ColorValue getColorValue()
{
return colorValue;
}
// Note the consistent order of the parameters - always red, green, blue.
public void setColorValue(int red, int green, blue)
{
// Don't use System.exit() in the middle of a method! An exception
// is the idiomatic way of reporting bad arguments.
if (red == 0 || blue == 0 || green == 0)
{
throw new IllegalArgumentException("red green and blue must be non-zero");
}
colorValue = new ColorValue(red, green, blue);
}
}
Your declared setColorValue() method takes 3 int parameters, but you are trying to call it by (presumably) passing a single ColorValue object, created by a method called clv that doesn't exist. Hence the signatures don't match and the symbol is not found.
This should fix the error:
public abstract class Geometry
{
private String shapeId;
ColorValue colorValue;//ColorValue data member from the ColorValue.java class
public Shape(String bodyid, int rd, int grn, int ble)
{
shapeId = bodyid;
setColorValue(rd, grn, ble);
}
private ColorValue getColorValue()
{
return colorValue;
}
private void setColorValue(int redIn, int blueIn, int greenIn)
{
if(redIn == 0 || blueIn == 0 || greenIn == 0 )
{
System.out.println("The value entered in is null. Please try again ");
System.exit(0);
}
colorValue = new ColorValue(redIn, greenIn, blueIn);
}
}
Your setColorValue method takes 3 ints yet your trying to pass it a ColorValue
setColorValue(int redIn, int blueIn, int greenIn)
to use this method you need to do something like
public Shape(String bodyid, int rd, int grn, int ble)
{
setColorValue(rd, grn, ble);
}
or if you want to pass it a ColorValue object
public Shape(String bodyid, int rd, int grn, int ble)
{
ColorValue clv = new ColorValue(rd, grn, ble);
setColorValue(clv);
}
private void setColorValue(ColorValue clv)
{
// do stuff
}
or you can do this which will create the object and pass it to the method in the one step:
public Shape(String bodyid, int rd, int grn, int ble)
{
setColorValue(new ColorValue(rd, grn, ble));
}
At the moment you seem to have a combination of lots of these.

Categories

Resources