Java 如何在main方法中使用FOR循环
我似乎不知道如何制作for循环,所以在他们完成加法1后,它将返回菜单。我也需要使用for循环来实现这一点 我删掉了代码的其余部分以节省空间。所以我只需要在加法上得到帮助,剩下的我可以做。 我从未使用过这个网站,所以我不知道如何正确发布代码Java 如何在main方法中使用FOR循环,java,loops,for-loop,Java,Loops,For Loop,我似乎不知道如何制作for循环,所以在他们完成加法1后,它将返回菜单。我也需要使用for循环来实现这一点 我删掉了代码的其余部分以节省空间。所以我只需要在加法上得到帮助,剩下的我可以做。 我从未使用过这个网站,所以我不知道如何正确发布代码 public static void main (String args[]) { Scanner userInput = new Scanner(System.in); int add, add2, sub, sub2, multi, m
public static void main (String args[])
{
Scanner userInput = new Scanner(System.in);
int add, add2, sub, sub2, multi, multi2, divi, divi2, rema, rema2, power, power2, Conf;
System.out.println("(1) Addition~");
System.out.println("(2) Subtraction~");
System.out.println("(3) Multiply~");
System.out.println("(4) Divide~");
System.out.println("(5) Remainder~");
System.out.println("(6) Power~");
System.out.println("(7) Quit~");
Conf = userInput.nextInt();
if(Conf == 1)
{
System.out.print("Enter first number to add: ");
add = userInput.nextInt();
System.out.print("Enter second number to add: ");
add2 = userInput.nextInt();
Ansr();
Adder(add, add2);
Sp();
}
else if(Conf == 7);
System.out.println("Exiting Program...");
System.exit(0);
userInput.close();
}
}
你的问题需要更清楚一点,比如为什么你需要一个for循环来进行加法 在这种情况下,while循环在语法上是更好的选择 试试这个:
public static void main (String args[])
{
Scanner userInput = new Scanner(System.in);
int add, add2, sub, sub2, multi, multi2, divi, divi2, rema, rema2, power, power2, Conf;
Conf = 0;
while(Conf != 7)
{
System.out.println("(1) Addition~");
System.out.println("(2) Subtraction~");
System.out.println("(3) Multiply~");
System.out.println("(4) Divide~");
System.out.println("(5) Remainder~");
System.out.println("(6) Power~");
System.out.println("(7) Quit~");
Conf = userInput.nextInt();
if(Conf == 1)
{
System.out.print("Enter first number to add: ");
add = userInput.nextInt();
System.out.print("Enter second number to add: ");
add2 = userInput.nextInt();
Ansr();
Adder(add, add2);
............
}
else if()
{
// add additional else if for other operations
}
}
userInput.close();
}
我真的很困惑你到底想要什么。有什么问题吗?你想让代码做什么?它在做什么?我认为while循环更合适。比如while Conf!=7.初始化Conf=0,然后将所有内容放在变量声明和初始化之后的循环中。开关将比多个if-else构造更易于读取。我可能会添加一些函数来解决这些问题。他们可能都在做同样的事情:打印两行请求输入的内容,输入两个数字,然后执行一个操作。Edit:为了澄清这一点,我在Conf for 1到6中使用了一个switch语句,该语句调用了一些doMath函数,其中一个参数指定了数学类型;我会吃第一个数字。Conf=0要干净得多;在底部。@PM77-1糟糕透了!!感谢您为了清晰起见指出它:for和while循环可以互换使用。只有当您知道循环将要运行的有限次数时,才应该使用for的推理是不准确的。我确实同意,在这种情况下,while将更加明显。