简体   繁体   中英

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 would print

H

ee

lll

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. 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

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 . In this case, 4-2=2, so the substring should contain 2 characters, which it does.

An easier way to print out the ith character is to use charAt(i) instead of substring(i,i+1);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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