簡體   English   中英

如何測試Java方法中返回的字符串

[英]How to test a string returned in a method Java

好的,所以我想弄清楚如何測試從 Java 中的方法返回的字符串。 我知道我無法測試字符串,但對如何更改返回值以能夠將其測試為字符或其他內容感到困惑。

這就是問題所在,我似乎無法過去。

if(flip().equals("Heads")) {
            headsCount++;
            }

完整代碼

public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("How many times should I flip the coin? ");
        int headsCount = 0;
        int flips = input.nextInt();
        for(flips = flips; flips >= 1; flips--) {
            flip();
            }

        if(flip().equals("Heads")) {
            headsCount++;
            }

        System.out.println(headsCount);

    }

    public static int flip() {`enter code here`
        int rand = (int) (Math.random() * 2);
        if (rand == 1) {
            System.out.println("Heads");
            }
        if (rand != 1){
            System.out.println("tails");
            }
        return rand;
    }

flip方法更改為:

    public static String flip() {
        int rand = (int) (Math.random() * 2);
        String result = null;
        if (rand == 1) {
            System.out.println("Heads");
            result = "Heads";
        }
        if (rand != 1){
            System.out.println("tails");
            result = "tails";
        }
        return result;
    }

並且,將for循環更改for以下內容:

for(flips = flips; flips >= 1; flips--) {
    String result = flip();
    if("Heads".equals(result)) {
            headsCount++;
      }
}
public static void main(String[] args) {
    System.out.println("How many times should I flip the coin? ");
    Scanner input = new Scanner(System.in);
    int headsCount = 0;
    int flips = input.nextInt();
    for(int flips = flips; flips >= 1; flips--) {
        flip();
        }

    if(flip() == true) {
        headsCount++;
        }

    System.out.println(headsCount);

}

public static boolean flip() {
    int rand = (int) (Math.random() * 2);
    if (rand == 1) {
        System.out.println("Heads");
        return true;
        }
    if (rand != 1){
        System.out.println("tails");
        return false;
        }
}

所以你甚至不需要比較字符串

  1. 當返回一個 int 時,您正在測試一個 String

應該是這樣的:

//variable ensures that we are not testing a separate flip all the time
int result = flip();
if (result == 1) {
    headscount++;
} else {
    tailscount++;
}
  1. 您檢索隨機數的方法很拙劣......很可能是尾部

    Random random = new Random(); //from + random.nextInt(to - from + 1) //0 + random.nextInt(1-0+1) int result = random.nextInt(2);
  2. 您的 for 循環正在運行一個過程,然后在您的 for 循環之外,您正在測試單個翻轉是否為正面,這與正面/反面結果和其余翻轉的概率完全無關。

     for(int x = 0; x < flips; x++) { //variable ensures that we are not testing a separate flip all the time int result = flip(); if (result == 1) { headscount++; } else { tailscount++; } }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM