简体   繁体   English

为什么Java无法在if else语句内的嵌套for循环内打印并显示为终止?

[英]Why does java not print inside nested for loops inside a if else statement and appears as terminated?

So, I'm writing a program that returns pyramids when you give a word as an input for instance: "Enter a word: " Hello 因此,我正在编写一个程序,当您输入一个单词作为输入时,它会返回金字塔,例如:“输入单词:”

Justification (L=left, R=Right)? 理由(L =左,R =右)? L would print 我会打印

H H

ee EE

lll LLL

llll LLLL

oooo

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

You are using substring(begin,end) incorrectly. 您正在错误地使用substring(begin,end) The character at the begin index is included while the character at the end index is not. 包括开始索引处的字符,但不包括结束索引处的字符。

If the word is hello, and you call substring(2,4), it would be ll 如果单词hello,并且您调用substring(2,4),它将是ll

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

One way to check if substring is used correctly is that endIndex-beginIndex=length of substring . 检查substring是否正确使用的一种方法是endIndex-beginIndex = substring的长度 In this case, 4-2=2, so the substring should contain 2 characters, which it does. 在这种情况下,4-2 = 2,因此子字符串应该包含2个字符。

An easier way to print out the ith character is to use charAt(i) instead of substring(i,i+1); 打印第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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM