几天前,我在这里发布了关于两个数字之和(输入的前两个数字的总和),现在我已经到了最后一部分,需要更多帮助。
我想显示以减号为中心的最后一个数字的输出。 字符总数应为 20。因此,如果最后一个数字是 16,则两侧都应该有 2 减去。如果它是一个奇数,则右侧应该有一个奇数个缺点。
这就是我所拥有的
import java.util.Scanner;公共类 交互 {
public static void menu (){
System.out.print(" Select one of the option belown" +
" 1 - Enter a new numbern " +
" 2 - Show the sum of the last two numbern" +
" 3 - Show the current number as plusesn" +
" 4 - Show the current number as centred plusesn" );
}
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
个--------++++++++++++++--------
如果数字是奇数,则应在右侧打印额外的减号
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("-");
}