I am trying to allow the user to specify the character to print out and the number of characters to print on each line.
I tried to reach this goal with the following class and method:
import java.util.Scanner; public class test3char { /** * @param args */ public static void main(String[] args) { //insert the character System.out.println("insert character"); Scanner keyboard = new Scanner(System.in); String str= keyboard.nextLine(); //insert the time you would like to print the character System.out.println("insert the number of times you would like to print the car"); int n = keyboard.nextInt(); keyboard.close(); // loop int i; for (i=1;i<=n;i=i+1) { System.out.print(str.charAt(i)); } } } I have the following error at line 17:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1 at java.lang.String.charAt(Unknown Source) at test3char.main(test3char.java:17) How I can fix this loop in order to print the string input by the user by n time on the same line.
str.charAt(i)? Do you know what that means?