Java交换字符而不是元音

问题描述 投票:0回答:1

我想交换字符串中除元音之外的字符。有很多代码,但是,这是我正在处理的代码,我觉得很容易理解,但是并没有产生预期的结果。

public class RandomPractise {

    //1st find out a vowel
    public Boolean isVowel(char c) {
        boolean isV = true;
        if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
            isV = true;
        } else {
            isV = false;
        }
        return isV;
    }

    //Check current and next chars if not vowel do the swap
    public void randomTest() {
        String str = "boat";

        char[] c1 = str.toCharArray();

        for (int i = 0; i < c1.length - 1; i++) {
            if (!(isVowel(c1[i])) && !(isVowel(c1[i + 1]))) {
                char temp = c1[i];
                c1[i] = c1[i + 1];
                c1[i + 1] = temp;
            }
        }
        System.out.println(String.valueOf(c1));
    }

    public static void main(String[] args) {
        RandomPractise r = new RandomPractise();
        r.randomTest();
    }

示例:如果我使用输入:boat,我希望看到输出:toab [这不会发生]。当我使用输入:sboath时,我看到输出bsoaht。

问题:我应该做些什么改变才能使其在船上工作?

感谢您的时间。

java swap
1个回答
0
投票

“问题:我应该做些什么改变才能使其在船上工作?”

您是要这样做吗?

public class RandomPractise {

    //1st find out a vowel
    public Boolean isVowel(char c) {
        boolean isV = true;
        if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
            isV = true;
        } else {
            isV = false;
        }
        return isV;
    }

    public void randomTest() {
        String str = "boat";

        char[] c1 = str.toCharArray();
        int n = str.length();
        for (int i = 0; i < n/2; i++) {
            if (!(isVowel(c1[i])) && !(isVowel(c1[n - i - 1]))) {
                char temp = c1[i];
                c1[i] = c1[n - i - 1];
                c1[n - i - 1] = temp;
            }
        }
        System.out.println(String.valueOf(c1));
    }

    public static void main(String[] args) {
        RandomPractise r = new RandomPractise();
        r.randomTest();
    }
© www.soinside.com 2019 - 2024. All rights reserved.