& M'在哪里?去? [英] Where did the 'M' go?

查看:66
本文介绍了& M'在哪里?去?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对String Buffer玩了一点,发现混合使用char和String是一个坏主意.我希望我的以下代码可以打印"Main",但是只有一个"ain".

很明显,单词是用String Buffer构造函数的char版本初始化的,但是我测试了诸如toString或getIndex()的几种方法,但是找不到"ain"旁边的任何东西-这让我感到奇怪:构造函数做了什么?有用途吗?可以通过某种方式再次从单词中检索"M"吗?

  import java.util.Random;公共类OrNotPublicClass {私有静态随机数rnd =新的Random();公共静态void main(String [] args){StringBuffer word = null;开关(rnd.nextInt(2)){情况1:字=新的StringBuffer('P');情况2:字=新的StringBuffer('G');默认:字=新的StringBuffer('M');}word.append("ain");System.out.println(word);}} 

解决方案

除了 break 问题之外,这里的主要问题是如何初始化 StringBuffer .

没有构造函数接受 char 作为参数

(还请注意,使用 StringBuilder 代替 StringBuffer ;后者仅在极少数需要线程安全的情况下有用)

I played a bit around with String Buffer and noticed, that mixing chars and String is a bad idea. I expected my following code to print "Main", however just got an "ain".

Clearly word was initialized with the char version of the String Buffer constructor, however I tested several methods like toString or getIndex( ), but could not find anything beside "ain" - which makes me wonder: What did the constructor do? Is there a usage for it? Can the 'M' somehow be retrieved again from word ?

import java.util.Random;

public class OrNotPublicClass {
    private static Random rnd = new Random();

    public static void main(String[] args) {
        StringBuffer word = null;
        switch (rnd.nextInt(2)) {
        case 1:
            word = new StringBuffer('P');
        case 2:
            word = new StringBuffer('G');
        default:
            word = new StringBuffer('M');
        }
        word.append("ain");
        System.out.println(word);
    }
}

解决方案

Apart from the break problem, the main problem here is how you initialize your StringBuffer.

There is no constructor accepting a char as an argument, but there is one accepting an int for the capacity.

And that is the one you use...

You should do:

word = new StringBuilder(); // not StringBuffer
// switch. Then:
word.append("ain");

(also note the use of StringBuilder instead of StringBuffer; the latter is useful only in the rare case where thread-safety is required)

这篇关于& M'在哪里?去?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆