-1

내 프로그램에 문제가 있습니다.
while 루프에서 보이는 새의 수를 저장하고 프로그램 종료시 가장 많이 보이는 새를 인쇄하고 싶습니다.
if 문에 문제가 있습니다.
도움이 될 것입니다. 의Java While 루프 문제 (신규)

import java.util.*; 

class gardenbird 
{ 
    public static void main(String[] main) 
    { 
     askbird(); 
     System.exit(0); 
    }// END MAIN METHOD 

    public static void askbird() 
    { 
     final int sentinel = -1; 
     int mostseen = 0; 
     int howmany = 0; 

     print("When you want to end the program type in "+sentinel); 

     while(howmany != sentinel) 
     { Scanner scanner = new Scanner(System.in); 
      print("Which bird have you seen?"); 
      String bird = scanner.nextLine(); 
      howmany = input("How many where in your garden at once?"); 

      if(howmany>mostseen) 
      { 
       howmany = mostseen; 
      } 
      print("You saw " + howmany+ " " + bird +"\n It was the most common bird in your garden."); 
     } 
    } 

    public static String print(String message) 
    {  
     System.out.println(message); 
     return message; 
    } 

    public static int input(String count) 
    { 
     Scanner scanner = new Scanner(System.in); 
     print(count); 
     String number1=scanner.nextLine(); 

     int number = Integer.parseInt(number1); 
     return number; 
    } 
} 
+3

'howmany = mostseen'은'mostseen = howmany'이어야합니다. – JimmyB

+2

새로운 Scanner 인스턴스를 과도하게 사용하는 것을 다시 생각해보십시오. – Fildor

답변

1

다른 사람들은 블록 교체가 거꾸로되었는지를 지적했습니다.

System.out.println()을 수행 할 유틸리티 메서드를 만드는 것은 과도한 캡슐화입니다.

개체를 여러 번 만들면 시스템 리소스가 낭비되고 코드를 읽기가 어려워 지지만 올바르게 작동합니다.

비교하고 대조하십시오.

import java.util.Scanner; 

public class GardenBird 
{ 
    public static void main(String[] main) 
    { 
    askbird(); 
    System.exit(0); 
    }// END MAIN METHOD 

    public static void askbird() 
    { 
    Scanner scanner = new Scanner(System.in); 
    final int sentinel = -1; 
    int mostseen = 0; 
    int howmany = 0; 
    String mostSeenBird = ""; 
    String currentBird = ""; 

    System.out.println("When you want to end the program type in " + sentinel); 

    while (howmany != sentinel) 
    { 
     System.out.println("Which bird have you seen?"); 
     currentBird = scanner.nextLine(); 
     System.out.println("How many where in your garden at once?"); 
     howmany = Integer.parseInt(scanner.nextLine()); 

     if (howmany > mostseen) 
     { 
     mostseen = howmany; 
     mostSeenBird = currentBird; 
     } 
    } 
    System.out.println("You saw " + howmany + " " + mostSeenBird 
     + "\n It was the most common bird in your garden."); 
    scanner.close(); 
    } 
} 
1

내용 명세서 뒤로하고,이 시도하는 경우 : 또한

if(howmany > mostseen) 
{ 
    mostseen = howmany; 
} 

,

print("You saw " + mostseen + " " + bird +"\n It was the most common bird in your garden."); 
아마도 동안의 외출해야

? 그렇게하면 사용자는 새로운 항목을 만들 때마다 대신 사용자에게 종료 사실만을 알려줍니다. 루프에서 벗어날 수있는 디자인은 실제로 없지만 문제는 진술 한 것입니다. 또는 if 문 안에 넣을 수 있으므로 조건이 참일 때만 인쇄됩니다.