gpt4 book ai didi

java - 如何获取用户输入的 double 值,然后用它执行计算

转载 作者:行者123 更新时间:2023-12-01 09:22:37 25 4
gpt4 key购买 nike

我正在 Java eclipse windowbuilder 中创建一个小程序。用户输入不等式语句的左侧(LHS)和右侧(RHS),使得LHS < (m/n) < RHS。程序将输出满足条件的最小整数值m和n。我有执行此操作所需的逻辑/代码,但我不确定如何在 windowbuilder 中获取 LHS 和 RHS 的用户值。左侧的文本字段称为 lhs,右侧的文本字段称为 rhs,如下图所示。如何获取用户的输入(作为双数据类型)?当用户输入这两个值时,我会将代码逻辑放在actionPerformed下。谢谢!

JButton btnCompute = new JButton("Compute");
btnCompute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}

enter image description here

 package ntheory;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class Ntheory {

private JFrame frame;
private JTextField lhs;
private JTextField rhs;

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Ntheory window = new Ntheory();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the application.
*/
public Ntheory() {
initialize();
}

/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);

lhs = new JTextField();
lhs.setBounds(6, 46, 68, 26);
frame.getContentPane().add(lhs);
lhs.setColumns(10);

JLabel label = new JLabel("<");
label.setBounds(86, 51, 10, 16);
frame.getContentPane().add(label);

JLabel label_1 = new JLabel("<");
label_1.setBounds(159, 51, 10, 16);
frame.getContentPane().add(label_1);

rhs = new JTextField();
rhs.setColumns(10);
rhs.setBounds(181, 46, 68, 26);
frame.getContentPane().add(rhs);

JLabel lblmn = new JLabel("(m/n)");
lblmn.setBounds(108, 51, 61, 16);
frame.getContentPane().add(lblmn);

JButton btnCompute = new JButton("Compute");
btnCompute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnCompute.setBounds(261, 46, 117, 29);
frame.getContentPane().add(btnCompute);
}
}

最佳答案

JButton btnCompute = new JButton("Compute");
btnCompute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
double leftValue = Double.parseDouble(lhs.getText());
double rightValue = Double.parseDouble(rhs.getText());
// Do your stuff with it.
}
catch ( NumberFormatException ex ) {
// Do stuff if the input is not a number.
}
}
}

关于java - 如何获取用户输入的 double 值,然后用它执行计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40068703/

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