0

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.

2
  • Not sure I'm following. Can you share a sample input and the output that's supposed to be generated for it? Commented Oct 8, 2017 at 8:00
  • Why are you printing str.charAt(i)? Do you know what that means? Commented Oct 8, 2017 at 8:09

2 Answers 2

1

You are on the right track, but instead of using charAt inside your for-loop, instead try something like this where you use charAt earlier on:

import java.util.Scanner; class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Please enter the character you want repeated: "); char character = scanner.next().charAt(0); System.out.print("Please enter the number of times you would like to print the character:"); int number = scanner.nextInt(); for(int i = 0; i < number; i++) { System.out.print(character); } } } 

Example usage:

Please enter the character you want repeated: a Please enter the number of times you would like to print the character: 5 aaaaa 
Sign up to request clarification or add additional context in comments.

Comments

0

From the Javadoc:

Returns the char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.

You're going from 1 to length(), not 0 to length() - 1.

1 Comment

@JohnS. Don't forget to upvote and accept this answer (using the tick underneath the voting buttons) if you found it useful.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.