how to find a 'carriage return' and loop back to main until user enters a string

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • hopes
    New Member
    • Mar 2010
    • 1

    #1

    how to find a 'carriage return' and loop back to main until user enters a string

    excuse me, simple question
    I want a user to enter a string so that I may recursively call it to reverse it.
    Just one thing, i wanna make sure the user did not enter a carriage return, if he/she did, it will loop and ask them to enter a string again. Basically error prevention. So I tried a while (x=="\n") or "" or "\r" where x is my string..it did not do anything. BTW i am using Eclipse.
    So basically how can i do a loop in main that will keep asking user for a string and checking whether or not he enterd a "Enter"
    Thanks ahead of time.

    The prog:
    *************** *************** ****

    import java.io.*;
    import java.util.Scann er;
    public class stringreverse
    {

    public static void stringreversed( String s, int n)
    {
    if (n==0){
    System.out.prin t("you entered nada");
    return;}
    else{

    System.out.prin t(s.charAt(n-1));
    stringreversed( s,n-1);
    }
    }

    public static void main(String[] args)
    {
    Scanner scan = new Scanner(System. in);
    System.out.prin t("What do you want to reverse? ");
    int t;
    String x = scan.next();
    while (x !="")
    {
    t = x.length();

    stringreversed( x,t);
    }

    else
    System.out.prin t("You entered an empty string,try again");
    //want it to loop back to main here until a string is entered









    }
    }
  • jkmyoung
    Recognized Expert Top Contributor
    • Mar 2006
    • 2057

    #2
    use the nextLine() function if you're looking for line by line input as opposed to word by word input.

    scan.next(); will never return "" unless you have changed the input delimiters.

    Comment

    Working...