首页 > 解决方案 > 矩形程序不准确

问题描述

我正在尝试制作一个程序,它将询问用户矩形的长度和宽度,其中长度和宽度将用 * 符号描绘。该程序实际上运行良好,它只是添加了一个额外的符号,我这样做了不知道为什么。

例如,我输入 5 作为长度,输入 4 作为宽度,我的输出最终将如下所示:

          xxxxxx
          x    x
          x    x
          x    x
          xxxxxx

我上面的这些尺寸实际上是 6x5,即使我在程序中放了 5x4。

我希望程序看起来像这样,预期输出:

        xxxxx
        x   x
        x   x
        xxxxx

我的代码是:

import java.util.Scanner;

public class aps{
public static void main(String [] args){ 

    //Declaring variables
    int length, width;

    //Prompting user for length
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter the length of your rectangle: ");
    length = scanner.nextInt();// integer i for rows(width)

    //Prompting user for width
    System.out.print("Enter the width of your rectangle: ");
    width = scanner.nextInt();//integer j for columns(length)

    //Processing
    for(int i = 0; i<=width; i++){  //first loop
        for(int j = 0; j<=length; j++){ //second loop
            if(i==0||j==0||j==length||i==width){
                System.out.print("*");
            }
            else{
                System.out.print(" ");
            }

        }// end of second loop

        System.out.println();

    } //end of first loop


    }
}

标签: java

解决方案


如果您希望 for 循环运行某些n时间,则需要 for 循环采用形式for(int i=0; i < n; i++)for(int i=1; i <= n; i++)代替for(int i=0; i <= n; i++),它运行n+1时间(即一次为 0,然后n从 开始1..n)。

一个简单的解决方法是在 for 循环条件中更改<=to <,以及更改if条件以反映更改:

import java.util.Scanner;

public class aps{
public static void main(String [] args){ 

    //Declaring variables
    int length, width;

    //Prompting user for length
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter the length of your rectangle: ");
    length = scanner.nextInt();// integer i for rows(width)

    //Prompting user for width
    System.out.print("Enter the width of your rectangle: ");
    width = scanner.nextInt();//integer j for columns(length)

    //Processing
    for(int i = 0; i<width; i++){  //first loop
        for(int j = 0; j<length; j++){ //second loop
            if(i==0||j==0||j==length-1||i==width-1){
                System.out.print("*");
            }
            else{
                System.out.print(" ");
            }

        }// end of second loop

        System.out.println();

    } //end of first loop


    }
}

推荐阅读