我的老师希望我们制作一个使用Scanner添加数字的代码。我们还应确定答案是正确还是错误。但我不能使用break和if-else语句,因为我被告知不要使用它。所以,我的代码中的问题是,当我输入数字并输入它们的总和时(当我输错了答案时),如果我的答案大于实数总和,我输入的总和将被减去实数总和。当我的回答小于实际总和时,输出是无限的。我已经做了我能做的事。先感谢您。
package additionwhileloop;
import java.util.*;
public class AdditionWhileLoop {
public static void main(String[] args) {
Scanner program = new Scanner(System.in);
int a, b, c, sum;
System.out.println("Enter the first value:");
a = program.nextInt();
System.out.println("Enter the second value:");
b = program.nextInt();
System.out.println("The sum of two numbers is: ");
c = program.nextInt();
sum = a + b;
while(sum == c){
sum++;
System.out.println("Your answer is correct.");
}
sum = a + b;
while(sum != c){
sum++;
System.out.println("Your answer is wrong.");
}
c = a + b;
System.out.println("The sum of entered numbers is " + c);
}
}
答案 0 :(得分:3)
你的代码无限循环" (但在技术上,并非真的)因为:
while(sum != c){
sum++;
System.out.println("Your answer is wrong.");
}
你继续递增sum
,但如果它已超过预期值,它将继续计数到无穷大。 (实际上,它实际上会导致整数溢出,并从负数开始计数,并在很长一段时间后最终达到正确的值)
你想做的是"假的"一个正确的答案,所以while循环可以在一次迭代后终止:
while(sum != c){
sum = c; // while loop condition will be false next time
System.out.println("Your answer is wrong.");
}
不要担心,如果你没有真正理解这一点。这是一项糟糕的任务,通常没有人会编写这样的代码。
答案 1 :(得分:0)
虽然我个人认为这项任务非常愚蠢,但这是一个可以解决你问题的代码......
// Read values for a, b and c first.
// Save a backup of c
c2 = c;
// subtract a and b from c.
c -= a;
c -= b;
// Check if c is 0
while (c == 0)
{
// In that case make sure we break the loop
c++;
// Also print something nice.
System.out.println("Correct result");
}
// Do the same again with our backup value
c2 -= a;
c2 -= b;
// Check if it is not 0 (so wrong result)
while (c2 != 0)
{
// Set it to 0 to break.
c2 = 0;
// Print something nice.
System.out.println("Incorrect result");
}
答案 2 :(得分:0)
我在java方面也没有多少经验,但想分享输入。由于你的问题不是很明确,所以根据我的理解,我能够到达这里:
import java.util.*;
public class AdditionWhileLoop {
public static void main(String[] args) {
Scanner program = new Scanner(System.in);
int a, b, c, sum;
System.out.println("Enter the first value:");
a = program.nextInt();
System.out.println("Enter the second value:");
b = program.nextInt();
System.out.println("The sum of two numbers is: ");
c = program.nextInt();
sum = a + b;
while(sum == c){
sum++;
System.out.println("Your answer is correct.");
}
sum = a + b;
int temp = c-sum;
int result = (temp==0)?sum:(temp>0)?negate(sum,c):add(sum,c);
System.out.println("The sum of entered numbers is " + sum);
}
static int negate(int sum, int c){
System.out.println("Your answer is wrong.");
while(sum != c){
sum++;
}
return sum;
}
static int add(int sum, int c){
System.out.println("Your answer is wrong.");
while(sum != c){
sum--;
}
return sum;
}
}
如果这个答案请告诉我。
答案 3 :(得分:-1)
三元运算符怎么样:
int x=10;
int y=25;
int z =36;
System.out.println("Sum is:" + (((x+y)==z) ? "valid" : "invalid"));
OR
使用布尔变量作为标志。将标志初始化为true。如果sum是正确的(在你的第一次内部),将flag设置为false。在你的第二个时候添加&& flag
,然后在其中将flag设置为false。