[英]Why does java not print inside nested for loops inside a if else statement and appears as terminated?
因此,我正在编写一个程序,当您输入一个单词作为输入时,它会返回金字塔,例如:“输入单词:”
理由(L =左,R =右)? 我会打印
H
EE
LLL
LLLL
呜
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"
检查substring是否正确使用的一种方法是endIndex-beginIndex = substring的长度 。 在这种情况下,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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.