简体   繁体   English

如何获得程序以将每个字符打印为“字符1 :(字符),字符2 :(字符)等”?

[英]How can I get my program to print out each character as “Character #1: (character) , Character #2: (character), etc”?

int i;

System.out.print("Please enter a string: ");
String string_1 = input.nextLine();

  System.out.println("Entered string: " + string_1);

  for ( i = 0;  i < string_1.length();  i++ ) {
     System.out.println ("Character #1:" + string_1.charAt(i));
  }

How can I get the program to print out each character on new line headed by "Character #(the characters number):" 如何获取程序以在以“字符#(字符编号):”开头的新行上打印出每个字符

Sorry if the question is confusing, I'm new to programming 抱歉,这个问题令人困惑,我是编程新手

您可以将“ i”打印为文本

 System.out.println ("Character #" + i + ":" + string_1.charAt(i));

Right now you are only printing "Character #1:" in each loop iteration. 现在,您在每次循环迭代中仅打印"Character #1:" Instead of that, you'll need to output "Character #" , then (i + 1) , then ":" , then string_1.charAt(i) . 取而代之的是,您需要输出"Character #" ,然后是(i + 1) ,然后是":" ,然后是string_1.charAt(i)

A few things to note here. 这里要注意几件事。 First of all, you are never actually creating an object to accept input from the console. 首先,您永远不会真正创建一个对象来接受来自控制台的输入。 In Java, this task is often carried out using a Scanner . 在Java中,通常使用Scanner来执行此任务。

Scanner sc = new Scanner(System.in);

Next, typical Java code conventions (taking Google's guide for example ) dictate that variable names should be in camelCase style, and should not contain underscore characters. 接下来,典型的Java代码约定(以Google指南为例 )规定变量名称应采用camelCase样式,并且不应包含下划线字符。 A better name for string_1 would therefore be input , or something similar. 因此,将input string_1的更好名称,或类似的名称。

System.out.print("Please enter a string: ");
String input = sc.nextLine(); // input from console
System.out.println("Entered string: " + input);

Finally, in your for-loop , you want to increment the number that is being displayed to the user for the character location as the loop progresses. 最后,在for-loop ,您希望随着for-loop ,递增显示给用户的字符位置编号。 This is done by concatenating a String that includes the loop variable i . 这是通过串联一个包含循环变量iString来完成的。 Since the loop is zero-indexed, and presumably you want the output to be interpreted by humans, it would be useful to add one to the index when displaying it. 由于循环是零索引的,并且大概您希望人类对输出进行解释,因此在显示索引时将其添加到索引会很有用。

for (int i = 0;  i < input.length();  i++ ) {
    // build a string using `i + 1` to display character index
    System.out.println ("Character #" + (i + 1) + ": " + input.charAt(i));
}

It's also worth noting, that declaring the loop variable int i within the loop definition is preferable, as it limits the scope of the variable (See: Declaring variables inside or outside of a loop ). 还值得注意的是,最好在循环定义中声明循环变量int i ,因为它限制了变量的范围(请参阅: 在循环内部或外部声明变量 )。

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

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