用于循环输出

时间:2014-11-18 19:14:07

标签: java loops for-loop

几天前我在这里发布了Sum of previous two numbers entered)关于两个数字的总和,现在我已经到了最后一部分需要更多的帮助。

我想显示以减号为中心的最后一个数字的输出。字符总数应为20.因此,如果最后一个数字是16,则应该有2减去任何一方。如果它是一个奇数,那么右边应该有一个奇数的误差。

这就是我所拥有的

import java.util.Scanner; 公共类Interact {

public static void menu (){

        System.out.print(" Select one of the option below\n" +
                 "  1 -     Enter a new number\n " +
                 "  2 - Show the sum of the last two number\n" +
                 "  3 - Show the current number as pluses\n" +
                 "  4 - Show the current number as centred pluses\n" );

        }


public static void main(String[] args) {
    int no=0;  
    int option;

    int last = 0;
    int beforeLast = 0;

    Scanner input = new Scanner(System.in);


     do {
         menu();
         option=input.nextInt();

     switch (option) {

         case 1:

            System.out.print("Please enter a number between 0 and 20 : "  ); 
            no=input.nextInt();

            beforeLast = last;
            last = no;

            break;


         case  2:
            System.out.println("The Sum of the Numbers is : " + (last+beforeLast));
            break;

        case 3:

            int i;
            int j =0;
                               for (i=0; i<last; i++) {
                   System.out.print("+");
                   }
            for (j=20;j>last;j--){
                       System.out.print("-");}
            break;


        case 4: 
            int div=2;
            for (j=20;j>last;j--){
                       System.out.print("-");}
               for (i=0; i<last; i++) {
                   System.out.print("+");
                   }
            for (j=20;j>last;j--){
                       System.out.print("-");}
            break;          
         default :
             System.out.print("Invalid option");


     } 
 } while (option !=5);
}

}

如果数字为12,则左右应有4个误差,但我的输出在两侧显示为8

-------- ++++++++++++++++++++++++

如果数字为奇数,则应在右侧打印额外减号

1 个答案:

答案 0 :(得分:0)

Prettygeek是对的,你的代码很乱......无论如何试试这个......

int side = (20 - last) / 2;

for (int i = 0; i < side; i++) {
    System.out.print("-");
}
for (int i = 0; i < last; i++) {
    System.out.print("+");
}
for (int i = 0; i < side; i++) {
    System.out.print("-");
}