Basically, I have code that uses the same few lines in different scenarios, and it makes the code a bit messy (especially since I probably overcomplicated what I made, but that's another issue). What I wanted to do is store that piece of code as another function and calling it in the longer one. WHich should work as far as I know, except, the longer function has variables that aren't set in the shorter one, and if they were, I'm pretty sure it would change the final result of the function.
Here is the longer code:
public static void combat(Character a,Character b){
int battleturn = 1;
int maxTurns=20;
int draw1 = 0;
//stop after 20 turns, or stop when one player has 0 HP.
while (a.health > 0 && b.health > 0 && maxTurns > 0){
/* run a round of combat*/
if (b.health < 0.25 * b.maxHealth){
if (b.getFlee(a)){
System.out.println(">>>>>>>>>>The enemy has fled successfully<<<<<<<<<<");
break;
}else{
System.out.println("Battle turn " + battleturn + ", <attack> or <flee>?");
Scanner input = new
Scanner(System.in);
String move = input.next();
while(!move.equals("attack") && !move.equals("flee")){
System.out.println("Error: Please input <attack> or <flee>.");
input = new Scanner(System.in);
move = input.next();
}
if (move.equals("attack")){
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name + "." + " Enemy has "
+ b.getHealth() + "/" + b.getMaxHealth() + " health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}else if(move.equals("flee")){
if (a.getFlee(b)){
draw1++;
System.out.println(">>>>>>>>>>You have fled!<<<<<<<<<<");
break;
}else{
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name + "." + " Enemy has " +
b.getHealth() + "/" + b.getMaxHealth() + " health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}
}
}
}else{
System.out.println("Battle turn " + battleturn + ", <attack> or <flee>?");
Scanner input = new
Scanner(System.in);
String move = input.next();
while(!move.equals("attack") && !move.equals("flee")){
System.out.println("Error: Please input <attack> or <flee>.");
input = new Scanner(System.in);
move = input.next();
}
if (move.equals("attack")){
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name+ "." + " Enemy has " +
b.getHealth() + "/" + b.getMaxHealth() + "health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}else if(move.equals("flee")){
if (a.getFlee(b)){
draw1++;
System.out.println(">>>>>>>>>>You have fled!<<<<<<<<<<");
break;
}else{
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name+ "." + " Enemy has " +
b.getHealth() + "/" + b.getMaxHealth() + " health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}
}
}
}
}
As you can see there is a part of code that is repeated, and that is.
System.out.println("Battle turn " + battleturn + ", <attack> or <flee>?");
Scanner input = new
Scanner(System.in);
String move = input.next();
while(!move.equals("attack") && !move.equals("flee")){
System.out.println("Error: Please input <attack> or <flee>.");
input = new Scanner(System.in);
move = input.next();
}
if (move.equals("attack")){
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name + "." + " Enemy has "
+ b.getHealth() + "/" + b.getMaxHealth() + " health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}else if(move.equals("flee")){
if (a.getFlee(b)){
draw1++;
System.out.println(">>>>>>>>>>You have fled!<<<<<<<<<<");
break;
}else{
System.out.println(a.name + " dealt " + a.combatRound(b) + " damage to " + b.name + "." + " Enemy has " +
b.getHealth() + "/" + b.getMaxHealth() + " health.");
System.out.println(b.name + " dealt " + b.combatRound(a) + " damage to " + a.name + "." + " You have " +
a.getHealth() + "/" + a.getMaxHealth() + " health");
maxTurns--;
battleturn++;
}
}
}
It won't compile if I set that chunk of code as a method, because it doesn't have the variables battleturn, maxturns, draw1, but if I put them in there, the amount of battle turns messes up.
Any ideas?
Java applications should be modular: each class fulfilling its own function, each method generally performing a single operation.
In a method you can use either class variables or its own local variables.
If you need several methods work with the same data, it should either be part of a class (instance and/or static variables) or passed to each method as parameters.
Make sure that you do not define class variables in a method. This will create local variables that will shadow class variables.
This might help you accomplish what you're trying to do.
private static void reportDamage(Character a,
Character b) {
System.out.println(a.name + " dealt "
+ a.combatRound(b) + " damage to " + b.name
+ "." + " Enemy has " + b.getHealth() + "/"
+ b.getMaxHealth() + " health.");
}
I suggest changing your combat method like this.
int battleturn = 0;
int maxTurns = 20;
// stop after 20 turns, or stop when one player has 0
// HP.
Scanner input = new Scanner(System.in);
try {
while (a.health > 0 && b.health > 0
&& battleturn < maxturn) {
battleturn++;
/* run a round of combat */
if (b.getFlee(a)) {
System.out.println(">>>>>>>>>>"
+ "The enemy has fled successfully"
+ "<<<<<<<<<<");
break;
} else {
System.out.println("Battle turn "
+ battleturn + ", <attack> or <flee>?");
boolean isFlee = false;
boolean isAttack = false;
String move = input.next();
for (;;) {
isAttack = "attack".equalsIgnoreCase(move);
isFlee = "flee".equalsIgnoreCase(move);
if (isFlee || isAttack) {
break;
}
System.out.println("Error: "
+ "Please input <attack> or <flee>.");
move = input.next();
}
if (isAttack) {
reportDamage(a, b);
reportDamage(b, a);
} else { // isFlee
if (a.getFlee(b)) {
System.out.println(">>>>>>>>>>"
+ "You have fled successfully"
+ "<<<<<<<<<<");
break;
} else {
// b is fleeing.
// reportDamage(a, b);
reportDamage(b, a);
}
}
}
}
} finally {
input.close();
}
Related
I have since updated this code per suggestions for this forum. I am still confused as to how to get my .txt file selection to out print all instances of the name entered. my file in which all my .txt files are contained is named, namesbystate. To access this and all instances of the names entered are where I am getting issues. I am wondering if I replace myFile with namesbystate as a pathway extension or not?
package babynamestatesocial;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class BabyNameStateSocial {
private Scanner x;
public static void main(String[] args) throws FileNotFoundException {
// Scanner variable set up to intake user input for state selection and person's name
Scanner scan = new Scanner(System.in);
System.out.println("Available state files are: \n" +
"AK " + "AL " + "AR " + "AZ " + "CA " + "CO " + "\n" +
"CT " + "DC " + "DE " + "FL " + "GA " + "HI " + "\n" +
"IA " + "ID " + "IL " + "IN " + "KS " + "KY " + "\n" +
"LA " + "MA " + "MD " + "ME " + "MI " + "MN " + "\n" +
"MO " + "MS " + "MT " + "NC " + "ND " + "NE " + "\n" +
"NH " + "NJ " + "NM " + "NV " + "NY " + "OH " + "\n" +
"OK " + "OR " + "PA " + "RI " + "SC " + "SD " + "\n" +
"TN " + "TX " + "UT " + "VA " + "VT " + "WA " + "\n" +
"WI " + "WV " + "WY " + "\n");
System.out.print("Enter a state to read names from: " + "\n");
String filename = scan.nextLine() + ".txt";
System.out.println("Which name would you like to look up?");
String personName = scan.nextLine();
File myFile = new File(filename);
openFile(myFile,personName);
}
private static void openFile(File myFile, String personName){
try {
Scanner sc = new Scanner(myFile);
while (sc.hasNext()) {
// nextLine variable now has the line from the file in it that matches the name the person input
String nextLine = sc.nextLine();
if (nextLine.contains(personName)) {
}
}
} catch(FileNotFoundException e) {
System.out.print(e.getMessage());
}
}
}
Something like this will get you to where you want to be. I do not have the format of your state text files so I couldn't write the full program for you
(Edit - I just changed the code slightly. Instead of sc.next(), I should have written sc.nextLine(). The following program runs successfully with that edit):
package babynamestatesocial;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class BabyNameStateSocial {
private Scanner x;
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
System.out.println("Available state files are: \n" +
"AK " + "AL " + "AR " + "AZ " + "CA " + "CO " + "\n" +
"CT " + "DC " + "DE " + "FL " + "GA " + "HI " + "\n" +
"IA " + "ID " + "IL " + "IN " + "KS " + "KY " + "\n" +
"LA " + "MA " + "MD " + "ME " + "MI " + "MN " + "\n" +
"MO " + "MS " + "MT " + "NC " + "ND " + "NE " + "\n" +
"NH " + "NJ " + "NM " + "NV " + "NY " + "OH " + "\n" +
"OK " + "OR " + "PA " + "RI " + "SC " + "SD " + "\n" +
"TN " + "TX " + "UT " + "VA " + "VT " + "WA " + "\n" +
"WI " + "WV " + "WY " + "\n");
System.out.print("Enter a state to read names from: " + "\n");
String filename = scan.nextLine() + ".txt";
System.out.println("Which name would you like to look up?");
String personName = scan.nextLine();
File myFile = new File(filename);
openFile(myFile,personName);
}
private static void openFile(File myFile, String personName){
try {
Scanner sc = new Scanner(myFile);
while (sc.hasNext()) {
String nextLine = sc.nextLine();
if (nextLine.contains(personName)) {
//nextLine variable now has the line from the file in it that matches the name the person input so you need to parse that line and do something with it
}
}
} catch(Exception e) {
System.out.print(e.getMessage());
}
}
}
I have a segment of code that splits a string into tokens and prints them each out on a new line. I am having a hard time writing a code that determines if a word is a reserved word or not. I have to print "Reserved word is: " if the word is a java keyword, otherwise print "Current word is: ". Here is my code so far:
package projectweek3;
/**
*
* Name -
* Email Address -
* Date -
*
*/
public class Week3Project {
final static String program = "/*\n" +
" * To change this license header, choose License Headers in Project Properties.\n" +
" * To change this template file, choose Tools | Templates\n" +
" * and open the template in the editor.\n" +
" */\n" +
"package testapplication2;\n" +
"\n" +
"import java.util.Scanner;\n" +
"\n" +
"/**\n" +
" *\n" +
" * #author james\n" +
" */\n" +
"public class TestApplication2 {\n" +
"\n" +
" /**\n" +
" * #param args the command line arguments\n" +
" */\n" +
" public static void main(String[] args) {\n" +
" Scanner input = new Scanner(System.in);\n" +
" \n" +
" System.out.println(\"Enter integer #1\");\n" +
" int num1 = input.nextInt();\n" +
" \n" +
" System.out.println(\"Enter integer #2\");\n" +
" int num2 = input.nextInt();\n" +
" \n" +
" System.out.println(\"Enter integer #3\");\n" +
" int num3 = input.nextInt();\n" +
" \n" +
" System.out.println(\"Enter integer #4\");\n" +
" int num4 = input.nextInt();\n" +
" \n" +
" System.out.println(\"Enter integer #5\");\n" +
" int num5 = input.nextInt();\n" +
" \n" +
" //determine the sum\n" +
" int sum = num1 + num2 + num3 + num4 + num5;\n" +
" \n" +
" //this is helpful to make sure your sum is correct\n" +
" System.out.println(\"The sum is: \" + sum);\n" +
" \n" +
" //why doesn't this generate the sum correctly\n" +
" double average = sum / 5;\n" +
" \n" +
" //The average, lets hope its right...\n" +
" System.out.println(\"The average of your numbers is: \" + average);\n" +
" \n" +
" }\n" +
" \n" +
"}\n" +
"";
**public static void main(String[] args)
{
String str = program;
String s = "";
for (int i = 0; i < str.length(); i++) {
s += str.charAt(i) + "";
if (str.charAt(i) == ' ' || str.charAt(i) == '\t' || str.charAt(i) == '\n' || (str.charAt(i) == ' ' && str.charAt(i) == '\n')) {
String currentWord = s.toString();
String res = "int";
if (currentWord.equals(res)) {
System.out.println("Reserved word is: [" + currentWord + "]");
}
else {
System.out.println("Current word is: [" + currentWord + "]");
}
s = "";//Clear the string to get it ready to build next token.
}
}**
I would reconsider the way you're looping through the "program."
Instead of going through character by character, use the Java String.split() function.
String program = "int num1 = input.nextInt();\n";
String[] words = program.split("[\\n\\s\\t]");
for (String word : words) {
System.out.println(word);
}
Output:
int
num1
=
input.nextInt();
EDIT:
Since you can't use String.split(), your looping solution looks good. To check if the current word is reserved, try using Set.contains().
Set<String> reserved = new HashSet<>();
reserved.add("int");
// ...
if reserved.contains(word) {
System.out.println("Reserved word is: " + word);
} else {
System.out.println("Current word is: " + word);
}
That is, assuming you're allowed to use Set.
I need the currentStockLevel for another void Method in java, is there any possibility to get it?
I think no, because of void right?
public void receive (int currentStock)
{
String outLine;
if (currentStockLevel > 0)
outLine = productCode;
{
outLine = ". Current Stock: " + currentStockLevel;
outLine += " Current Stock changed from " + currentStockLevel;
currentStockLevel += currentStock;
outLine += " to " + currentStockLevel;
int storeCost = wholeSalePrice * currentStockLevel;
System.out.println (productCode + ":" + " Received " + currentStockLevel + "." + " Store Cost " + "$" + storeCost + "." + " New stock level: " + currentStockLevel);
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have read several posts suggesting to clear a JLabel (displayEntered) on a panel (display) with text by using the setText(" "). However, I have tried this and the outcome is it is just posting the array entered twice and does not clear the first set. I have an action shown below when a button is pressed both times; the first is to enter the data entered (I have the same code 4 times for the 4 different possible objects to enter but just put in the one since it's basically the same), which works fine and the second is to remove a specific one shown. My code is long, so am just putting that in. If someone wants something else please let me know. Thanks, I'd appreciate any input!
//adds the Herb data to the Array and list
enterHerbData.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
if(e.getActionCommand().equals("Enter")){
Name = NameTxt.getText();
Colors = ColorTxt.getText();
ID = (int) IDCmbo.getSelectedItem();
Flavor = FlavorTxt.getText();
if(((String) MedicinalCmbo.getSelectedItem()).equals("Yes"))
Medicinal = true;
else
Medicinal = false;
if(((String) SeasonalCmbo.getSelectedItem()).equals("Yes"))
Seasonal = true;
else
Seasonal = false;
plants[count] = new Herb(Name, ID, Colors, Flavor, Medicinal, Seasonal);
String displayArraytemp = " ";
if(plants[count] != null){
if(plants[count] instanceof Flower){
displayArraytemp = ((count + 1) + ": " + plants[count].getID() + ", " + plants[count].getName() + ", " + ((Flower)plants[count]).getColor() + ", " + ((Flower)plants[count]).getSmell() + ", Thorny: " + ((Flower)plants[count]).getThorns() + "\n");
}
else if(plants[count] instanceof Fungus){
displayArraytemp = ((count + 1) + ": " + plants[count].getID() + ", " + plants[count].getName() + ", " + ((Fungus)plants[count]).getColor() + ", Poisonous: " + ((Fungus)plants[count]).getPoisonous() + "\n");
}
else if(plants[count] instanceof Weed){
displayArraytemp = ((count + 1) + ": " + plants[count].getID() + ", " + plants[count].getName() + ", " + ((Weed)plants[count]).getColor() + ", Edible: " + ((Weed)plants[count]).getEdible() + ", Medicinal: " + ((Weed)plants[count]).getMedicinal() + ", Poisonous: " + ((Weed)plants[count]).getPoisonous() + "\n");
}
else if(plants[count] instanceof Herb){
displayArraytemp = ((count + 1) + ": " + plants[count].getID() + ", " + plants[count].getName() + ", " + ((Herb)plants[count]).getColor() + ", " + ((Herb)plants[count]).getFlavor() + ", Medicinal: " + ((Herb)plants[count]).getMedicinal() + ", Poisonous: " + ((Herb)plants[count]).getSeasonal() + "\n");
}
sb.append("<html>" + displayArraytemp).
append("<br> ");
displayArray = sb.toString();
}
displayEntered.setText(displayArray);
count++;
frameB.setVisible(false);
}
}
});
//removes the data to the Array and panel
ActionListener RemoveAction = new ActionListener(){
#Override
public void actionPerformed(ActionEvent RemoveAction){
if(RemoveAction.getActionCommand().equals("Enter")){
if((Btn1).isSelected()){
String displayArraytemp2 = " ";
if(count >= 1){
for(int n = 0; n < count; n++){
plants[n] = plants[n+1];
}
count--;
frameB.setVisible(false);
displayEntered.setOpaque(true);
for(int n = 0; n < 25; n++){
if(plants[n] != null){
if(plants[n] instanceof Flower){
displayArraytemp2 = ((n + 1) + ": " + plants[n].getID() + ", " + plants[n].getName() + ", " + ((Flower)plants[n]).getColor() + ", " + ((Flower)plants[n]).getSmell() + ", Thorny: " + ((Flower)plants[n]).getThorns() + "\n");
}
else if(plants[n] instanceof Fungus){
displayArraytemp2 = ((n + 1) + ": " + plants[n].getID() + ", " + plants[n].getName() + ", " + ((Fungus)plants[n]).getColor() + ", Poisonous: " + ((Fungus)plants[n]).getPoisonous() + "\n");
}
else if(plants[n] instanceof Weed){
displayArraytemp2 = ((n + 1) + ": " + plants[n].getID() + ", " + plants[n].getName() + ", " + ((Weed)plants[n]).getColor() + ", Edible: " + ((Weed)plants[n]).getEdible() + ", Medicinal: " + ((Weed)plants[n]).getMedicinal() + ", Poisonous: " + ((Weed)plants[n]).getPoisonous() + "\n");
}
else if(plants[n] instanceof Herb){
displayArraytemp2 = ((n + 1) + ": " + plants[n].getID() + ", " + plants[n].getName() + ", " + ((Herb)plants[n]).getColor() + ", " + ((Herb)plants[n]).getFlavor() + ", Medicinal: " + ((Herb)plants[n]).getMedicinal() + ", Poisonous: " + ((Herb)plants[n]).getSeasonal() + "\n");
}
sb.append("<html>" + displayArraytemp2).
append("<br> ");
displayArray = sb.toString();
}
}
}
displayEntered.setText(" ");
displayEntered.setText(displayArray);
}
}
}};
Your real problem is that you are re-using sb without clearing it.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
So I have written a JAVA code that is supposed to tell the user what color he will get if combining two other (from a list) random selected colors. Mind you I am very new to JAVA (have only programmed in Python before).
Code:
package ListOfWords;
public class testListWords {
public static void main (String[] args) {
String [] colors = {"red","green","gray","black","blue","yellow"};
int colorsLength = colors.length;
int rand1 = (int) (Math.random() * colorsLength);
int rand2 = (int) (Math.random() * colorsLength);
while(rand1==rand2){
int rand2 = (int) (Math.random() * colorsLength);
}
String phrase1 = colors[rand1];
String phrase2 = colors[rand2];
while(phrase1 = "green"){
if (phrase2 = "red") {
System.out.print("Combining" + " " + phrase1 + " " + "with" + " " + phrase2 + " " + "will give you the color Brown");
}
if (phrase2 = "gray") {
System.out.print("Combining" + " " + phrase1 + " " + "with" + " " + phrase2 + " " + "will give you the color Dark Green");
}
if (phrase2 = "black") {
System.out.print("Combining" + " " + phrase1 + " " + "with" + " " + phrase2 + " " + "will give you the color Black");
}
if (phrase2 = "blue") {
System.out.print("Combining" + " " + phrase1 + " " + "with" + " " + phrase2 + " " + "will give you the color Brown");
}
if (phrase2 = "yellow") {
System.out.print("Combining" + " " + phrase1 + " " + "with" + " " + phrase2 + " " + "will give you the color Brown");
}
}
while(phrase1 = "red"){
if (phrase2 = "green") {
System.out.print("Combining" + " " + phrase1 + " " + "with" + " " + phrase2 + " " + "will give you the color Brown");
}
if (phrase2 = "gray") {
System.out.print("Combining" + " " + phrase1 + " " + "with" + " " + phrase2 + " " + "will give you the color Dark Red");
}
if (phrase2 = "black") {
System.out.print("Combining" + " " + phrase1 + " " + "with" + " " + phrase2 + " " + "will give you the color Black");
}
if (phrase2 = "blue") {
System.out.print("Combining" + " " + phrase1 + " " + "with" + " " + phrase2 + " " + "will give you the color Brown");
}
if (phrase2 = "yellow") {
System.out.print("Combining" + " " + phrase1 + " " + "with" + " " + phrase2 + " " + "will give you the color Brown");
}
}
while(phrase1 = "gray"){
if (phrase2 = "red") {
System.out.print("Combining" + " " + phrase1 + " " + "with" + " " + phrase2 + " " + "will give you the color Dark red");
}
if (phrase2 = "green") {
System.out.print("Combining" + " " + phrase1 + " " + "with" + " " + phrase2 + " " + "will give you the color Dark Green");
}
if (phrase2 = "black") {
System.out.print("Combining" + " " + phrase1 + " " + "with" + " " + phrase2 + " " + "will give you the color Black");
}
if (phrase2 = "blue") {
System.out.print("Combining" + " " + phrase1 + " " + "with" + " " + phrase2 + " " + "will give you the Dark blue");
}
if (phrase2 = "yellow") {
System.out.print("Combining" + " " + phrase1 + " " + "with" + " " + phrase2 + " " + "will give you the color Green");
}
}
while(phrase1 = "black"){
if (phrase2 = "red") {
System.out.print("Combining" + " " + phrase1 + " " + "with" + " " + phrase2 + " " + "will give you the color Black");
}
if (phrase2 = "green") {
System.out.print("Combining" + " " + phrase1 + " " + "with" + " " + phrase2 + " " + "will give you the color Black");
}
if (phrase2 = "gray") {
System.out.print("Combining" + " " + phrase1 + " " + "with" + " " + phrase2 + " " + "will give you the color Black");
}
if (phrase2 = "blue") {
System.out.print("Combining" + " " + phrase1 + " " + "with" + " " + phrase2 + " " + "will give you the Black");
}
if (phrase2 = "yellow") {
System.out.print("Combining" + " " + phrase1 + " " + "with" + " " + phrase2 + " " + "will give you the color Black");
}
}
while(phrase1 = "yellow"){
if (phrase2 = "red") {
System.out.print("Combining" + " " + phrase1 + " " + "with" + " " + phrase2 + " " + "will give you the color Brown");
}
if (phrase2 = "green") {
System.out.print("Combining" + " " + phrase1 + " " + "with" + " " + phrase2 + " " + "will give you the color Blue");
}
if (phrase2 = "gray") {
System.out.print("Combining" + " " + phrase1 + " " + "with" + " " + phrase2 + " " + "will give you the color Green");
}
if (phrase2 = "blue") {
System.out.print("Combining" + " " + phrase1 + " " + "with" + " " + phrase2 + " " + "will give you the Green");
}
if (phrase2 = "black") {
System.out.print("Combining" + " " + phrase1 + " " + "with" + " " + phrase2 + " " + "will give you the color Black");
}
}
while(phrase1 = "Blue"){
if (phrase2 = "red") {
System.out.print("Combining" + " " + phrase1 + " " + "with" + " " + phrase2 + " " + "will give you the color Brown");
}
if (phrase2 = "green") {
System.out.print("Combining" + " " + phrase1 + " " + "with" + " " + phrase2 + " " + "will give you the color Brown");
}
if (phrase2 = "gray") {
System.out.print("Combining" + " " + phrase1 + " " + "with" + " " + phrase2 + " " + "will give you the Dark blue");
}
if (phrase2 = "yellow") {
System.out.print("Combining" + " " + phrase1 + " " + "with" + " " + phrase2 + " " + "will give you the Green");
}
if (phrase2 = "black") {
System.out.print("Combining" + " " + phrase1 + " " + "with" + " " + phrase2 + " " + "will give you the color Black");
}
}
}
}
So im getting an error message saying:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Duplicate local variable rand2
Type mismatch: cannot convert from String to Boolean.
And im not sure how to fix this - any help please.
Firstly = is for assignment, you must use == as a boolean operator.
Secondly, to compare strings in Java you need to call the equals() method on a string.
if ("red".equals(phrase2)) {
// logic here
}
Thirdly you assign rand2 two times. You must either use another variable for the second time or you must remove the int indication.
int rand2 = (int) (Math.random() * colorsLength);
while(rand1==rand2){
rand2 = (int) (Math.random() * colorsLength);
}
One problem you have is this:
while(rand1==rand2){
int rand2 = (int) (Math.random() * colorsLength);
}
You've already declared rand2, so don't do that again. You should change it to:
while(rand1==rand2){
rand2 = (int) (Math.random() * colorsLength);
}
Another thing is, you're mixing the assignment operator (=) with the equality operator (==). The former assigns a value to a variable, and the latter checks if variables are equal.
When you're trying to match variables, use ==.
Lastly, in Java, you can't use the equality operator to check strings - this will literally match one object to another and see if they are the same object. You have to use the equals method instead, like this:
while(phrase1.equals("green"))
Instead of this:
while(phrase1 = "green")
Or even while(phrase1 == "green") (which would work for integers/booleans/other types).
Alright. There are a number of problems with what you have written here. I will try to help you address some of them.
First off, as bas pointed out, in general, if you want to compare two values to see if they are equal, you use ==, not =. For example:
if ( x == y ) {
//DO STUFF
}
Second, bas also pointed this out, in Java you can't use == to compare strings. What you need to do is:
if ( string1.equals(string2) ) {
//DO STUFF
}
Third. "While". This one is going to cause lots of issues for you. While means to keep doing the code that follows, until its test is false. So, when you do this:
while ( myString.equals( "bananas" ) ) {
System.out.println ( "Lots of bananas." );
}
If the string is "bananas", then you'll get this:
Lots of bananas.
Lots of bananas.
Lots of bananas.
Lots of bananas.
Lots of bananas.
Lots of bananas.
Lots of bananas.
Lots of bananas.
....
Forever. What you actually want to use is another if. Actually, there is a convenient piece of logic here as well. Instead of a bunch of if's, you can modify the statement to use else ifs, since all of these options are mutually exclusive:
if ( string1.equals("yellow")) {
if ( string2.equals("green")) {
System.out.println("stuff");
}
else if ( string2.equals("blue")) {
System.out.println("more stuff");
}
}
else if ( string1.equals("green")) {
if ( string2.equals("blue")) {
System.out.println("lalala");
}
else if ( string2.equals("yellow")) {
System.out.println("more stuff");
}
}
There are also some much better ways of writing this program that involve a lot less code duplication and ultimately simpler logic, but to avoid overloading you, this is probably sufficient for now.
For comparing strings in Java you will have to use equals() method use "red".equals(phrase2) or "red".equalsIgnoreCase(phrase2)
== operator in Java is used for checking equality and = is an assignment operator. But Strings in Java are Objects of String.class so == does reference check rather than value check.
So to compare two objects in Java you use equals() method.
one syntax error here:
int rand1 = (int) (Math.random() * colorsLength);
int rand2 = (int) (Math.random() * colorsLength);
while(rand1==rand2){
//int rand2 = (int) (Math.random() * colorsLength); - wrong
//rand2 is already defined, you can write only
rand2 = (int) (Math.random() * colorsLength);
}
also, if you want 2 different random numbers, you can:
int rand1 = (int) (Math.random() * colorsLength);
int rand2 = (int) (Math.random() * (colorsLength-1));
if(rand2 >= rand1) rand2++;