有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么负输入不能在for循环中工作

如果扫描仪输入为负数,则不会显示任何内容。 如果我输入-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();
        }

    }
}    

即使我的循环变量是负数


共 (1) 个答案

  1. # 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