input and specify the character to print out and the number of characters to print on each line

时间:2017-10-08 07:55:25

标签: java loops character

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 个答案:

答案 0 :(得分:1)

你走在正确的轨道上,而不是在你的for循环中使用charAt,而是在之前使用 charAt 的地方尝试这样的事情:

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);
    }
  }
}

使用示例:

Please enter the character you want repeated:  a
Please enter the number of times you would like to print the character: 5
aaaaa   

答案 1 :(得分:0)

来自Javadoc

  

返回指定索引处的char值。索引范围从0length() - 1。序列的第一个char值是索引0,下一个是索引1,依此类推,就像数组索引一样。

您将从1转到length(),而不是0转到length() - 1