如果扫描仪输入为负,则不显示任何内容。 如果我输入-11那么10,-10和-1应该是输出。
import java.util.Scanner;
public class Factor
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String replay = "replay";
while(replay.equals("replay"))
{
System.out.println("The numbers that add to be ___(number1)___ that multiply to be ___(number2)___ are...");
System.out.println("Enter number1:");
int n1 = scan.nextInt();
System.out.println("Enter number2:");
int n2 = scan.nextInt();
System.out.println("Computing...");
for(double f2 = -1000; f2 <= n1; f2++)
{
for(double f1 = -1000; f1 <= n1; f1++)
{
if(f1*f2 == n2 && f1+f2 == n1)
{
System.out.println(f1 + " and " + f2);
}
}
}
scan.nextLine();
System.out.println("Enter replay if you would like to compute again");
replay = scan.nextLine();
}
}
}
即使我的循环变量是负数。
答案 0 :(得分:1)
您的扫描仪可以使用负数,它运行正常。你没有得到预期的输出,因为你的循环结束于n1是-11,所以循环不会达到(f1 * f2 == n2&amp;&amp; f1 + f2 == n1)为真的点。如果你迭代,让我们说从-1000到1000,你将获得所需的输出。
此代码:
`import java.util.Scanner;
public class NegativeScanner{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String replay = "replay";
while(replay.equals("replay"))
{
System.out.println("The numbers that add to be ___(number1)___ that multiply to be ___(number2)___ are...");
System.out.println("Enter number1:");
int n1 = scan.nextInt(); //-11
System.out.println("Enter number2:");
int n2 = scan.nextInt(); // 10
System.out.println("Computing...");
for(double f2 = -1000; f2 <= 1000; f2++){ //-1000-től -11-ig
for(double f1 = -1000; f1 <= 1000; f1++){ //-1000-től -11-ig
if(f1*f2 == n2 && f1+f2 == n1)
{
System.out.println(f1 + " and " + f2);
}
}
}
scan.nextLine();
System.out.println("Enter replay if you would like to compute again");
replay = scan.nextLine();
}
}
}
产生此输出:
The numbers that add to be ___(number1)___ that multiply to be ___(number2)___ are...
Enter number1:
-11
Enter number2:
10
Computing...
-1.0 and -10.0
-10.0 and -1.0
Enter replay if you would like to compute again
答案 1 :(得分:0)
f1和f2的值小于-11。也许对于循环的边界会更好java.lang.Math.max(n1,n2)