有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java给定的输入得到了错误的输出

import java.util.Scanner ;
public class printH 
{
public static void main( String[] args ) 
{
    Scanner in = new Scanner(System.in) ;
    System.out.print("Please enter the height of H: ") ;
    int height = in.nextInt() ;
    int heightThird = findThird(height);
    int topBottom = printTopAndBottom(heightThird);
}
public static int findThird(int height3)
{
    if(height3>=4)
    {
        height3 = (height3 + 2) / 3 ;

    }
return height3 ;
}
public static int printTopAndBottom(int spacingH)
{
    String letterH = "H" ;
    String letterSpace = " " ;
    System.out.print(letterH) ;
    System.out.print(letterSpace)  ;
    System.out.println(letterSpace) ;
    return spacingH ; 
 }    
}

这是我到目前为止提出的代码,但它给了我错误的输出

如果输入为10,则输出应为

hhhh    hhhh
hhhh    hhhh
hhhh    hhhh
hhhh    hhhh

然而,我得到的输出

Please enter the height of H: H  

共 (1) 个答案

  1. # 1 楼答案

    您可以使用以下行:String letterH = "H" ;,这样就不会出现h。您需要一些循环,用于打印正确数量的h

    这里有一些简单的代码:

    public static void main( String[] args )
    {
        Scanner in = new Scanner(System.in) ;
        System.out.print("Please enter the height of H: ") ;
        int height = in.nextInt() ;
        int heightThird = findThird(height);
        for (int i = 0; i < heightThird; i++) {
            printTopAndBottom(heightThird);
        }
    }
    
    public static int findThird(int height3)
    {
        if(height3 >= 4)
        {
            height3 = (height3 + 2) / 3 ;
        }
        return height3 ;
    }
    
    public static void printTopAndBottom(int spacingH)
    {
        String line = "";
    
        for (int j = 0; j < spacingH; j++) {
            String currentChar = j % 2 == 0 ? "h" : " ";
            for (int i = 0; i < spacingH; i++) {
                line += currentChar;
            }
        }
    
        System.out.print(line + "\n");
    }