开发者

Taking User Input in Java

I'm creating a program that checks if a word or phrase is a palindrome. I have the actual "palindrome tester" figured out. What I'm stuck with is where and what to place in my code to have the console read out "Enter palindrome..." and then text. I've tried with IO but it doesnt work out right. Also, how do I create a loop to keep going? This code only allows one at a time `public class Palindrome {

public static void main(String args[]) {  
  String s="";  
  int i;  
  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+ 开发者_如何学JAVA" is not a palindrome"); }

}


To read in the text, you'll need to make use of the Scanner class, for example:

import java.util.*;

public class MyConsoleInput {

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

        System.out.println("Enter some data: ");
        myInput = in.nextLine();
        in.close();

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

Apply this concept before you actually do a palindrome check, and you're sorted on that front.

As for looping over to allow multiple checks, you can do something like provide a keyword (such as "exit") and then do something like:

do {
    //...
} while (!myInput.equals("exit"));

With your relevant code in the middle, obviously.


Not a real answer since it's already given (hence CW), but I couldn't resist (re)writing the isPalindrome() method ;)

public static boolean isPalindrome(String s) {
    return new StringBuilder(s).reverse().toString().equals(s);
}


Another common idiom is to wrap your test in a method:

private static boolean isPalindrome(String s) {
    ...
    return str.equals(s);
}

Then filter standard input, calling isPalindrome() for each line:

public static void main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String s;
    while ((s = in.readLine()) != null) {
        System.out.println(isPalindrome(s) + ": " + s );
    }
}

This makes it easy to check a single line:

echo "madamimadam" | java MyClass

or a whole file:

java MyClass < /usr/share/dict/words
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜