【问题标题】:Checking characters in an array to build palindrome list检查数组中的字符以构建回文列表
【发布时间】:2014-11-26 21:39:17
【问题描述】:

我需要创建一个数组,并用 25 个 5 位回文数填充它。我为先前的分配创建了一个方法,该方法使用 for 循环将其反向输出。对于这个,我想在数组中做这一切,学习新的东西。我发现this code 可以通过添加两个字符生成 00000 - 99999,并将所有范围设为 0 - 9。完整代码请参见帖子底部。

char[] digit1 = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

为了澄清,在 main() 中使用了 digit1,如下所示:

char[] digit1 = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
char[] digit2 = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
char[] digit3 = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
char[] digit4 = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
char[] digit5 = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

char[][] arrs = {digit1, digit2, digit3, digit4, digit5};
int[] inds = new int[5];

我尝试将 printIndices 方法的输出部分转换为字符串,认为我可以使用 charAt 或 StringBuilder.reverse()。现在我有这个:

String output = String.valueOf(arrs[i][inds[i]]);
System.out.print(output);

效果很好,但如果我尝试这样做:

String palindrome = new StringBuilder(output).reverse().toString();
System.out.print(palindrome); 

我得到与以前完全相同的字符 - 我是否正确地认为如果使用该方法反转 00001,结果将是 10000?

如果我使用 charAt:

char output1 = output.charAt(1);
System.out.print(output1);

对于 charAt(0) 以外的任何值,我都会收到以下错误:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.charAt(String.java:646)
at PalindromeArray.printIndices(PalindromeArray.java:31)
at PalindromeArray.main(PalindromeArray.java:51)
Java Result: 1

如果我使用 charAt(0),它会打印所有数字,这让我认为它们没有被视为可以分开的单个字符,因此如果我尝试访问第一个之后的任何内容,则会出现错误一个。

public class PalindromeArray

{
    static char[] digit1 = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
    static char[] digit2 = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
    static char[] digit3 = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
    static char[] digit4 = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
    static char[] digit5 = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

static boolean incrementIndices(char[][] arrs, int[] inds) 
{
int n = arrs.length;
for(int i = n - 1; i >= 0; i--) 
{
    if(inds[i] < arrs[i].length - 1) 
    {
        inds[i]++;
        return true;
    }
    inds[i] = 0;
}
return false; // could not increment further
}

static void printIndices(char[][] arrs, int[] inds) 
{
int n = arrs.length;
for(int i = 0; i < n; i++) 
{

    String output = String.valueOf(arrs[i][inds[i]]);

    for(char c1: digit1)
{
    for(char c2: digit1)
    {
        for(char c3: digit1)
        {
            for(char c4: digit1)
            {
                for(char c5: digit1)
                {
                    String tempCheck = ""+c1+c2+c3+c4+c5;
                    if(isPalindrome(tempCheck))
                    {
                        System.out.println(tempCheck);
                    }
                }
            }
        }
    }
}

    System.out.print(output);


}
System.out.println();
}

public static boolean isPalindrome(String str)
{
String opposite = "";
for(int a = str.length()-1; a > 0; a++)
{
    opposite += str.charAt(a);
}
return opposite.equals(str); 
}

public static void main(String[] args)
{


    char[][] arrs = {digit1, digit2, digit3, digit4, digit5};
    int[] inds = new int[5];

    do 
    {
        printIndices(arrs, inds);
    } 
    while(incrementIndices(arrs, inds));
 }

}

【问题讨论】:

  • 如果在尝试使用charAt(1) 访问它的第二个字符之前打印output,你会得到什么?
  • 看了你的问题我有点迷茫......无法理解你的问题,你定义了digit1数组,但从未使用过,谁知道arrs, inds ...是什么你的最终目标是什么?生成一个包含 25 个 5 位回文数的数组?哪 25 个数字重要吗?
  • 添加了对 digit1... 部分的说明。 @OlaviMustanoja,我得到“0”,然后是前面提到的 StringIndexOutOfBoundsException。什么数字无关紧要。我想生成一个列表,然后从中随机挑选一些。最终目标是这样做,然后找出哪些是奇数,哪些是偶数。我之前使用过一个我刚刚填充数字的数组;取数的模2,如果等于0,则为奇数。

标签: java arrays palindrome


【解决方案1】:
/*
Project Name: PalindromeLab
Programmer: Jack
Class: Computer Science
Date: 10/14/16
Description: Simple Palindrome Programm
*/
import java.util.Scanner;

public class NewPalindromeLab
{ 
   public static void main(String[] args)
   {
      Scanner input = new Scanner(System.in);
      System.out.println("Welcome to Palindrome Converter");
      System.out.print("Enter in what you want Palindromeinated ==> ");
      String palin = input.nextLine();
      System.out.println("The origional was: " + palin);

      palin = palin.toLowerCase();

      int length = palin.length();

      char[] tempCharArray = new char[length];
      char[] charArray = new char[length];

      for(int i=0; i<length; i++)
      {
         tempCharArray[i] = palin.charAt(i);
      } 

      for(int k=0; k<length; k++)
      {
         charArray[k] = tempCharArray[length - 1 - k];
      }

      String reversePalin = new String (charArray);
      String reverseNewPalin = "";
      reverseNewPalin = reversePalin.replaceAll("[^A-Za-z0-9]", "");

      System.out.println("The reversed word is: " + reverseNewPalin);

      if (reversePalin.equals(palin))
      {
         System.out.println("This is a palindrome!");
      }
      else      
      {
         System.out.println("This is not a palindrome!");
      }
   }
}

/*
The following is the Output of the program:
Welcome to Palindrome Converter
Enter in what you want Palindromeinated ==>  Hello
The origional was:  Hello
The reversed word is: olleh
This is not a palindrome!
*/

【讨论】:

    【解决方案2】:

    你总是可以创建一个类似的方法

    public static boolean isPalindrome(String str)
    {
        String opposite = "";
        for(int a = str.length()-1;a>0;a++)
        {
            opposite+=str.charAt(a);
        }
        return opposite.equals(str);
    }
    

    编辑:我将编写实现它的方法。

        for(char c1: digit1)
        {
            for(char c2: digit1)
            {
                for(char c3: digit1)
                {
                    for(char c4: digit1)
                    {
                        for(char c5: digit1)
                        {
                            String tempCheck = ""+c1+c2+c3+c4+c5;
                            if(isPalindrome(tempCheck))
                            {
                                System.out.println(tempCheck);
                            }
                        }
                    }
                }
            }
        }
    

    【讨论】:

    • 我把它作为一个方法添加进去,然后这个位到 printIndices() 中:String output = String.valueOf(arrs[i][inds[i]]);isPalindrome(output);if (isPalindrome(output)){System.out.print(output);} 结果是没有输出。如果我将布尔值更改为假,我会得到所有的数字。
    • 所以,这对 digit1 的每个字符运行一个 for-each,是吗?我现在得到的字符串索引超出范围:5,引用此行:opposite += str.charAt(a);
    • 你能告诉我你的整个代码吗?试图认识到你的问题有点困难。
    • 添加在帖子底部。最初,digit1...digit5 变量是 main() 的本地变量,由于您的方法引用了它们,我将它们设为全局变量。
    【解决方案3】:

    我最终完全放弃了代码并走上了不同的路线。从有人在做相同练习的 Java 论坛中借用一部分,使用随机数生成器对其进行改进,使要填充的整数范围对项目有意义,并添加计数器来计算回文数的总数。

    感谢所有做出贡献的人 - 我学到了很多关于什么可以做和不可以做的事情。

    import java.util.Random;
    public class PalindromeArray
    {
    static void arrayFill()
    {
      int evens = 0, odds = 0;
      int []palindrome = new int [25];
      int j = 0;
      for(int i = 10001; i < 100000; i++) //Start our counter at the first 5-digit palindrome
      {
        String s1 = Integer.toString(i);
        StringBuilder sb = new StringBuilder(s1); //Strings enables us to use sb.reverse for a quick and easy check
        if(s1.equals(sb.reverse().toString()))
        {
            Random r = new Random(); //PRNG so the same numbers don't come up every time
            i = r.nextInt((99999 - 10001) + 1) + 10001; //Ensure generated seed is in desired range
            palindrome[j++] = i;
            if(j == 25)
            {
                break;
            }
        }
      }
    
      for(int i = 0; i < 25; i++)
      {
        if(palindrome[i]%2 == 0)
        {
            System.out.println("The palindrome at subscript " + i + " = " + palindrome[i] + " --> even");
            evens++;
        }
        else
        {
            System.out.println("The palindrome at subscript " + i + " = " + palindrome[i] + " --> odd");
            odds++;
        }
      }
    
      System.out.println("\nThe total number of even palindromes is " + evens);
      System.out.println("\nThe total number of odd palindromes is " + odds);
    }
    
    public static void main(String[] args)
    {
       arrayFill();
    }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-25
      • 1970-01-01
      • 2015-09-22
      • 2021-12-03
      相关资源
      最近更新 更多