不断收到错误

时间:2014-03-24 00:45:56

标签: java palindrome

为什么我一直在" int numLength = palNum1.length();?"我试图完成这个实验室,我正在为我的java类做,我坚持这一部分。任何帮助将不胜感激。

import java.util.*;
public class Lab6
{
    public static void main (String [] args)
    {
      String pal1, pal2="";
      int palNum1, palNum2, choice;
      Scanner in = new Scanner(System.in);

      System.out.println("Word(w) or Number(n)?");
      choice = in.nextLine().charAt(0);

      if (choice == 'w') {

          System.out.println("Enter a word: ");
          pal1= in.nextLine();

          int length = pal1.length();


          for ( int i = length - 1 ; i >= 0 ; i-- )
            pal2 = pal2 + pal1.charAt(i);


         if (pal1.equals(pal2))
            System.out.println("The word you entered is a palindrome.");
         else
            System.out.println("The word you entered is not a palindrome.");
        }
      else{

          System.out.println("Enter a bunch of numbers: ");
          palNum1 = in.nextInt();

          int numLength = palNum1.length();


          for ( int j = numLength - 1 ; j >= 0 ; j-- )
            palNum2 = palNum2 + palNum1.charAt(j);

         if (palNum1.equals(palNum2))
            System.out.println("The numbers you entered is a palindrome.");
         else
            System.out.println("The numbers you entered is not a palindrome.");
        }
    }
}

1 个答案:

答案 0 :(得分:0)

正如dasblink所说,原始类型没有方法。 鉴于你输入一个整数时你想要做什么,你应该把它转换成一个字符串,然后基本上重复第一部分的代码。而不是:

      System.out.println("Enter a bunch of numbers: ");
      palNum1 = in.nextInt();

      int numLength = palNum1.length();

      for ( int j = numLength - 1 ; j >= 0 ; j-- )
        palNum2 = palNum2 + palNum1.charAt(j);

简单的做法是将他们输入的int转换为String,然后重复以前的代码:

      System.out.println("Enter a bunch of numbers: ");
      palNum1 = in.nextInt();
      // Conver it to String to allow you to easily check if its a palindrome.
      pal1 = Integer.parseInt(palNum1);

      int numLength = pal1.length();

      for ( int j = numLength - 1 ; j >= 0 ; j-- )
        pal2 = pal2 + pal1.charAt(j);

永远不需要palNum2。

编辑: 对不起,如果我弄糊涂了你,我的意思是你在回文中读作一个int(和你原来的一样),但是你把它转换成一个String,然后像以前一样对待它。 else的完整代码:

  else{
      // If you are here, user is entering an int.
      System.out.println("Enter a bunch of numbers: ");
      palNum1 = in.nextInt();
      pal1 = Integer.parseInt(palNum1);

      int numLength = pal1.length();

      for ( int j = numLength - 1 ; j >= 0 ; j-- )
        pal2 = pal2 + pal1.charAt(j);

     if (pa1.equals(pal2))
        System.out.println("The numbers you entered is a palindrome.");
     else
        System.out.println("The numbers you entered is not a palindrome.");
    }