gpt4 book ai didi

java - java.length或我的整个程序出现问题

转载 作者:行者123 更新时间:2023-12-02 11:10:43 25 4
gpt4 key购买 nike

我在第56行的代码中出现错误。我正在尝试制作一个将句子转换为Pig Latin的程序。

谁能理解为什么此代码未运行?它已准备好进行编程。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.*;
public class PigLatin extends JFrame implements ActionListener {
JLabel lblInput, lblOutput;
TextField txtInput, txtOutput;
Button btnReverse, btnClear;
String Broken;

Container frame;

public PigLatin() {
frame = getContentPane();

setTitle("PigLatin"); // Set the frame's name

lblInput = new JLabel("Enter a phrase");
lblOutput = new JLabel("Pig Latinified");
txtInput = new TextField(50);
txtOutput = new TextField(50);

btnReverse = new Button("Reverse String");
btnClear = new Button("Clear");

frame.setLayout(new GridLayout(3, 2));

frame.add(lblInput);
frame.add(txtInput);
frame.add(lblOutput);
frame.add(txtOutput);
frame.add(btnReverse);
frame.add(btnClear);

btnReverse.addActionListener(this);
btnClear.addActionListener(this);

setSize(400, 300);
setVisible(true);

} // Constructor


public void actionPerformed(ActionEvent e) {

String DNC = "does not compute";

Broken = txtInput.getText();

String Inp[] = Broken.split(" ");
int N;

for (int i = 0; i < Inp[i].length(); i++) {
N = i;

char Q = Inp[N].charAt(0);
char Vowel = Inp[N].charAt(1);
if (Q == 'a' || Q == 'e' || Q == 'i' || Q == 'o' || Q == 'u') {
txtOutput.setText("" + Inp[N] + "way");
} else if (Q == 'q' && Vowel == 'u') {
String quay = Inp[N];
quay = quay.replaceAll("q", "");
quay = quay.replaceAll("u", "");

txtOutput.setText(quay + "quay");
} else if ((Q == 'q' != true) && (Vowel == 'u' != true)) {
String Reg = Inp[N];
Reg = Reg.replaceAll("" + Q, "");

txtOutput.setText(Reg + Q + "ay");
} else if (Inp[N] == " ") {
txtOutput.setText("" + DNC + "");
} else {
txtOutput.setText("" + Inp + "");
}
}
}


public static void main(String[] args) {
new PigLatin(); // Create a PigLatin frame
} // main method
} // PigLatin class

最佳答案

干得好:

我注意到了几件事:

  • 解决您的问题:我想您也有一个IndexOutOfBoundsException
    这与for循环中的条件一起出现。在您的语句中,在当前索引处遍历String的长度。这有点像在其主对角线上遍历矩阵。我猜你想遍历数组Inp中的所有元素

    因此,将您的声明更改为:
    for(int i = 0; i < Int.length; i++){
    //...
    }

    应该做的工作。
  • 有关if语句的简要说明:
    第二个} else if (Inp[N] == " ") {是不必要的,因为您已经在" "上拆分了输入String。因此,结果中不应剩下任何" "
  • 也请为defaultCloseOperation指定一个JFrame,以便您的程序正确停止。

  • 可能还有更多可以改进的地方。

    关于java - java.length或我的整个程序出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29544562/

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