gpt4 book ai didi

java - 为什么 java 不在 if else 语句内的嵌套 for 循环中打印并显示为已终止?

转载 作者:行者123 更新时间:2023-12-02 12:03:16 24 4
gpt4 key购买 nike

所以,我正在编写一个程序,当你输入一个单词作为输入时,它会返回金字塔例如:“输入一个词:”你好

理由(L=左,R=右)?L将打印

H

呜呜

   import java.util.Scanner;

public class Justification{
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
System.out.println("Enter a word: ");
String word=in.nextLine();
System.out.println("Justification (L=left, R=Right)?");
String Justification=in.nextLine();
if(Justification.equalsIgnoreCase("l")){
for (int i = 0; i < word.length(); i++) {
for (int j = 1; j <= i; j++) {
System.out.print(word.substring(i,i));
}
System.out.println();
}
}else if(Justification.equalsIgnoreCase("r")){
for (int i = word.length()-1; i >= 0; i--) {
for (int s = 0; s < i; s++) {
System.out.print(" ");
}
for (int j = word.length()-1; j >= i; j--) {

System.out.println(word.substring(i,i));
}
System.out.println("");
}
}else System.out.println("Bad input");
}}

最佳答案

您错误地使用了substring(begin,end)。包含开始索引处的字符,但不包含结束索引处的字符。

如果单词是 hello,你调用 substring(2,4),它会是 ll

String str = "hello".substring(2,4); //str is "ll"

检查子字符串是否正确使用的一种方法是endIndex-beginIndex=子字符串的长度。在本例中,4-2=2,因此子字符串应包含 2 个字符,事实确实如此。

打印第 i 个字符的更简单方法是使用 charAt(i) 而不是 substring(i,i+1);

System.out.println("hello".substring(0,1)); //prints h
System.out.println("hello".charAt(0)); //also prints h

关于java - 为什么 java 不在 if else 语句内的嵌套 for 循环中打印并显示为已终止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47087562/

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