简体   繁体   English

用Java打印字符

[英]Printing character in java

I'm trying print a given String char by char: 我正在尝试通过char打印给定的String char:

public static void main(String[] args) {
    char c;
    Scanner scaner = new Scanner(System.in);
    int length = scaner.next().length();
    System.out.println(length);
    int i = 0;

    while (i < length) {
        c = scaner.next().charAt(i);
        System.out.println(c);
        i++;
    }
}

Once this code has reached int length = scaner.next().length(); 一旦此代码达到int length = scaner.next().length(); it doesn't continue. 它不会继续。 What's causing this? 是什么原因造成的?

You should store the scanned value in the temporary variable. 您应该将扫描的值存储在临时变量中。

char c;
Scanner scaner = new Scanner(System.in);

// Storing scanned value
String nextStr = scaner.next();

int length = nextStr.length();
System.out.println(length);

int i = 0;
while(i < length){
    c = nextStr.charAt(i);
    System.out.println(c);
    i++;
}

In your original code you call next repeatedly in a loop, but this does not return the original scanned value, but the next line of input. 在原始代码中,您将在循环中重复调用next ,但这不会返回原始扫描值,而是返回下一行输入。

You need to enter something after calling next(). 您需要在调用next()之后输入一些内容。

As addition too Alexander's answer. 亚历山大的答案也是如此。

The line: int length = scaner.next().length(); 这行代码: int length = scaner.next().length(); gets the next line and then checks the length. 获取下一行,然后检查长度。 So you already got the next line and calling next() again asks for different input. 因此,您已经获得了下一行,并再次调用next()要求输入不同的内容。

That's the reason why you should always store the return value of next() in a variable! 这就是为什么您应该始终将next()的返回值存储在变量中的原因!

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

相关问题 "打印字符串中出现的字符 - Java" - Printing character occurrence in string - Java 用Java打印Unicode或补充字符 - Printing Unicode or Supplementary Character in Java 在Java中打印与字符串等效的特定于字符的行 - Printing a character specific line equivalent to string in Java Java:不打印以某些字符开头的行 - Java: not printing lines which start with certain character 在点矩阵上打印-没有字符/字母间距(从Java应用程序打印) - Printing on dot matrix --no character/letter spacing (Printing from java application) Java JDBC-无效字符,将打印查询放入SQLDeveloper中并可以使用 - Java JDBC - invalid character, put printing query and using it in SQLDeveloper works Java IO,从文件读取并打印到2D字符数组 - Java IO, reading from a file and printing to a 2d character array Java,不在 Visual Studios Code 中打印汉字,但在 Python 中有效 - Java, not printing Chinese Character in Visual Studios Code, but works in Python Java:在控制台泰语文本打印为一些奇怪的字符 - Java : In console Thai text is printing as some strange character Java打印文本文件的输出并检查第一个字符 - Java printing output of text file and checking first character
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM