我正在尝试打印出用户指定的字母数量。例如用户输入单词“Horse”并指定他们想要打印的字母数量- 4. 输出应为“结果:Hors”。我必须使用子字符串方法。
我的程序删除了用户指定的字母并打印出其余的字母。我怎样才能解决这个问题?
import java.util.Scanner;
public class FirstPart {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a word: ");
String word = reader.nextLine();
System.out.println("Length of the first part: ");
int firPar = Integer.parseInt(reader.nextLine());
int i = 0;
while (i <= firPar) {
System.out.print("Result: " + word.substring(firPar));
i++;
break;
}
}
}
最佳答案
您可能应该使用Scanner.nextInt()
而且你根本不需要循环。只需调用String.substring(int, int)
从 0
到 firPar
就像
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a word: ");
String word = reader.nextLine();
System.out.println("Length of the first part: ");
int firPar = reader.nextInt();
System.out.println("Result: " + word.substring(0, firPar));
}
关于java - 打印出用户指定长度的第一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27257495/