-2

我试图找到一个使用 switch 语句的(内置)java 方法。

为了澄清我的问题,我不是在问如何使用 Java switch 语句。我意识到我可以创建自己的方法并将 switch 语句放入其中。

我正在寻找一种在 Java 中将此类语句合并到其代码中的方法。

为了进一步澄清我的问题,我想在 Java API 中找到一个方法: http ://docs.oracle.com/javase/7/dofucs/api/使用 switch 语句。

谢谢!

4

1 回答 1

3

这是源代码中所有提到“switch”的 .java 文件的列表(它们中的大多数似乎都在使用 switch 语句,尽管有些似乎只是在评论中讨论它)。

http://pastebin.com/grBqEjBE

但要回答最初的问题:在众多示例中,这里有一个来自JLabel.java

    public String getAtIndex(int part, int index) {
        if (index < 0 || index >= getCharCount()) {
            return null;
        }
        switch (part) {
        case AccessibleText.CHARACTER:
            try {
                return getText(index, 1);
            } catch (BadLocationException e) {
                return null;
            }
        case AccessibleText.WORD:
            try {
                String s = getText(0, getCharCount());
                BreakIterator words = BreakIterator.getWordInstance(getLocale());
                words.setText(s);
                int end = words.following(index);
                return s.substring(words.previous(), end);
            } catch (BadLocationException e) {
                return null;
            }
        case AccessibleText.SENTENCE:
            try {
                String s = getText(0, getCharCount());
                BreakIterator sentence =
                    BreakIterator.getSentenceInstance(getLocale());
                sentence.setText(s);
                int end = sentence.following(index);
                return s.substring(sentence.previous(), end);
            } catch (BadLocationException e) {
                return null;
            }
        default:
            return null;
        }
    }

这在 Java API中确实可用。

于 2013-02-27T03:33:15.670 回答