简体   繁体   中英

Java - toggle between two strings

I have 2 strings with value "good" and "bad"

I send one of this(say "good") to a method as a parameter and when the same method is called again in the same class, I want to use the second variable with value ("bad") to be passed as a parameter.

I could not find a better solution.

I had alternate way of doing this is to write a small function to pick this variable randomly.

    public static Set<String> selectRandomString() {
    Random r = new Random();
    int firstR = r.nextInt((2 - 0) + 1) + 0;

    List<String> animals = Arrays.asList( new String[] { "good", "bad"});

    Set<String> returnAnimals = new HashSet<String>();

    if (firstR > 0) {

            int animalCount = r.nextInt((firstR - 0) + 1) + 0;
            String temp = animals.get(animalCount);
            returnAnimals.add(temp);
        }

    return returnAnimals;
}
public class ToggleStrings {

   static Random r = new Random();

   public static String toggleString() {
      return r.nextBoolean() ? "good" : "bad";
   }

   public static void main( String[] args ) {
      System.out.println( toggleString());
      System.out.println( toggleString());
      System.out.println( toggleString());
      System.out.println( toggleString());
      System.out.println( toggleString());
      System.out.println( toggleString());
      System.out.println( toggleString());
      System.out.println( toggleString());
      System.out.println( toggleString());
      System.out.println( toggleString());
   }
}

Execution trace:

bad
bad
good
bad
bad
bad
bad
good
bad
good

You could just use a variable to "remember" the previous answer. This code will always alternate between "good" and "bad".

class Utils {
    static boolean toggle;
    public static String getString() {
        toggle = !toggle;
        if (toggle)
            return "good";
        else
            return "bad";
    }
}

I have another tricky way as following:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class RandomList {
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>(){{
            this.add("good");
            this.add("bad");
        }};
        Collections.shuffle(list);
        System.out.println(list.get(0));
        Collections.shuffle(list);
        System.out.println(list.get(0));
        Collections.shuffle(list);
        System.out.println(list.get(0));
    }
}

the output:

bad
good
good

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM