[英]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.