1
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

BasdGod
  • 33
  • 2
  • 8
  • 1
    You're very close. One important thing you missed was instantiation of the object `input` for reading text from the console, e.g. `Scanner input = new Scanner(System.in);` – x4nd3r Sep 25 '14 at 22:24

3 Answers3

1

You can print "i" as text

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

Right now you are only printing "Character #1:" in each loop iteration. Instead of that, you'll need to output "Character #", then (i + 1), then ":", then string_1.charAt(i).

rgettman
  • 176,041
  • 30
  • 275
  • 357
0

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.

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. A better name for string_1 would therefore be input, or something similar.

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. This is done by concatenating a String that includes the loop variable i. 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).

Community
  • 1
  • 1
x4nd3r
  • 855
  • 1
  • 7
  • 20