I'm a bit confused about what to do with this problem. I have to take a Stack and flip it, once flipped the elements in the stack have to also 'flip'. for example every string that reads 'blue' must now read 'red', every string that reads 'White' should be 'black' etc.
I've written a method to flip the stack, but writing a method to replace all instances of the given variables with new variables isn't working. This is what i have so far. I've tried two approaches and i'm still not getting the result i want. Here is what I have:
//here color is the name of my stack. I tried to convert the stack to an array
Object[] arr = color.toArray();
for (int i =0;i<arr.length;i++){
/*
* replace instances of "blue" in the string [] with red
*/
arr [i] = ((String) arr[i]).replaceAll("Blue", "Red");
arr [i] = ((String) arr[i]).replaceAll("Red", "Blue");
arr [i] = ((String) arr[i]).replaceAll("Green", "Yellow");
arr [i] = ((String) arr[i]).replaceAll("Yellow", "Green");
System.out.print(arr[i]);
}
another method i tried:
import java.util.*;
public class colors{
/*
* method to swap the colors
* color black gets changed to white, blue changes to red etc...
* method would have to be implemented on a stack to change all the elm of the stack to the opposite
* then the stack gets printed out and can be changed in the flip part of the main method
*/
private static Stack<String> opposite(Stack<String>color){
// method takes stack of strings. if 'red' then change to 'blue'
/*
* the stack gets put into this method
* if the stack (strings) has these values then they are replaced with my values
*
* can't return String values if the input is Stack<String>
*/
String b = "blue";
String r = "red";
String g = "green";
String y = "yellow";
b.replace("blue", "red");
r.replace("red", "blue");
g.replace("green","yellow");
y.replace("yellow","green");
return color; // return type hase to be same as input type so change return type to match Stack<String>
/*
* if return type is same it can't return color....
try using switch statement to
*/
}
public static void main(String[]args){
Stack<String> way = new Stack<>();
color.push("red");
color.push("blue");
System.out.println(way);
System.out.println(opposite(way));
}
}
I wanted the method to intake a stack and output a stack that has the elements changed