一段很基础的java代码,希望高手帮忙看下,谢谢
public class Example
{
 public static void main (String argv[])
   {char ch = (char) - 1;
   System.out.println("Enter a character");
   try
     (
      ch = (char)System.in.read();
      }catch (Expetion e)
        {
        }
     System.out.println(ch);
    }
}
 我要问的是:红色部分那里的 (char)-1是什么意思啊 为什么要减1呢 大家帮帮我啊!

解决方案 »

  1.   

    强制转换?能详细点吗是接收键盘上的一个字符 用(char)不就行了吗 后面又减1是什么意思呢
      

  2.   

    char ch = (char)-1;只是为了实例化一个char类型的变量而已,并没有特殊的含义。
    你也可以写成
    char ch = 'a';或者其他的字符。
      

  3.   

    那么如果是整型的我该怎么写啊
    public class test
    {
    public static void main (String argv [])
    int j = 0;
      for (int i = 0;i < j;i++)
        {    
           System.out.println("Enter a number:");
     try
          {
           j = (int)System.in.read();
          }
        catch (Exception e)
        {
        }
          System.out.println("number:"+i);
       }
    }
    }
    上面的代码怎么都运行不起 我觉得是红色的地方出错了 
      

  4.   

    汗~~你的循环又跑不起~~
    你的try和catch你检查下所在位置怎么可能有效果呢!
      

  5.   

    我修改了下这样还是和预期结果不一样 晕哦
    public class test
    {
    public static void main (String argv [])
    { int j = 0;
    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);    
           }
    }
    }
      

  6.   


    public class Test{
    public Test(){}
    public static void main (String argv[]) 
      {
    char ch = (char)-1;//只是为了实例化一个char类型的变量而已,并没有特殊的含义。
    int a = 0; 
    int b=0;
    System.out.println("Enter a number"); 
        try {
    ch = (char)System.in.read();
    a=Integer.parseInt(String.valueOf(ch));//要得到输入char的int值,我
                                                                       //只想到这个方法,同样作为菜鸟,给你参考下
    b=(int)ch; //得到的是AS..码值
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();

        System.out.println(a);
        System.out.println(b); 
        } 
    }结果[code=Java]Enter a number
    8
    8
    56
      

  7.   

    你注意看你j = (int)System.in.read(); 
    这句所得出的值是取的ASCII
    比如说你输入a
    而对应的值就是65~~如果输入阿拉伯数字1,对应的就是48
    最后循环肯定不少了~~
      

  8.   

    也就是说~你输入的是字符~~而接收的是int型~~也就是字符的ASCII
      

  9.   

    这样没问题的public static void main (String argv []) 
    {  
    System.out.println("Enter a number:"); 
      
        
    Scanner x=new Scanner(System.in);
    System.out.print("请输入一个整数"); 
    int i=x.nextInt();
        
        for (int a = 0; a < i ;a++) 
          { 
                  System.out.println("number:"+a);    
          }