java - 从同一行读取多个 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;
}
}
}
解决方案
数组从 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]));
还要注意整数除法轮次。因此,从您发布的示例中,除以的结果10
将20
是0
。这可能不是您想要的,因为您使用的是术语比率。要获得真实的比率,您需要将其中一个数字转换为double
. 上面的行然后变成
System.out.println("The ratio r is: "+((double) numbers[0]/numbers[1]));
这个问题有更多细节。
推荐阅读
- r - 当我尝试使用 RStudio 在 jmvtools 中创建模块时出错
- amazon-web-services - 如何通过 SSH 访问我的实例编写 boto3 代码
- flutter - 在颤动中将位置数据导出到csv
- keras - 我可以在 keras 中使用“经典”ml 模型吗?
- android - 此应用程序不能树摇图标字体。android部署的Flutter构建错误
- postgresql - 找出年份的差异
- java - 有没有办法用 Spring Cloud Gateway 调用 2 个微服务?
- javascript - 每次调用 JS 函数时如何生成一个新的 HTML 元素
- javascript - 如何在 Tslint ot tsconfig 中禁用深度导入?
- angular - 如何访问 Angular Material Data-Table 中同一行的不同单元格中的单元格的值?