如何使用字符串标记器和缓冲区。

时间:2014-02-12 01:57:58

标签: java string parsing stringtokenizer stringbuffer

我正在开发一个程序来撤销电话号码,删除所有分隔符,并将其与原始号码进行比较,以确定它是否是回文。它还会将电话号码转换为带逗号的整数。我有几个问题。我收到错误,不知道为什么。此外,它不能正确地确定该号码是否是回文。任何帮助将不胜感激。

//Phone String Palindrome Conversions
//This program will turn a phone number around and check to see if it is a palindrome
//This program will remove all deasdspace and symbols from the phone number
//This program will reverse the string and compare it to the original
//This program will put a phone number in a long intiger format
import java.io.*;
import java.util.*;
import java.text.DecimalFormat;
public class DottinoN_palindrome
{
  public static void main (String [] args) throws IOException
{
    String phoneshort1;
    boolean pal;
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter your phone number");
String phone1=br.readLine();
phoneshort1 = spaceremover(phone1);
System.out.println(phoneshort1);
pal = palindrometest(phoneshort1);
System.out.println(pal);
if(pal = false)
{
  System.out.println("Your phone number is a palindrome!");
}
else if(pal = true)
  System.out.println("Your phone number is not a palendrome...");
numberformat(phoneshort1);

}
public static String spaceremover (String phone2)
{
String phoneshort = "";
StringTokenizer st = new StringTokenizer(phone2,"()- " ,false);
while(st.hasMoreTokens())
{
  phoneshort += st.nextToken();
}
return phoneshort;
}
public static boolean palindrometest (String phoneshort2)
{
boolean pal;
StringBuffer br = new StringBuffer(phoneshort2);
String phonebkwd = br.reverse().toString();
if(phonebkwd == phoneshort2)
{
  pal = true;
}
else pal = false;
System.out.println(phonebkwd + "--" + phoneshort2);
return pal;

}
public static void numberformat (String phoneshort2)
{
DecimalFormat formatter = new DecimalFormat("0,000,000,000");
int number = Integer.parseInt(phoneshort2);
System.out.println("Your phone number as an intiger is: " + formatter.format(number) );
}
}

3 个答案:

答案 0 :(得分:1)

您的计划确实存在一些问题,

  1. 如wipindipy10所说,用等方法改变字符串比较

  2. 如果打印的条件是否是回文,请改为

    if (!pal) {
        System.out.println("Your phone number is a palindrome!");
    } else {
        System.out.println("Your phone number is not a palendrome...");
    }
    
  3. 正如您所提到的那样,异常发生在底部附近。这可能是您输入的手机超过Integer.MAX_VALUE,即2147483647 [0x7fffffff]

答案 1 :(得分:0)

由于您正在比较字符串,请使用方法equals。

    if(phonebkwd == phoneshort2)

将其更改为

    if(phonebkwd.equals(phoneshort2))

另外,请指出您遇到的错误。

答案 2 :(得分:0)

代码中有很多错误。 对于字符串比较,请使用equals方法

if(phonebkwd.equals(phoneshort2))

以下if语句错误

if(pal = false)
{
  System.out.println("Your phone number is a palindrome!");
}
else if(pal = true)
  System.out.println("Your phone number is not a palendrome...");

你应该交换if,否则阻止。 Integer.parseInt(phoneshort2)的最后一个错误;似乎是你试图解析一个大于Integer.MAX_VALUE的数字