如何在与for-loop输出相同的行上打印一行文本

时间:2016-03-04 03:09:38

标签: java for-loop

我的代码行如下。我正试图在与它相关的商店#旁边打印星号。现在,例如,如果我为商店1输入200,它将输出:

Store 1:  
**

但我希望它输出:

Store 1: **

我该怎么做?

  int store1;
  System.out.print("Enter today's sales for store 1 in dollars: $");
  store1 = keyboard.nextInt();

  int store2;
  System.out.print("Enter today's sales for store 2 in dollars: $");
  store2 = keyboard.nextInt();

  int store3;
  System.out.print("Enter today's sales for store 3 in dollars: $");
  store3 = keyboard.nextInt();

  int store4;
  System.out.print("Enter today's sales for store 4 in dollars: $");
  store4 = keyboard.nextInt();

  int store5;
  System.out.print("Enter today's sales for store 5 in dollars: $");
  store5 = keyboard.nextInt();

  System.out.println("SALES BAR CHART");

     System.out.println("Store 1:");

     for (int a = 0; a <= store1; a += 100)
     {
        System.out.print("*");
     }

     System.out.print("\n");
     System.out.println("Store 2:");

     for (int b = 0; b <= store2; b += 100)
     {
        System.out.print("*");
     }

     System.out.print("\n");
     System.out.println("Store 3:");

     for (int c = 0; c <= store3; c += 100)
     {
        System.out.print("*");
     }

     System.out.print("\n");
     System.out.println("Store 4:");

     for (int d = 0; d <= store4; d += 100)
     {
        System.out.print("*");
     }

     System.out.print("\n");
     System.out.println("Store 5:");

     for (int e = 0; e <= store5; e += 100)
     {
        System.out.print("*");
     }

        System.out.print("\n");
        System.out.print("Each * represents $100");

2 个答案:

答案 0 :(得分:0)

System.out.println("Store 1:");应为System.out.print("Store 1:");正如您所知,println打印出文本然后转到新行。

答案 1 :(得分:0)

使用System.out.print()代替System.out.println()打印内容而不打印换行符。

例如,

 System.out.println("Store 1:");

 for (int a = 0; a <= store1; a += 100)
 {
    System.out.print("*");
 }

 System.out.print("\n");

应该是

 System.out.print("Store 1: ");

 for (int a = 0; a <= store1; a += 100)
 {
    System.out.print("*");
 }

 System.out.println();