使用数组和多个单词时java toLowerCase函数的问题'在字符串中

时间:2014-10-22 16:36:57

标签: java arrays while-loop split java.util.scanner

我对java非常新,因为在,我几乎不会写20行基本代码并让它们工作,新的水平,我有2个问题可能会也可能不会相关,因为它们来自非常相似的部分我亲自编写的代码。

import java.util.Scanner;

public class StringCW {


public static void main (String [] args) {

    String word = ""; 

    while(!(word.equals("stop"))){


        Scanner capconversion = new Scanner(System.in);
        System.out.println("Enter word:" );

        word = capconversion.next(); 
        String lower = word.toLowerCase();
        word = lower;
        System.out.println("conversion = " + word);

    }


    System.out.println("ending program");


        }
    }
}

这是我的第一个代码块,它被设计为接受任何字符串并将其转换为小写,但是如果我要打印任何由空格分隔的内容,例如:" WEWEFRDWSRGdfgdfg DFGDFGDFG"只有第一个单词'将被打印和转换,我也从封面转换中获得内存泄漏,但我不明白这意味着什么或如何解决它

我的第二个问题可能是同样的问题

import java.util.Scanner;

public class splitstring {

private static Scanner capconversion;

public static void main (String [] args) {

    String word = ""; 

    while(!(word.equals("stop"))){

        capconversion = new Scanner(System.in);
        System.out.println("Enter word:" );

        word = capconversion.next(); 
        String lower = word.toLowerCase();
        String[] parts = lower.split(" ");
        parts [0] = "";
        parts [1] = "";
        parts [2] = "";
        parts [3] = "";
        parts [4] = "";


        System.out.println("conversion = " + lower
        parts [0] + parts [1] + parts [2] + parts [3] + parts [4]);

        }

        System.out.println("ending program");
    }
}

这是第二大块代码,旨在完成与前一个相同的工作,除了打印出每个单词'在新行上,然后返回到输入部分,直到输入停止命令

我得到的错误是

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
    at splitstring.main(splitstring.java:21)

然而,我不明白错误的来源

1 个答案:

答案 0 :(得分:3)

这是因为您正在使用Scanner.next(),它返回一个令牌 - 并且默认使用空格作为令牌分隔符。

如果你想一次捕获整行,也许你应该使用nextLine()

至于你的ArrayIndexOutOfBoundsException - 原因基本相同。您在一个单词上调用split,因此返回的数组只有一个元素(元素0)。当你尝试设置元素1时,它超出了数组的范围,因此是例外。

请注意,此处的任何内容都与toLowerCase()无关。