I'm having a problem! I'm making an app with multiple panels. I'm using Card Layout and I don't have this problem with changing to the other panels. I have a JButton (in a panel called optionsPanel) that should first change to the panel "panelCargando" (which has two JLabel, one with text and the other with a squared animated GIF (72x72)) and then looks after some info using Twitter4J that is showed in another JPanel called tweetsPanel. The problem is that when I press the button, it doesn't hide the other panels and make "panelCargando" visible, it keeps the options panel in the front and when it finishes looking for the info, it puts both panels together. Here's the code that I'm using in the ActionListener of the JButton:
btnNewButton_2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
mainPanel.setVisible(false);
optionsPanel.setVisible(false);
tweetsPanel.setVisible(false);
panelCargando.setVisible(true);
long lCursor = -1;
IDs friendsIDs;
try
{
friendsIDs = twitter.getFriendsIDs(twitter.getId(), lCursor);
System.out.println(twitter.showUser(twitter.getId()).getName());
do
{
for (long i : friendsIDs.getIDs())
{
if(textArea.getText().isEmpty())
{
textArea.setText(textArea.getText() + "ID de usuario: " + i +
"\nNombre de usuario: #" + twitter.showUser(i).getScreenName() +
"\nNombre: " + twitter.showUser(i).getName() +
"\nDescripción: " + twitter.showUser(i).getDescription() +
"\nImagen de perfil: " + twitter.showUser(i).getProfileImageURLHttps() +
"\nSigue a " + twitter.showUser(i).getFriendsCount() + " usuarios" +
"\nTiene " + twitter.showUser(i).getFollowersCount() + " seguidores\n");
}
else
{
textArea.setText(textArea.getText() + "\nID de usuario: " + i +
"\nNombre de usuario: #" + twitter.showUser(i).getScreenName() +
"\nNombre: " + twitter.showUser(i).getName() +
"\nDescripción: " + twitter.showUser(i).getDescription() +
"\nImagen de perfil: " + twitter.showUser(i).getProfileImageURLHttps() +
"\nSigue a " + twitter.showUser(i).getFriendsCount() + " usuarios" +
"\nTiene " + twitter.showUser(i).getFollowersCount() + " seguidores\n");
}
}
}
while(friendsIDs.hasNext());
frame.setTitle("Información sobre seguidores de " + twitter.showUser(twitter.getId()).getName() + " - BISmart");
panelCargando.setVisible(false);
tweetsPanel.setVisible(true);
tweetsPanel.setFocusable(true);
tweetsPanel.requestFocusInWindow();
So, finally I see the "tweetsPanel" panel with the textArea and the "panelCargando" in the front. In that code that I put here, I changed it and added "panelCargando.setVisible(false)", but this way I can't see it at all.
Can anyone help me with this? If it's not clear please let me know! Thank you all!
EDIT
Now the code is this one, but I keep having problems with the same. Even if I do "layout.show(frame.getContentPane(), "panelCargando")", the panel doesn't show. I added this:
layout = new CardLayout(0,0);
frame.getContentPane().setLayout(layout);
frame.getContentPane().add(splashPanel, "splashPanel");
frame.getContentPane().add(newTweetPanel, "newTweetPanel");
frame.getContentPane().add(mainPanel, "mainPanel");
frame.getContentPane().add(tweetsPanel, "tweetsPanel");
frame.getContentPane().add(optionsPanel,"optionsPanel");
frame.getContentPane().add(panelCargando, "panelCargando");
And the actionPerformed looks like this:
public void actionPerformed(ActionEvent arg0)
{
layout.show(frame.getContentPane(), "panelCargando");
long lCursor = -1;
IDs friendsIDs;
try
{
friendsIDs = twitter.getFriendsIDs(twitter.getId(), lCursor);
System.out.println(twitter.showUser(twitter.getId()).getName());
do
{
for (long i : friendsIDs.getIDs())
{
if(textArea.getText().isEmpty())
{
textArea.setText(textArea.getText() + "ID de usuario: " + i +
"\nNombre de usuario: #" + twitter.showUser(i).getScreenName() +
"\nNombre: " + twitter.showUser(i).getName() +
"\nDescripción: " + twitter.showUser(i).getDescription() +
"\nImagen de perfil: " + twitter.showUser(i).getProfileImageURLHttps() +
"\nSigue a " + twitter.showUser(i).getFriendsCount() + " usuarios" +
"\nTiene " + twitter.showUser(i).getFollowersCount() + " seguidores\n");
}
else
{
textArea.setText(textArea.getText() + "\nID de usuario: " + i +
"\nNombre de usuario: #" + twitter.showUser(i).getScreenName() +
"\nNombre: " + twitter.showUser(i).getName() +
"\nDescripción: " + twitter.showUser(i).getDescription() +
"\nImagen de perfil: " + twitter.showUser(i).getProfileImageURLHttps() +
"\nSigue a " + twitter.showUser(i).getFriendsCount() + " usuarios" +
"\nTiene " + twitter.showUser(i).getFollowersCount() + " seguidores\n");
}
}
}
while(friendsIDs.hasNext());
frame.setTitle("Información sobre seguidores de " + twitter.showUser(twitter.getId()).getName() + " - BISmart");
layout.show(frame.getContentPane(), "tweetsPanel");
}
Related
I am trying to drag & drop 2 elements into my workspace but they are dropped over each other, how can i specify the position of dropping the elements?
I am using dragAndDrop() function
Actions act=new Actions(driver);
act.dragAndDrop(From, To).build().perform();
enter image description here
Using dragAndDrop() method you can perform drag and drop operations on only one location at a time. it is usually used to perform operations on web element which is capable of dropping. please find the reference http://demoqa.com/droppable/ for various types of dropable elements.
To implement drag and drop operation -
Example:
WebElement From=driver.findElement(By.xpath( <<source xpath>> ));
WebElement To=driver.findElement(By.xpath( <<destination xpath>> ));
Actions actions=new Actions(driver);
actions.dragAndDrop(From, To).build().perform();
to drag and drop another element, you need to perform above all steps again.
Hope this helps :)
Try Using below code :
public static void dragAndDropViaJQueryHelper(WebDriver driver, String dragSourceJQuerySelector, String dropTargetJQuerySelector) {
String jqueryScript = "(function( jquery ) {\r\n" +
" jquery.fn.simulateDragDrop = function(options) {\r\n" +
" return this.each(function() {\r\n" +
" new jquery.simulateDragDrop(this, options);\r\n" +
" });\r\n" +
" };\r\n" +
" jquery.simulateDragDrop = function(elem, options) {\r\n" +
" this.options = options;\r\n" +
" this.simulateEvent(elem, options);\r\n" +
" };\r\n" +
" jquery.extend(jquery.simulateDragDrop.prototype, {\r\n" +
" simulateEvent: function(elem, options) {\r\n" +
" /*Simulating drag start*/\r\n" +
" var type = 'dragstart';\r\n" +
" var event = this.createEvent(type);\r\n" +
" this.dispatchEvent(elem, type, event);\r\n" +
"\r\n" +
" /*Simulating drop*/\r\n" +
" type = 'drop';\r\n" +
" var dropEvent = this.createEvent(type, {});\r\n" +
" dropEvent.dataTransfer = event.dataTransfer;\r\n" +
" this.dispatchEvent(jquery(options.dropTarget)[0], type, dropEvent);\r\n" +
"\r\n" +
" /*Simulating drag end*/\r\n" +
" type = 'dragend';\r\n" +
" var dragEndEvent = this.createEvent(type, {});\r\n" +
" dragEndEvent.dataTransfer = event.dataTransfer;\r\n" +
" this.dispatchEvent(elem, type, dragEndEvent);\r\n" +
" },\r\n" +
" createEvent: function(type) {\r\n" +
" var event = document.createEvent(\"CustomEvent\");\r\n" +
" event.initCustomEvent(type, true, true, null);\r\n" +
" event.dataTransfer = {\r\n" +
" data: {\r\n" +
" },\r\n" +
" setData: function(type, val){\r\n" +
" this.data[type] = val;\r\n" +
" },\r\n" +
" getData: function(type){\r\n" +
" return this.data[type];\r\n" +
" }\r\n" +
" };\r\n" +
" return event;\r\n" +
" },\r\n" +
" dispatchEvent: function(elem, type, event) {\r\n" +
" if(elem.dispatchEvent) {\r\n" +
" elem.dispatchEvent(event);\r\n" +
" }else if( elem.fireEvent ) {\r\n" +
" elem.fireEvent(\"on\"+type, event);\r\n" +
" }\r\n" +
" }\r\n" +
" });\r\n" +
"})(jQuery);";
((JavascriptExecutor) driver).executeScript(jqueryScript);
String dragAndDropScript = "jQuery('" + dragSourceJQuerySelector + "').simulateDragDrop({ dropTarget: '" + dropTargetJQuerySelector + "'});";
((JavascriptExecutor) driver).executeScript(dragAndDropScript);
}
Just pass css or xpath selectors in parameters.
Hope that helps you.
If that does not help you I can help you out with some other solutions also.
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.
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();
}
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++;