已关闭此问题为not reproducible or was caused by typos。它目前不接受回答。
此问题是由打印错误或无法再重现的问题引起的。虽然类似的问题可能是on-topic在这里,这一个是解决的方式不太可能帮助未来的读者。
2天前关闭。
Improve this question
我只是使用Double.parseDouble和JOptionPane将一个String解析为一个double,请求用户输入。例如,当输入为2时,它只返回20。
下面是我的代码:
import java.util.ArrayList;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
ArrayList<String> hermanas_nombres = new ArrayList<String>();
ArrayList<Double> hermanas_edades = new ArrayList<Double>();
for (int i = 0; i <=1 ; i++) {
var nombre = JOptionPane.showInputDialog("Introduce el nombre de la hermana n " + i);
hermanas_nombres.add(nombre);
double edad = Double.parseDouble(JOptionPane.showInputDialog("Introduce la edad de la hermana ") + i);
hermanas_edades.add(edad);
}
double media = ((hermanas_edades.get(0) + hermanas_edades.get(1))/2) ;
for (int i = 0; i <=1 ; i++) {
System.out.println("Nombre hermana número "+i+ " "+ hermanas_nombres.get(i));
System.out.println("Edad hermana número "+i+ " "+ hermanas_edades.get(i));
}
System.out.println("Media de las edades: " + media);
}
}
正如您所看到的,当使用JOption面板询问“edad”并将其添加到arraylist时,它只会向用户输入添加一个额外的0。
1条答案
按热度按时间ymdaylpp1#
我怀疑错误是由于
+ i
在这一行的位置:此时,您正在将
i
添加到JOptionPane.showInputDialog
返回的值中。假设您输入6
以响应输入对话框中的消息Introduce la edad de la hermana
。Java将执行以下代码:如果
i
为零,则"6" + i
是字符串"60"
,因为您正在执行字符串连接,而不是数字加法。这会导致edad
的值在末尾多出一个零。我认为您希望将
i
添加到JOptionPane
中显示的消息的末尾,而不是showInputDialog
方法返回的消息。尝试将+ i
移动到行尾两个)
字符中第一个字符的左侧: