public class test
{
      public static void main (String argv [])

          int j = 1;
  System.out.println("Enter a number:");
  try 
    {
      j = (int)System.in.read();
    }catch (Exception e)
      {
      } 
   for (int i = 0; i < j ;i++)
      {
                System.out.println("number:"+i);    
      }
}
}
预期的结果是输入2,显示number:0
                    number:1
可运行出来的结果是:number:0
                  number:1
                  ........
                  ........
                  number:49
怎么回事啊

解决方案 »

  1.   

    因为字符'2'的acsii码值是50。
      

  2.   

    import java.util.Scanner;public class Tnum{
    public static void main(String argv[]) {
    Scanner scanner = new Scanner(System.in);
    int j = 1;
    System.out.println("Enter a number:");
    try {
    j = scanner.nextInt();
    } catch (Exception e) {
    }
    for (int i = 0; i < j; i++) {
    System.out.println("number:" + i);
    }
    }
    }用Scanner来获取就好了..
      

  3.   

    我是刚学啊 还没学到Scanner那里 我就是不明白什么地方弄错了
      

  4.   

    把j = (int)System.in.read();改成Integer.valueOf(System.in.read());试试
      

  5.   

    那你先把System.in.read()的值大印出来看下,是什么?如果不行,只有用Scanner类了,很好用的
    Scanner s = new Scanner(System.in);
    int num = s.nextInt();
      

  6.   

    import java.util.*;
    public class test1 {
     public static void main (String[]args){
         Scanner input =new Scanner (System.in);
           int j=input .nextInt();
           int a =0;
           while (a<j){
            System.out.println("number:"+a);
             a++;
    }
           
    }
    }
      我这个方法可以实现
      用while 循环 自己试试看吧
      

  7.   


    j = (int)System.in.read();
    改为BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
    int j = Integer.parseInt(bf.readLine());就行了 
      

  8.   

    记得导入包 import java.io.*;
      

  9.   

    得到你所要的结果方法实在是太多了.比如以下两种吧.
    ======================================================
    public static void main(String argv[]) {
    Integer j = 1;
    System.out.println("Enter a number:");
    try {
    Character c = (char) System.in.read();
    // j=c.getNumericValue(c) ;  方法一
    j = Integer.parseInt(c.toString());//方法二
    } catch (Exception e) {
    }
    for (int i = 0; i < j; i++) {
    System.out.println("number:" + i);
    }
    }