gpt4 book ai didi

java - 仅允许使用 java 扫描仪进行双输入

转载 作者:行者123 更新时间:2023-12-02 09:20:38 25 4
gpt4 key购买 nike

import java.util.Scanner;
import java.io.*;
public class Positive {
public static void main (String args[]) {
double first;
Scanner scan = new Scanner(System.in);
System.out.print("Please enter first value" + "\n");
first= scan.nextDouble();

if (first>0.00) {
System.out.println("Please enter second value");
}
else if (first <0.00) {
first =-first;
System.out.println(first);
System.out.println("Please enter second value");

}

double second;
Scanner scaning = new Scanner(System.in);
second = scan.nextDouble();
if (first>second) {
System.out.println(first-second);
}
else if (second>first) {
System.out.println(second-first);
}
}
}

任务:如果该值为正,则请求第二个值。打印这两个数字之间的差,使差值始终为正。例如,如果第一个值为 10.3,第二个值为 4.1,则您将打印结果 6.2。如果第一个值为 3.8,第二个值为 13.4,您将打印结果 9.6。

If the first value read is negative, print its positive equivalent. For instance, if its value is –89.6 you should print 89.6.

If the first value is not a number, give appropriate error message (The standard error message from Java (e.g. “Exception in thread "main” ...”) does not count! Have a look at the Java API or Stack Overflow how to approach this).

其余代码运行正确,但我不知道如何在输入中仅包含 double 值

最佳答案

通过使用 Scanner::nextDouble 您将强制输入仅是 double ,但如果您要使用 Scanner::nextLine 那么您可以尝试转换为 double ,如果失败则打印消息

 Scanner scan = new Scanner(System.in);
System.out.println("Enter double");
String line = scan.nextLine();

double firstNum = 0.00;

try {
firstNum = Double.parseDouble(line);
}
catch (NumberFormatException e) {
System.err.println("Not a double");
}

另外,而不是做

if (first>second) {
System.out.println(first-second);
}
else if (second>first) {
System.out.println(second-first);
}

这样做会更容易

System.out.println (Math.abs(first - second));

而且您还应该删除此行,因为它没有必要,而且您甚至没有使用它

Scanner scaning = new Scanner(System.in);

关于java - 仅允许使用 java 扫描仪进行双输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58722144/

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