gpt4 book ai didi

java - 我的 Java 三角形代码未打印完整的三角形

转载 作者:行者123 更新时间:2023-12-01 19:57:27 25 4
gpt4 key购买 nike

我必须编写一个代码来打印一个三角形,最后一行的长度是输入数字。此外,空白处必须用点填充。

It has to look like this.

此外,代码必须运行直到输入为奇数为止。

遗憾的是,我的代码没有打印出点或其他星星,而只是打印出最后一行。

有人可以看一下并给我一些提示吗?

任何帮助表示赞赏。预先非常感谢您。

这是代码:



import java.util.Scanner;

public class Triangle_new {

//Main-Method with Input-Check

public static void main(String[] args) {

System.out.println("Type in a number to get the triangle:");


Scanner sc = new Scanner(System.in);

int length = sc.nextInt();



if(length < 0 || length%2 == 0) {

System.out.println("Please type in a uneven number or zero to quit. ");
Triangle_Test.check_input(length);

}else{
display_triangle(length);
}

}

//DisplayTriangle-Method


public static void display_triangle(int length) {

int lines = (length+1)/2;

//Height of the Triangle
get_lines(length);

//Dotfiller Left Side
if(lines > 0){
get_dotsleft(lines, length);
}
//Stars-Output
if(lines > 0) {
get_stars(lines);
}
//Dotfiller Right Side
if(lines > 0) {
get_dotsright(lines, length);
}

}

//Constructors for Triangle

public static void get_lines(int length) {

for(int lines = 1; lines <= (length + 1) / 2; lines++){
System.out.println();
}
}

public static void get_dotsleft(int lines, int length){
for(int leftfiller = 1; leftfiller <= ((length + 1) / 2) - lines; leftfiller++) {
System.out.print(".");

}
}

public static void get_stars(int lines) {
for(int stars = 1; stars <= (2 * lines) - 1; stars++) {
System.out.print("*");

}
}



public static void get_dotsright(int lines, int length){
for(int rightfiller = 1; rightfiller <= ((length+1) / 2) - lines; rightfiller++) {
System.out.print(".");
}
}


}


//Triangle_Test Class with Input-Check Method

class Triangle_Test extends Triangle_new {

public static void check_input(int length) {


//Check Input until Input is uneven number

Scanner sc = new Scanner(System.in);

do {

length = sc.nextInt();

if(length%2 == 0 && length != 0) {
System.out.println("Invalid input. Try again.");
}


if(length%2 != 0 && length > 0) {

}

//Triangle Output

if(length%2 != 0){

Triangle_new.display_triangle(length);

}

if(length == 0) {
System.out.println(" -> Zero detected. Program will be shutdown.");
}



}while(length%2 != 0 || length != 0);

}

}



最佳答案

您的 get_lines() 方法听起来应该返回三角形将填充多少行(也基于您的注释),但它的作用是打印空行。尝试不使用它。

关于java - 我的 Java 三角形代码未打印完整的三角形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59028115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com