如果输入输出错误

时间:2016-06-26 18:47:27

标签: 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 个答案:

答案 0 :(得分: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");
}