• ベストアンサー

Javaのforとwhileの使い方

プログラミングをはじめたばかりのものです。 「何回か数字を入力してその合計が100になったら終了 するプログラム(100になるまで入力待ちを繰り返すプログラム」 というのを作っているのですが、 以下のようにするとエラーが出ました。 public class upto100 { public static void main(String[] args) { for (int i=0; i <= 100; i=i+j) { String line = reader.readLine(); int j = Integer.parseInt(line); System.out.println("まだ100じゃない"); } System.out.println("もう100"); } } 入力待ちにするString line~~と int j~~~の場所が間違っているのだろうと 思うのですが、どのようにすればよろしいのでしょうか?

  • fuyu
  • お礼率69% (145/210)
  • Java
  • 回答数2
  • ありがとう数6

質問者が選んだベストアンサー

  • ベストアンサー
  • a-kuma
  • ベストアンサー率50% (1122/2211)
回答No.2

タイプミスがいくつかあります。 クラス名 BufferedReader に余計な空白が入っている。 変数 j の宣言の行の ";" がない。 for() の中に ";" がひとつしかない。 for() ループの中で二重に宣言されている。 NumberFormatException を e で受けているのに ie で使ってる。 で、それをふまえた上で、 > Buffered Readerから、System.out.println("もう100");あたりまでの > 構造はあっていますでしょうか? 基本的にはあっていると思いますが、最初の入力で 100 を超えない場合に、 100 を超えると、一度「まだ100じゃない」と出力されてから、for ループを 抜けて「もう100」と表示されます。 これは、期待通りの動きではないですよね? 何通りも実装方法はあると思いますが、ひとつのやり方は   for (j = 0 ; i <= 100 ; i = i + j) {     line = reader.readLine();     j = Integer.parseInt(line);     System.out.println("まだ100じゃない");   } の数値を獲得して i に足すことをいっぺんにしてしまう、つまり   for (; i <= 100 ; i = i + Integer.parseInt(reader.readLine())) {     System.out.println("まだ100じゃない");   } という感じ。変数 j は使ってません。

fuyu
質問者

お礼

for (; i <= 100 ; i = i + Integer.parseInt(reader.readLine())) {     System.out.println("まだ100じゃない");   } というような書き方ができるんですね。 初めて知りました。 解答ありがとうございました。 おかげさまでできました。 また、NumberFormatException あたりはよく 分からないまま本を写していた状況だったのですが、 教えていただいたことで少し理解できました。 ありがとうございました。

その他の回答 (1)

  • selenity
  • ベストアンサー率41% (324/772)
回答No.1

そりゃ~エラーが出るでしょう。 また、エラーの原因はエラーメッセージの通りです。 変数iはfor (int i=0; i <= 100; i=i+j) で宣言 されているので問題はありませんが、変数jはこの 時点では宣言されていません。 従って、変数i,jともにfor()の前で宣言しましょう。 また、for()の前でj=0;と変数jを初期化しましょう。 String lineのfor()の外で、宣言しておけば 良いでしょう。 まず、この2点を治しましょう。

fuyu
質問者

お礼

精一杯考えてみました。 forの前で2つの変数を宣言してみたのですが、 Buffered Readerから、 System.out.println("もう100");あたりまでの 構造はあっていますでしょうか? public class upto100 { public static void main(String[] args) { Buffered Reader reader = new BufferedReader(new InputStreamReader(System.in), 1); try { String line = reader.readLine(); int i = Integer.parseInt(line); int j = 0 for (i <= 100; i=i+j) { line = reader.readLine(); int j = Integer.parseInt(line); System.out.println("まだ100じゃない"); } System.out.println("もう100"); } catch (IOException e) { System.out.println(e); } catch (NumberFormatException e) { System.out.println(ie); } } }

fuyu
質問者

補足

初心者な上に、コンパイルとかできない環境で ざっと書いたプログラムだったので、 BufferedReader reader =~~ の行が抜けていたり、穴だらけですね。 教えていただいた2点を中心にもう少し考えてみます。

関連するQ&A

  • Java言語のプログラムをC言語にする場合

    次の2つのJava言語のプログラムをC言語にしたいのですが、C言語でプログラムを書いたことがありません。C言語にする場合はどう書けばいいのでしょうか? import java.io.*; public class Sort { public static void main(String[] args) { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try{ System.out.println("整数値を入力してください"); String line = reader.readLine(); int a = Integer.parseInt(line); String line2 = reader.readLine(); int b = Integer.parseInt(line2); String line3 = reader.readLine(); int c = Integer.parseInt(line3); String line4 = reader.readLine(); int d = Integer.parseInt(line4); int[] data = {a, b, c, d}; for (int i = 0; i< data.length - 1 ; i++) { for (int j = i + 1; j< data.length; j++) { if(data[i] > data[j]) { int e = data[i]; data[i] = data[j]; data[j] = e; } } } System.out.println("昇順に並べ替えると、"); for (int i = 0; i< data.length; i++) { System.out.print(data[i] + " "); } System.out.println("です。"); } catch (IOException e){ System.out.println(e); } catch (NumberFormatException e) { System.out.println("数式の形式が正しくありません。"); } } } import java.io.*; public class Yakusu { public static void main(String[] args) { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try{ System.out.println("2つの整数値を入力してください"); System.out.print("整数A : "); String line = reader.readLine(); int a = Integer.parseInt(line); System.out.print("整数B : "); String line2 = reader.readLine(); int b = Integer.parseInt(line2); if(a%b == 0){ System.out.println("BはAの約数です"); } else { System.out.println("BはAの約数ではありません"); } } catch (IOException e){ System.out.println(e); } catch (NumberFormatException e) { System.out.println("数式の形式が正しくありません。"); } } }

  • java while文です。教えてください(__)

    public class mondai2{ //プログラム開始 public static void main(String args[]){ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int i; int ans=0; int seikai=0; for(i=0;i<5;i++){ try{ { Random ran = new Random(); int num1 = ran.nextInt(8)+1; int num2 = ran.nextInt(8)+1; ans = num1*num2; System.out.print("問題"+(i+1)+":"); System.out.print(num1 + "×" +num2 + "="); String s =in.readLine(); seikai = Integer.parseInt(s); if(seikai==ans){ System.out.println("正解"); }else{ System.out.println("不正解"); } } }catch(IOException e){ System.out.println("エラー"); } } } } このプログラムをwhile文か、do while文にして正解が出るまで問題が出続けるようにしたいんですけど、まったくわからなくて困っています>< 教えてください(+o+)

    • ベストアンサー
    • Java
  • javaについて・・・

    このように出力されるプログラムを考えています ↓ 受験者人数を入力してください 3 3人分の点数を入力してください 50 80 20 1人目の点数は50です 2人目の点数は80です 3人目の点数は20です 最高点は80です っという感じのプログラムを考えています。 そしていまここまでプログラムを書いたのはいいのですが 感じんの最高点が表示されません・・・ import java.io.*; class test{ public static void main(String[] args) throws IOException{ System.out.println("テストの受験者数を入力してください。"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str =br.readLine(); int num = Integer.parseInt(str); int test[] = new int[num]; int max=0; System.out.println(test.length +"人の点数を入力してください"); for(int i=0; i<num; i++){ String str1 = br.readLine(); test[i] = Integer.parseInt(str1); } for(int i=0; j<num; i++){ System.out.println((i+1)+"番目の人の点数は"+ test[i]+"です。"); if(test[i]>max){ max=test[i]; } } System.out.println("最高点は" +max+ "です。"); } } どこをどのように直せば最高点が表示されるようになるでしょうか? ご指摘おねがいします。

  • Java for文

    for文について、キーボードで入力して、その数が素数(1またはその数以外で割り切れない数)であるかを判断するコードですが、for文とif文の関係が良くわかりません。ご教示ください。 <サンプル> public static void main(String[] args) throws IOException{ System.out.println("2以上の整数を入力してください。"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = br.readLine(); int num = Integer.parseInt(str); ※1 for(int i=2; i<=num; i++){ if(i == num){ System.out.println(num + "は素数です。"); ※2 }else if(num % i == 0){ System.out.println(num + "は素数ではありません。"); break; ※1と※2の処理について初心者でもわかるような解説をおねがいできますでしょうか? よろしくお願いいたします。

  • javaプログラミングの質問です。

    プログラムで数値の奇遇、合計値、最大値までは出せたのですが平均値の出し方がわかりません。 どこに何を入れればいいかを教えてください。お願いします。 public class pazu{ public static void main(String[] args){ int sum =0,saidai; System.out.println("コマンドラインパラメータは"+args.length+"個です"); for(int i=0;i<args.length;i++){ int x=Integer.parseInt(args[i]); if(pazu.is_even(x)) System.out.println(args[i]+"は偶数です"); else System.out.println(args[i]+"は奇数です"); sum+=x; } saidai=pazu.max(args); System.out.println("合計:"+sum); System.out.println("最大:"+saidai); } static boolean is_even(int number){ return number%2==0; } static int max(String[] number){ int max =0; for(int i=0;i<number.length;i++){ if(max<Integer.parseInt(number[i])){ max=Integer.parseInt(number[i]); } } return max; } }

    • ベストアンサー
    • Java
  • Javaで九九の計算

    今、Javaの勉強をしてる者です。勉強本の中に九九の問題があり、正しく動作することを確認したのですが、 入力された値が数値以外のものだった場合に、再入力させるプログラムに機能アップしたいと欲が出てきました。 現状のプログラムでは、入力値が整数でない場合、NumberFormatException で判定をして次の回に進んでしまってます。 int result = Integer.parseInt(line); の戻り値を判定して、整数でない場合に再入力させれば良いのかと予想したのですが、どう記載すべきかわかりません。 そもそもこの考え方は間違っているのか、別の方法が良いのかご教示いただけませんでしょうか。 --- import java.io.*; public class KuKu4 { public static final int max_question = 10; public static void main(String[] args){ int goodAns = 0; for(int i=0; i < max_question; i++){ boolean check = showQuestion(i+1); if(check){ goodAns++; } } double rate = (goodAns * 100 / max_question) ; System.out.println(""); System.out.println("正解は" + goodAns +"問"); System.out.println("間違いは" + (max_question - goodAns) +"問"); System.out.println("正答率は" + rate +"%"); } public static boolean showQuestion(int question){ int x = (int)(Math.random() * 9) + 1; int y = (int)(Math.random() * 9) + 1; BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try{ System.out.println("[第" + question + "問]" + x + " * " + y + "== ?"); String line = reader.readLine(); int result = Integer.parseInt(line); if(x * y == result){ System.out.println("正しい"); return true; }else{ System.out.println("正しくない"); return false; } }catch(IOException e){ System.out.println(e); }catch(NumberFormatException e){ System.out.println("入力された値が正しくない"); } return false; } }

  • 初心者Javaの件。

    いつも大変お世話になりありがとうございます。 次の2つのコードは関係があるのでしょうか? 2つを合体させないとプログラムがエラーになるのでしょうか? 私は合体させないとプログラムが成立しないと思います。 アドバイスのほど宜しくお願い申し上げます。 コード1 public class Person { private int age; private double weight; private double height; public Person(int age, double weight, double height) { this.age = age; this.weight = weight; this.height = height; } public void show() { System.out.println("年齢は" + age + "体重は" + weight + "身長は"+ height +"です。" ); } } コード2 import java.io.BufferedReader; public class Sample3 { { public static void main(String args[]) throws Exception { person p[]; System.out.println("人数を入力してください。"); BufferedReader br = new BufferedReader(new inputStreamReader(System.in)); String str = br.readLine(); int num = Integer.parseInt(str); p = new Person[num]; for(int i=0; i<num; i++) { } System.out.println("年齢を入力してください"); str = br.readLine(); int age = Integer.parseInt(str); P = new Person[num]; for(int i=0; i<num; i++){ System.out.println("年齢を入力してください"); str = br.readLine(); int age = Intger.parseInt(str); System.out.println("体重を入力してください"); str = br.readLine(); double weight = Double.parseDouble(str); System.out.println("身長を入力してください"); str = br.readLine(); double height = Double.parseDouble(str); p[i] = new person(age, weight, height); } for(int i=0; i<num; i++) { p[i].show(); } } }

    • ベストアンサー
    • Java
  • Java for文 だけで逆ピラミッドを作る

    教えてください。 for 文だけで逆ピラミッドを作りたいのですが、*の数が2個ずつ減ればピラミッド 作成なのですが、私の文だと*は1個ずつしか減りません。 2個の指定はどのうように記述すればよいでしょうか? *を3と指定した場合 ***** (5) -***   (3) --*     (1) と表示したいのですが、下の文だと ***** (5) -****  (4) --***   (3) となってしまいます。 import java.io.*; class Sample4 { public static void main(String [] args) throws IOException { System.out.println("いくつ*を入力しますか?"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = br.readLine(); int num = Integer.parseInt(str); int j =0; int i =0; int s =0; //行数制御 for(i=0; i<num; i++) { for(s=0; s<i; s++) { System.out.print("-"); } for(j=num*2-1; j>i; j--) { System.out.print("*"); //System.out.print("d"); } //改行タグ System.out.print("\n"); } } }

  • JAVAの初心者です。

    import java.io.*; class Sample1 { public static void main(String args[])throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); do{ System.out.println("1:入力文字整数確かめ"); System.out.println("2:終了"); String hako = br.readLine(); int sen = Integer.parseInt(hako); switch (sen){ case 1: System.out.println("整数を入力してください。"); String hako2 = br.readLine(); int hako3 = Integer.parseInt(hako2); if ((hako3%2)==0){ System.out.println("これは偶数ですね。"); } System.out.println("奇数ですね。"); break; case 2: System.out.println("終了いたします。"); break; } }while(sen != 2); } } 上記のように組んだのですが、}whileのところでエラー が出てしまうのです。 これってなぜなのでしょう?? 初心者特有の質問かもしれませんがご教授いただけたら嬉しいです。宜しくお願いいたします。 関係ないのかも知れませんがJDK1-5-006を使用してます。

    • ベストアンサー
    • Java
  • java ネストしたfor文について

    ***** **** *** ** * 上のように*が減るようにしたいのですが下のソースではどこが悪いか教えてください class TestGoo{ public static void main(String args[]){ for(int i = 5; i>=1; i--){ for(int j = 5;j>=1; j--){ System.out.print('*'); } System.out.println(); } } }

専門家に質問してみよう