2016-09-18 2 views
0

Der Ausgang wird als 1913 auf den nächsten 52 Zeilen gedruckt. Wie bekomme ich es die nächste Nummer zu laden und zu prüfen, ob das Prime ist. Wenn ich sage, dass es gedruckt werden soll, nachdem ich es analysiert habe, werden alle Zahlen extrahiert und fein angezeigt.Warum lädt das Programm nicht den nächsten Wert, Endlosschleife

Ich weiß, es ist ein logischer Fehler, weil ich denke, dass ich meine Schleifen falsch

Scanner INPUT_TEXT = new Scanner(new File("C:\\Users\\josep\\Downloads\\assignment2.csv")); //Create a Scanner Class and File Class to read a file from your computer. 

INPUT_TEXT.useDelimiter(" "); //Divide DemoData.txt into several pieces by a space 

while (INPUT_TEXT.hasNext()) { 
    //Read each word 
    String TempString = INPUT_TEXT.next(); 

    //Display all numbers.Eliminate comma, e.g., 1,200 -> 1200 
    String temp1 = TempString.replaceAll("[\\,]", ""); //Create a String class temp1 that eliminates comma. 
    String pattern1 = "[0-9]+"; //Create a String class pattern1 that stores the Regular Expression to match numbers. 
    Pattern r1 = Pattern.compile(pattern1); //Create Pattern class to compile pattern1. 
    Matcher m1 = r1.matcher(temp1); //Match each piece with the Regular Expression 

    if (m1.find()) { //If a number is matched, print the number. 
     int foo = Integer.parseInt(m1.group(0)); 
     result = foo; 

     while (limit > 0) { 

      //Assume the number if prime 
      boolean isPrime = true; //Is the current number prime? 

      // Test whether number is prime 
      for (int divisor = 2; divisor <= foo/2; divisor++) { 

       if (foo % divisor == 0) { //If true, number is not prime 
        isPrime = false; //Set isPrime to false 
        break; // Exit the for loop 
       } 
      } 
      if (isPrime) { 
       System.out.println(result); 
      } 
      limit--; 
     } 
    } 
} 

Antwort

0

Verwenden while(m1.find()) statt if(m1.find()) mit einigen Verbesserungen schreibe:

while(m1.find()){ 
    result = Integer.parseInt(m1.group()); 

    //result not prime 
    if(!(result % 2 == 0)){ 
     System.out.println(result); 
    } 
} 

Ich weiß nicht, was Ihre Variable limit wird für so verwendet, ich habe es weggelassen, aber fühle mich frei, es dort zu platzieren, wo es hingehört.

Verwandte Themen