import java.util.*;
public class Moon {
public static final float G=9.8F;//定义一个常量,表示重力常数
public static final float MoonG=0.17F;//定义常量比例
public static void main(String[] args) {
while(true){
System.out.println("请输入你的体重(KG)(退出程序请输入:exit):");
Scanner sc=new Scanner(System.in);
String str=sc.next();  //全部当字符串来接收
sc.close();            //接收完,关闭扫描...
if(str.equals("exit")){       //字符串内容的比较用equals
return;//关闭程序
}
else{
try{
float heavyNumber=Float.valueOf(str);//尝试强转
System.out.println("在月球上你重(N):"+String.valueOf(heavyNumber*G*MoonG));//如果成功,输出
}
catch(Exception e){
System.out.println("哥们,你的输入,Java不认啊,重新输入数值吧...");
}
}  
}
}
}在控制台执行一次循环后就报错了,是不是sc.close()不能用?怎么回事,求解答...

解决方案 »

  1.   

    没太用过这个。但觉得:
    如果想一直测试,就不要sc.close()。如果调用xxx.next()方法,最好先check下
    if(xxx.hasNext()){   // or while(xxx.hasNext())
        xxx.next()
    }
      

  2.   

    import java.util.Scanner;
    public class dddd {
     public static final float G=9.8F;//定义一个常量,表示重力常数
        public static final float MoonG=0.17F;//定义常量比例
        public static void main(String[] args) {
            while(true){
                System.out.println("请输入你的体重(KG)(退出程序请输入:exit):");
                Scanner sc=new Scanner(System.in);
                String str=sc.next();  //全部当字符串来接收
                           //接收完,关闭扫描...
                System.out.println("-------");
                if(str.equals("exit")){       //字符串内容的比较用equals
                    return;//关闭程序
                }
                else{
                    try{
                        float heavyNumber=Float.valueOf(str);//尝试强转
                        System.out.println("在月球上你重(N):"+String.valueOf(heavyNumber*G*MoonG));//如果成功,输出
                    }
                    catch(Exception e){
                        System.out.println("哥们,你的输入,Java不认啊,重新输入数值吧...");    
                    }
                }  
            }
        }}
    去掉sc.close()
    通过测试无误