2016-02-24 4 views
-2

Я разработал программу, которая проверяет, является ли строка, введенная пользователем палиндром или нет. Эта часть работает нормально, но я хотел бы, чтобы программа начиналась снова, если пользователь хочет ввести другую строку. Я смотрел на разных форумах и пробовал разные циклы, но я не могу заставить программу правильно повторять. В настоящее время у меня есть оператор do, и я думаю, что проблема связана с вызовом main(), поскольку он помечен как netbeans. Однако я не знаю, почему. Любая помощь или подталкивание в правильном направлении были бы оценены.Мне нужна помощь, чтобы моя программа повторялась

/* 
* This program checks to see if the user input is a palindrome. 
* white space and non alphanumeric characters will be ignored. 
*/ 
package firstsubroutines; 

/** 
* 
* @author anonymous 
*/ 

public class FirstSubroutines { 

    static String str; // global variable 
    static String reversed; // global variable 

/* 
* The subroutine strp accepts a string as an argument 
* and returns a string stripped of spaces and 
* non alphanumeric characters 
*/  
    static String strip(String str){ 
     str = str.replaceAll("[^a-zA-Z0-9]", ""); 
     str = str.toLowerCase(); 
     System.out.println("Stripped: " + str); 
     return str; 
    } // end of subroutine stripped 

/* 
* The subroutine reverse accepts a string as an argument 
* and returns a string in reverse order 
*/ 
    static String reverse(String str){ 
     int i; 
     reversed = ""; 
     for (i = str.length() - 1; i >= 0; i--) { 
      reversed = reversed + str.charAt(i); 
     } 
     System.out.println("Reversed: " + reversed); 
     return reversed; 
    } // end of subroutine reversed 

/* 
* This is the main progam where the subroutines 
* will be called 
*/ 
    public static void main(String[] args) { 
     String userInput; // The input by the user. 

     System.out.println("This program checks to see if the user's input is a palindrome."); 
     System.out.println("White space and non alphanumeric characters will be ignored."); 
     System.out.println(); 
     System.out.print("Please enter a string: "); 
     userInput = TextIO.getln(); // assigns the user input to a variable 

     // subroutine strip is called and an the value of 
     // the variable userInput is passed 
     str = strip(userInput); 

     // subroutine reverse is called and an the value of 
     // the variable str is passed 
     String rev = reverse(str); 

     // compares the two objects 
     if (str.equals(rev)) { 
      System.out.println("This IS a palindrome"); 
     } 
     else { 
      System.out.println("This NOT a palindrome"); 
     } // end of if statement 


     boolean toContinue; // True if user wants to play again. 
     do { 
      main(); 
      System.out.print("Do you want enter another string?: "); 
      toContinue = TextIO.getlnBoolean(); 
      } while (toContinue == true); 

    } // end main 

} // end class 
+0

Вы на самом деле вызывать метод public static void main (String [] args) в вашем цикле? – Stilleur

+0

Да. Разве это не то, что я должен делать? – robotsruin

+0

Вы не должны этого делать. Основной метод не следует вызывать :) см. Http://stackoverflow.com/questions/21992659/calling-main-method-inside-main-in-java. Я объясню вам, как это сделать по-другому. @Berger ответил на то, что я думал – Stilleur

ответ

3

Отдельные логики ваш вклад лечение другим способом:

private static void processString(){ 

     String userInput; // The input by the user. 

     System.out.println("This program checks to see if the user's input is a palindrome."); 
     System.out.println("White space and non alphanumeric characters will be ignored."); 
     System.out.println(); 
     System.out.print("Please enter a string: "); 
     userInput = TextIO.getln(); // assigns the user input to a variable 

     // subroutine strip is called and an the value of 
     // the variable userInput is passed 
     str = strip(userInput); 

     // subroutine reverse is called and an the value of 
     // the variable str is passed 
     String rev = reverse(str); 

     // compares the two objects 
     if (str.equals(rev)) { 
      System.out.println("This IS a palindrome"); 
     } 
     else { 
      System.out.println("This NOT a palindrome"); 
     } // end of if statement 


} 

Тогда просто вызовите его из main в цикле:

public static void main(String[] args) { 

     boolean toContinue = false; // True if user wants to play again. 
     do { 
      processString(); 
      System.out.print("Do you want enter another string?: "); 
      toContinue = TextIO.getlnBoolean(); 
      } 
     while (toContinue == true); 
} 
+1

Спасибо, что работал отлично, и я думаю, что я лучше понимаю, почему мой не работал. – robotsruin

0

Используйте Scanner класс:

Scanner sc = new Scanner(System.in); 

while (sc.hasNext()) { 
    String input = sc.next(); 
    // do something with input 
} 
+0

Спасибо за помощь – robotsruin

Смежные вопросы