2015-12-08 150 views
0

如果扫描仪输入为负数,则不显示任何内容。 如果我输入-11,那么10,-10和-1应该是输出。为什么负循环输入在for循环中不起作用

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

你应该让F1和F2的整数,而不是混合双打和整数在计算中。你可以用双打来解决问题,例如1.00000000000001!= 1。虽然 – slipperyseal

+0

我不是说这是你的问题,但一直迭代到1000解决你的问题? – handris

回答

0

f1和f2的值小于-11。也许对于循环的边界会更好java.lang.Math.max(n1,n2)

1

您的扫描仪可以采取负数,它运作完美。你没有得到预期的输出,因为你的循环结束于n1是-11,所以循环没有达到(f1 * f2 == n2 & & 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