0
import java.util.Scanner;

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

    int hoyde;
    int linje = 0;

    Scanner tast = new Scanner(System.in);

    System.out.println("Hvor hoy skal din V bli?(mellom 2 og 10)");
    hoyde = tast.nextInt();
    tast.nextLine();

     //assert (hoyde <=2 && hoyde >=10) : "hoyde må være mellom 2 og 10";

    for(linje= 0; linje < hoyde;linje++) {
      int start = linje;
      int end = (hoyde-1)*2;

      for(linje= 0;linje<=linje;linje++){
        if(linje == end){
          System.out.println("*");
          break;
        }
        else if(linje == start){
          System.out.print("*");
        } else{
          System.out.print(" ");
        }
      }
    }
  }
}

我正在尝试打印出Vusing *. 不知何故,当我运行代码时,它会在同一行打印出 2 个单星。我被困在这个问题上,我似乎无法找出我应该如何传播给定的信息。我使用Scanner输入一个数字,表示V应该有什么高度。

4

2 回答 2

1

即使它没有解决任何与 Java 相关的问题,而只是纯粹的 ad hoc 算法,它也不应该被回答。但是,由于您正在使用,drjava我假设您只是在 Java 世界中的第一条道路上,并且提供帮助会很好。

正如@Keppil 在他的评论中已经说过的那样,永远不要在两个认可的循环中使用相同的迭代原语,除非真的有特殊处理(我自己从来没有遇到过),因为当它增加(减少)时你会丢失第一个循环索引由内循环。

还有一些算法方法,希望在下面的代码中注释清楚:

public class FancyVDrawer
{
  public static void main(String[] args)
  {
    int hoyde;
    int linje = 0;
    Scanner tast = new Scanner(System.in);
    System.out.println("Hvor hoy skal din V bli?(mellom 2 og 10)");
    hoyde = tast.nextInt();
    tast.nextLine();
    //assert (hoyde <=2 && hoyde >=10) : "hoyde må være mellom 2 og 10";
    ++hoyde; //We need hoyde line stars thus should be incremented by one since we cannot draw one star in last line
    int end = (hoyde - 1) * 2; // The end should be calculated once, then decremented and not reassigned in each loop iteration
    for (linje = 0; linje < hoyde; linje++)
    {
      int start = linje;
      for (int i = 0; i < end; i++)
      {
        if ((i == start))
        {
          System.out.print("*");
        } else if (i == (end-1))
        {
          System.out.println("*");
          --end; // Decrement the end index once we are going to a new line
        }
        else
        {
          System.out.print(" ");
        }
      }
      if(linje == (hoyde - 2)) // Should break to prevent writing the last lonely star
        break;
    }
  }
}
于 2014-09-10T20:58:20.373 回答
0

它在 (linje==start) 时打印星号 1,在 (linje==end) 时打印星号 2。在内循环之后,linje>hoyde,因此退出外循环。

如上所述,您可能希望为循环变量指定不同的名称。

于 2014-09-10T20:08:11.363 回答