簡體   English   中英

檢查字符串是否包含帶for for循環的字符?

[英]Check if string contains a character with for loop?

我目前正在研究一個簡單的代碼,它將檢查用戶輸入的String是否包含for循環中指定的字符。

我目前的代碼

import java.util.Scanner;
public class AutumnLeaves {
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int G = 0;
    int R = 0;
    int Y = 0;
    int B = 0;
    String S = sc.nextLine();
    for (int i = 0; i < S.length(); i++) {
        if (S.contains("G")) {
            G++;
        } else {
            if (S.contains("R")) {
                R++;
            } else {
                if (S.contains("Y")) {
                    Y++;
                } else {
                    if (S.contains("B")) {
                        B++;
                    }
                }
            }
        }
    }
    int total = G + R + Y + B;
    System.out.println(G/total);
    System.out.println(R/total);
    System.out.println(Y/total);
    System.out.println(B/total);
}

}

如您所見,它檢查字符串是否包含此類字符,並將字符的計數器增加一。 但是,當我運行它時,我沒有收到我預測的結果。 如果我輸入GGRY,它輸出1 0 0 0.當所需的輸出為

0.5 0.25 0.25 0.0

任何幫助,將不勝感激!

問題是如果整個字符串包含給定的字符,則S.contains返回true。 S.charAt應該解決你的問題:

for (int i = 0; i < S.length(); i++) {
    if (S.charAt(i) == 'G') G++;
    else if (S.charAt(i) == 'R') R++;
    else if (S.charAt(i) == 'Y') Y++;
    else if (S.charAt(i) == 'B') B++;
}

此外,除以整數將返回一個整數(向下舍入)。 因此,除非所有字符都相同,否則輸出將始終為0 只需在打印前將它們double

System.out.println((double) G/total);
System.out.println((double) R/total);
System.out.println((double) Y/total);
System.out.println((double) B/total);

編輯:正如在評論中指出薩米特古拉蒂,switch語句中會有更好的表現在Java 7中另外,大衛康拉德指出,僅使用if S IN的for作為條件是相互排斥的循環將工作太。

你早期的代碼S.contains("some character")是在整個字符串中找到字符的索引。 使用S.charAt(i)專門找到字符串中第i個位置的索引。 最后,您需要將整數轉換為浮點,以便將輸出打印為浮點值。

public class AutumnLeaves {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int G = 0;
        int R = 0;
        int Y = 0;
        int B = 0;
        String S = sc.nextLine();
        for (int i = 0; i < S.length(); i++) {
            if (S.charAt(i) == 'G') {
                G++;
            } else {
                if (S.charAt(i) == 'R') {
                    R++;
                } else {
                    if (S.charAt(i) == 'Y') {
                        Y++;
                    } else {
                        if (S.charAt(i) == 'B') {
                            B++;
                        }
                    }
                }
            }
        }
        int total = G + R + Y + B;
        System.out.println(G * 1.0 / total);
        System.out.println(R * 1.0 / total);
        System.out.println(Y * 1.0 / total);
        System.out.println(B * 1.0 / total);
    }
}

在此輸入圖像描述

暫無
暫無

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

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