2010-04-19 55 views
2

我的程序检查以测试一个单词或短语是否是回文(回读和反向读,前“racecar”)。我遇到的问题是在有人进入“赛车”后进行实际测试。在下面的代码中,我标记了如果我输入“racecar”并运行,Java返回正确的答案,所以我知道我就在那里。但是我将它输入到控制台中时缺少什么。我认为我的代码是好的,但也许我有一些缺失或错误的地方?没有真正寻找一个新的答案,除非我失去了一些东西,但如果可能的话,也许是专业人士将我的代码移动到正确的区域BC我卡住了!用户输入问题

import java.util.*; 

public class Palindrome { 

public static void main(String[] args) { 
    String myInput; 
    Scanner in = new Scanner(System.in); 

    System.out.println("Enter a word or phrase: "); **//this asks user for input but doesn't check for whether or not it is a palindrome** 
    myInput = in.nextLine(); 
    in.close(); 

    System.out.println("You entered: " + myInput); 
} 

{ 
    String s="racecar"; **//I can type a word here and it works but I need** 
    int i;    **//I need it to work where I ask for the input** 
    int n=s.length(); 
    String str=""; 

    for(i=n-1;i>=0;i--) 
     str=str+s.charAt(i); 

    if(str.equals(s)) 
     System.out.println(s+ " is a palindrome"); 

    else System.out.println(s+ " is not a palindrome"); } 

} 

我是编程新手,所以我希望我得到的是好的。我知道回文测试的作品,我只需要帮助它进行测试,直到我将它输入到控制台。谢谢

+1

请查看编辑帮助http://stackoverflow.com/editing-help,以便您可以更好地设置问题的格式。 – spender 2010-04-19 00:56:53

回答

1

一切看起来不错,但是您的for循环仍然显示您检查s是否是回文,而不是myInput

现在,您需要做的就是将s的每次出现都替换为myInput,然后检查程序是否正常工作。

作为单挑,您的程序将无法识别短语“Madam Im Adam”作为回文。

由于这是作业,识别短语(不更改代码)的一种可能方法是在字符串中删除空格(可以使用String#replaceAll),然后执行回文检查。

1

首先,您提供的代码不会编译;一边。 看起来你正在寻找的是“如何读取用户输入”

以下是你需要什么深入浅出的事:

import java.util.Scanner; 
... 
... 

Scanner in = new Scanner(System.in); 

// Reads a single line from the console 
// and stores into variable called "s" 
String s= in.nextLine(); 
in.close(); 

然后用你的代码进行检查“S”为paliandrome。

+0

如果您只需要读取一行代码,扫描程序就会过度使用......使用BufferedReader应该不那么耗费资源。 – 2010-04-19 02:17:29