gpt4 book ai didi

java - 无法获取文本字符串的值

转载 作者:行者123 更新时间:2023-11-29 03:31:16 26 4
gpt4 key购买 nike

我正在准备一个简单的系统作为我的作业,但我遇到了一个问题,我不知道如何getText String 的值。我知道如何用整数来做,但不知道如何用字符串来做。

如果我想获得一个整数值,我会在我的代码中使用 Integer.parseInt(t2.getText());我已经将我的代码添加到其中。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class tollRate extends JFrame implements ActionListener {

JLabel L1 = new JLabel("Please insert your origin (in capital letter)");
JTextField t1 = new JTextField(20);
JLabel L2 = new JLabel("Please insert your destination (in capital letter)");
JTextField t2 = new JTextField(20);
JLabel L3 = new JLabel("Your vehicle class");
JTextField t3 = new JTextField(1);
JButton b1 = new JButton("Calculate");
JButton b2 = new JButton("Exit");
JLabel L4 = new JLabel("Class 0 : Motorcycles, bicycles, or vehicles with "
+ "2 or less wheels" + "\nClass 1 : Vehicles wit 2 axles and 3 "
+ "or 4 wheels excluding taxis" + "\nClass 2 : Vehicles with 2 "
+ "axles and 5 or 6 wheels excluding busses" + "\n Class 3 : "
+ "Vehicles with 3 or more axles" + "\nClass 4 : Taxis"
+ "\nClass 5 : Buses");
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
JPanel p4 = new JPanel();
JPanel p5 = new JPanel();
String i, j, k;

tollRate() {
JFrame a = new JFrame();
setTitle("Highway Toll Rates System");
setSize(600, 400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(5, 2));
p1.setLayout(new GridLayout(1, 2));
p1.add(L1);
p1.add(t1);
p2.setLayout(new GridLayout(1, 2));
p2.add(L2);
p2.add(t2);
p3.setLayout(new GridLayout(1, 2));
p3.add(L3);
p3.add(t3);
p4.setLayout(new FlowLayout());
p4.add(b1);
p4.add(b2);
p5.setLayout(new FlowLayout());
p5.add(L4);
add(p1);
add(p2);
add(p3);
add(p4);
add(p5);
b1.addActionListener(this);
b2.addActionListener(this);
}

public void actionPerformed(ActionEvent a) {
Object source = a.getSource();
if (source == b2) {
this.dispose();
} else if (source == b1) {
i = Integer.parseInt(t1.getText());
j = Integer.parseInt(t2.getText());
k = Integer.parseInt(t3.getText());
}
}

public static void main(String[] args) {
tollRate a = new tollRate();
}
}

最佳答案

首先 String i, j, k;

     i = Integer.parseInt(t1.getText());
j = Integer.parseInt(t2.getText());
k = Integer.parseInt(t3.getText());

这是错误的。您正在为 int 分配字符串。先纠正他们。如果你想要 int 值,最好使用

int i, j, k; 并使用 trim() 来避免额外的空格。

     i = Integer.parseInt(t1.getText().trim());
j = Integer.parseInt(t2.getText().trim());
k = Integer.parseInt(t3.getText().trim());

在你的情况下使用如下

        i = t1.getText();
j = t2.getText();
k = t3.getText();

关于java - 无法获取文本字符串的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18181368/

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