gpt4 book ai didi

java - 循环和堆栈,回文家庭作业

转载 作者:搜寻专家 更新时间:2023-11-01 01:46:23 25 4
gpt4 key购买 nike

我正在为我的编程课做作业,但我遇到了一些困难,我不确定还能去哪里找。基本上,这个问题要求我们编写一个检查回文的程序。

  • 用户输入文本(不允许使用非字母数字字符。)
  • 字符串一次被压入一个字符栈
  • 字符一次从堆栈中取出一个,从而反转字符串
  • 如果正反相同,则有回文

虽然我的循环遇到了一些问题,但我不知道从哪里开始,有没有人有任何建议或指示?我做错了什么?

这是我目前所拥有的。

import java.util.Stack;
import java.util.regex.*;
import javax.swing.*;

public class Question1 {

static Stack PDrome = new Stack();

public static String Reverse (String input) {
String reverse;

if (input.length() <= 1) {
return input;
}

//pushing onto the stack
for (int i=0; i<input.length();i++) {
PDrome.push(input.charAt(i));
}


//popping from the stack into the string
for (int i=0; i<input.length(); i++) {
PDrome.pop()=reverse.charAt(i);
}

return reverse;
}

//Illegal char check method
public static boolean checker (String input) {
Pattern p = Pattern.compile("[^a-z0-9]", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(input);
boolean b = m.find();

if (b) {
System.out.println("There is a special character in your string");
System.exit(0);
}

return b;
}


//Main
public static void main (String [] args) {
//input
String input = JOptionPane.showInputDialog("Enter text to check if it's a palndrome");

//error case
if (input==null); {
System.out.println("Nothing Entered");
System.exit(0);
}

//checking for illegal chars
checker(input);
}
}

最佳答案

这部分:

String reverse;
...
//popping from the stack into the string
for (int i=0; i<input.length(); i++)
{
PDrome.pop()=reverse.charAt(i);
}

应该是这样的:

String reverse = "";
...
//popping from the stack into the string
for (int i=0; i<input.length(); i++)
{
// appends the popped character to reverse
reverse += PDrome.pop();
}

请注意,当追加大量字符串时,这不是最好的方法,因为 Java 的字符串是不可变的,并且重复追加一个字符串需要每次都创建一个新字符串。这个问题足够小,虽然并不重要,但当问题变大时,您将需要使用 StringBuffer/StringBuilder。

关于java - 循环和堆栈,回文家庭作业,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9004464/

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