首页 > 解决方案 > 从同一行读取多个 INT

问题描述

我是新的 Java 和一般编程。我在我正在学习的课程中遇到了一个问题,我们将不胜感激。我们正在讨论 catch 块,程序需要读取同一行上的两个整数并将两者相除。两个 catch 块被零除,而不是输入数字。我遇到的问题是,我无法让程序正确读取两个整数输入。

package chapter9problem2;

import java.util.Scanner;

public class Chapter9Problem2 {


    public static void main(String[] args) {


        Scanner keyboard = new Scanner(System.in);

        boolean done = false;

        while (!done)
        {

            try{

                System.out.println("Enter two numbers. Please leave a space between the numbers. I will compute the ratio.");
                String input = keyboard.nextLine();
                String[] numbersStr = input.split(" ");
                int[] numbers = new int[ numbersStr.length ];

                for ( int i = 0; i < numbersStr.length; i++ )
                {
                    numbers[i] = Integer.parseInt( numbersStr[i] );
                }


                System.out.println("");
                System.out.println("The ratio r is: "+(numbers[1]/numbers[2]));
            }
            catch (ArithmeticException e)
            {
                System.out.println("There was an exception: Divide by zero... Try again.");
            }
            catch (Exception e) {

                System.out.println("You must enter an Integer. ");
            }
            continue;
        }

    }

}

这就是结果

标签: java

解决方案


数组从 0 开始索引,而不是 1。因此,要获取数组的第一个元素,您必须访问元素 0(numbers[0]在您的情况下)。因此这条线

System.out.println("The ratio r is: "+(numbers[1]/numbers[2]));

应该读

System.out.println("The ratio r is: "+(numbers[0]/numbers[1]));

还要注意整数除法轮次。因此,从您发布的示例中,除以的结果10200。这可能不是您想要的,因为您使用的是术语比率。要获得真实的比率,您需要将其中一个数字转换为double. 上面的行然后变成

System.out.println("The ratio r is: "+((double) numbers[0]/numbers[1]));

这个问题有更多细节。


推荐阅读