gpt4 book ai didi

java - 从同一行读取多个 INT

转载 作者:行者123 更新时间:2023-11-30 06:04:12 26 4
gpt4 key购买 nike

我是 Java 和编程新手。我在我正在学习的类(class)中遇到了一个问题,任何帮助将不胜感激。我们正在讨论 catch block ,程序需要读取同一行上的两个整数并将这两个整数相除。两个 catch block 除以零并且不输入数字。我遇到的问题是,我无法让程序正确读取两个整数输入。

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;
}

}

}

And this is the result

最佳答案

数组从 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]));

This question有更多详细信息。

关于java - 从同一行读取多个 INT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50064104/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com