【问题标题】:Error in String/character uppercase/lowercase conversion with loop带循环的字符串/字符大写/小写转换错误
【发布时间】:2014-10-23 11:02:28
【问题描述】:

我一直在做作业,但我被卡住了。如果我输入字母:ahb,它只打印最后一个字母b,而不是全部:

public void run() 
{
    String value;
    while (true) {
        try {
            value = (String) conB.remove();
            if(value != null) { {
                for(int i=0; i < value.length(); i++) {
                    if(Character.isDigit(value.charAt(i))) {
                        int x = Integer.parseInt(value);
                        bConWin.setData(" "+(x*2));
                    }
                    if(Character.isLowerCase(value.charAt(i))) {
                        char x = value.toUpperCase().charAt(i);
                        //changed.append(Character.toUpperCase(x));
                        bConWin.setData(" " +x);
                    }
                    if(Character.isUpperCase(value.charAt(i))) {
                        char x = value.toLowerCase().charAt(i);
                        bConWin.setData(" "+x);
                    }
                }
            }
        }
    }
}

【问题讨论】:

  • 我没有看到你在打印任何东西。
  • 实际上想做什么?
  • @Eran 它是一个窗口,我没有使用 system.out.print 打印,我使用的是我实现的 bConWin 类型的框架。
  • @AhmadHeiba bConWin.setData 是否将数据附加到窗口或用新数据覆盖当前数据?

标签: java loops


【解决方案1】:

您只分配了一个字符作为 bConWin 的数据。这是一个修复和一些整理:

public static void main(String args[]) {
    String value = "HaaaOppSaN";
    if(value != null) {
        StringBuilder newValue = new StringBuilder();

        for(int i = 0; i < value.length(); i++) {
            char x = value.charAt(i);

            if(Character.isLowerCase(x)) {
                x = Character.toUpperCase(x);
            } else {
                x = Character.toLowerCase(x);
            }

            newValue.append("" + x);
        }

        bConWin.setData(newValue.toString());
    }
}

【讨论】:

    【解决方案2】:

    不需要外部无限循环。不带 catch 块的 try 也是如此。

    看看这个:

    public static void main(String[] args) {
        String switched = switchCharacterCase("Hello World!");
    
        bConWin.setData(switched);
    
        System.out.println(switched);
    }  
    
    public static String switchCharacterCase(final String input) {
        StringBuilder switched = new StringBuilder();
    
        if(input != null) { // nothing to do here, return switched
    
            for(int i = 0; i < input.length(); i++) {
    
                Character c = input.charAt(i);
    
                if(Character.isLowerCase(c)) {
                    c = Character.toUpperCase(c);
                } else {
                    c = Character.toLowerCase(c);
                }
    
                switched.append(c);
            }
        }
    
        return switched.toString();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-25
      • 1970-01-01
      • 2014-03-30
      • 2018-09-07
      • 2011-01-16
      • 1970-01-01
      • 2021-11-13
      • 1970-01-01
      相关资源
      最近更新 更多