【问题标题】:Understanding palindrome pseudocode理解回文伪代码
【发布时间】:2015-03-17 21:56:41
【问题描述】:

对于我的任务,我必须编写和测试一个 Java 程序以读取多个 输入行,直到读取空行。读完每一行后,我必须确定该行是否包含回文,如果确实包含回文,我必须打印它是哪种类型的回文(单词、短语或数字)。为了做回文部分,我必须使用伪代码。

伪代码为:

注意:以下符号代表赋值

左0

右字符串最后一个字符的位置

好的真的

虽然还好,但左

ch1  字符串中位置(左)的字符

如果 ch1 不是数字或字母

向左递增

其他

ch2  字符串中位置(右)的字符

如果 ch2 不是数字或字母

向右递减

其他

将ch1和ch2都转换为大写

如果 ch1 = ch2

向左递增

向右递减

其他

好的假

结束

结束

结束

结束

还行

到目前为止我所拥有的是:

import java.util.Scanner;
public class Project4
{
public static void main (String [] args)
{

    String line = getInputLine();
    while (!isEmptyLine (line))
    {
        if (isPalindrome (line))
            System.out.println ("\"" + line + "\" is a palindrome and a " + getPalType (line));
        else
            System.out.println ("\"" + line + "\" is not a palindrome");
        line = getInputLine();
    }
System.out.println ("End of program");
}

public static String getInputLine()
{
    System.out.println("Enter a line of input: ");
    Scanner in = new Scanner(System.in);
    String line = in.next();
    System.out.println(line);
    return line;
}

public static boolean isEmptyLine (String str)
{
    boolean isEmptyLine;

    if( str == null)
        isEmptyLine = true;
    else
        isEmptyLine = false;

    return true;
}

public static boolean isPalindrome (String str)
{
    Scanner word = new Scanner(System.in);
    String isPalindrome = word.next();
    int strLength = isPalindrome.length();

    while(true && 0 < isPalindrome.charAt(isPalindrome.length() -1))
    {

        if(Character.isDigit(strLength) || Character.isLetter(0))
        {

我还没有完成,但我需要帮助来了解如何使用伪代码。我不太明白第一个 if 语句部分。如果有人有时间解释代码,我将不胜感激。

【问题讨论】:

    标签: java pseudocode palindrome


    【解决方案1】:

    我发现理解此类伪代码的最佳方法是在开始编写任何代码之前使用一张纸来完成它。写出类似“abcdcba”的东西

    用你的左右食指跟踪左右变量。您将从左手手指在最左边的字符开始,右手从最后一个字符开始。现在只需逐步执行说明。

    基本思想是将左边的字符与右边的字符进行比较。如果相同,则向左向右移动一位,向右向左移动一位。重复。

    您将跳过所有非字母数字字符。字符也被转换为大写以避免区分大小写。

    如果在任何时候左边的字符与右边的字符不匹配,那么我们就没有回文。如果左右相遇,或互相超越,并且到目前为止一切都是匹配的,那么我们确实有一个。

    既然你问了第一个 if 语句,就知道 Java 的 Character 类提供了

    public static boolean isLetterOrDigit(char ch)
    

    你可以使用:

    if (! Character.isLetterOrDigit(ch1))  { ...
    

    附带说明,您的 isEmptyLine() 方法始终返回 true。整个方法应该重写为:

    public static boolean isEmptyLine(String str) {
        return (str == null);
    }
    

    就此而言,该方法可以完全删除,只需将您的 while 循环重写为:

    while(line != null)  {
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-13
      • 1970-01-01
      • 2014-04-23
      • 1970-01-01
      • 2012-07-20
      • 2016-02-28
      • 1970-01-01
      • 2014-09-23
      相关资源
      最近更新 更多