gpt4 book ai didi

java - 两个数字的基本加法

转载 作者:行者123 更新时间:2023-11-30 07:02:24 25 4
gpt4 key购买 nike

很抱歉问了一个简单的问题,但我是个初学者。所以问题是当我将以下代码复制到我的 eclipse 中时,它工作正常。但是当我将变量的类型从 int 更改为 double 时,它​​显示某种错误。请检查一下。

import java.util.Scanner;

class AddNumbers
{
public static void main(String args[])
{
double x, y, z;
System.out.println("Enter two integers to calculate their sum ");
Scanner in = new Scanner(System.in);
x = in.nextDouble();
y = in.nextDouble();
z = x + y;
System.out.println("Sum of entered integers = "+z);
}
}

顺便说一句,错误如下

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
at AddNumbers.main(AddNumbers.java:10)

这是我刚刚观看的视频教程(https://www.youtube.com/watch?v=ANuuSFY2BbY)我只是尝试复制它

import java.util.Scanner;

class HelloWorld{

public static void main(String args[]) {
Scanner bucky = new Scanner(System.in);
double fnum;
double snum;
double answer;
System.out.println("Enter first number:");
fnum = bucky.nextDouble();
System.out.println("Enter second number:");
snum = bucky.nextDouble();
answer = fnum+snum;
System.out.print(answer);
}

}

我收到以下错误:

Enter first number:
34.6
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
at HelloWorld.main(HelloWorld.java:11)

最佳答案

Answer

你看。我得到了正确的答案。所以你必须像他们所说的那样表现出你的想法。

您还可以像下面这样修改代码以使其更强大。

import java.util.InputMismatchException;
import java.util.Scanner;

class AddNumbers
{
public static void main(String args[])
{
double x, y, z;
System.out.println("Enter two double to calculate their sum ");
Scanner in = new Scanner(System.in);

while (true) {
try {
x = Double.parseDouble(in.nextLine());
y = Double.parseDouble(in.nextLine());
z = x + y;
System.out.println("Sum of entered double = " + z);
break;
} catch (Exception e) {
System.out.println("Not a double param, please enter again");
continue;
}
}

}

}

关于java - 两个数字的基本加法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40690169/

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