简体   繁体   English

将一行单词从小写转换为大写

[英]Converting a line of words from lower case to upper case

I would like to convert a line of words, including punctuation and spaces, from lower case to upper case. 我想将包括标点和空格在内的一行单词从小写转换为大写。 My method to deal with the question is to firstly store the sentence in String form, then apply the "toUpperCase" Java class to it like this: 解决这个问题的方法是,首先以String形式存储句子,然后将“ toUpperCase” Java类应用到它,如下所示:

public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    String input = in.next();
    String upper = input.toUpperCase();

    System.out.println(upper);

}

But it reads a sentence with spaces or punctuation in the middle, something would come out like this: 但是它读取的句子中间有空格或标点符号,会出现类似以下的内容:

you are so smart!
YOU

How to solve this problem? 如何解决这个问题呢? Can anyone give me some advice? 谁能给我一些建议? Thanks in advance. 提前致谢。

Change 更改

 String input = in.next();

In to 进入

 String input = in.nextLine(); // you need to take entire line

Now 现在

 Scanner in = new Scanner(System.in);
 String input = in.nextLine();
 String upper = input.toUpperCase();

 System.out.println(upper);

Out out: 出:

 YOU ARE SO SMART

More info: Read next() and nextLine() 更多信息:阅读next()nextLine()

in.read() will return you the next token (as per javadoc , a complete token is preceded and followed by input that matches the delimiter pattern , , which by defaul matches a whitespace), not the next line. in.read()将返回下一个标记(按照javadoc的要求在其之前是完整的标记,然后是与定界符pattern匹配的输入,该定界符通过defaul匹配空格),而不是下一行。

Change 更改

String input = in.next();

to

String input = in.nextLine();

If you still want to stick to the " in.next() approach" and get the entire line, you can change the delimiter pattern. 如果您仍然希望坚持使用“ in.next()方法”并获得整行内容,则可以更改定界符模式。 Like this: 像这样:

Scanner in = new Scanner(System.in).useDelimiter("\n");

In this case, a token will be everthing that ends with a line-breaking character ( \\n ) and in.next() will return you the entire line. 在这种情况下, 令牌将是一切,以换行符( \\n )结尾,而in.next()将返回整行。

 String input = in.next();

When you store input by using .next(), whenever the scanner encounters a whitespace it stops reading for input. 当您使用.next()存储输入时,只要扫描仪遇到空白,它将停止读取输入。 Whereas if you use 而如果您使用

 String input = in.nextLine();

the scanner will input the complete line entered by the user. 扫描仪将输入用户输入的完整行。 In simple terms, next() - to input a word nextLine() - to input a sentense 简而言之,next()-输入单词nextLine()-输入句子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM