2016-10-06 7 views
3

- 私はこのプログラムは二つの整数で読み込み、STDINをフィルタリングするためにそれらを使用することになっているので、番号をフィルタリングするJava

public class Filter { 
public static void main(String[] args) { 

// read in two command-line arguments 
    int a = Integer.parseInt(args[0]); 
    int b = Integer.parseInt(args[1]); 

    // repeat as long as there's more input to read in 
    while (!StdIn.isEmpty()) { 

     // read in the next integer 
     int t = StdIn.readInt(); 


     if (????) { 
      StdOut.print(t + " "); 
     } 
    } 
    StdOut.println(); 
} } 

、失われました。たとえば、引数が2,3およびStdIn 5 7 8 9 10 4 6の場合、8 9 10を出力します(最初の2をスキップして次の3を出力します)。

答えて

4

現在の番号を知るためにカウンタを追加してみませんか?

int i = 0;  
while (!StdIn.isEmpty()) { 
    i++; 
    // read in the next integer 
    int t = StdIn.readInt(); 


    if (i > a && i <= a + b) { 
     StdOut.print(t + " "); 
    } 
} 
-1

?????--a <= 0 && --b >= 0

私は&&が短絡しているという事実を利用しています。すなわち--bは、--aが0以下になるまで評価されません。

最終的には、もちろんintは非常に長い入力蒸気セッションでアンダーフローしますが、これはまだ非常にクールな解決策です。

+1

コードの記述は限り短くし、可能な限り読みにくいが – nhouser9

+1

はおそらく、私はあなたよりも、単に全体の多くは、より聡明だ私の意見では「クール」ではありません!真剣に、教授がそれを望むなら、あなたはこの解決法をバックアップするためにコメントを使うことができます。 –

+1

私はそれがどのように機能するかを信じますが、それは誰もが意志するわけではありません。質問をする人は何かを書いたほうが、「クール」だと思うものよりも理解できることが保証されています。 – nhouser9

0
public class Filter { 
public static void main(String[] args) { 

// read in two command-line arguments 
    int a = Integer.parseInt(args[0]); 
    int b = Integer.parseInt(args[1]); 

    // repeat as long as there's more input to read in 
    while (!StdIn.isEmpty()) { 


     // read in the next integer 
     int t = StdIn.readInt(); 

     if(a-- > 0) 
      continue; 

     if (b-- > 0) { 
      StdOut.print(t + " "); 
     } 
    } 
    StdOut.println(); 
} } 
関連する問題