gpt4 book ai didi

java - 输入并指定要打印的字符以及每行要打印的字符数

转载 作者:行者123 更新时间:2023-12-02 12:09:41 25 4
gpt4 key购买 nike

我试图允许用户指定要打印的字符以及每行要打印的字符数。

我尝试使用以下类和方法来实现此目标:

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

}

}

第 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)

如何修复此循环,以便在同一行上打印 n 次用户输入的字符串。

最佳答案

您走在正确的轨道上,但不是使用 charAt在 for 循环中,尝试使用 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

关于java - 输入并指定要打印的字符以及每行要打印的字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46628759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com