2016-11-09 10 views
-1

私のプログラムに問題があります。
whileループで見られる鳥の数を保存し、プログラムが終了したときに最も鳥が見えるようにしたい。
if文に問題があります。
助けていただければ幸いです。あなたの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ステートメントの内部に入れてもよい