2010-04-19 57 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