你在这个代码/程序中发现了什么错误? Erro是不会运行,除非你先输入一个数字 [英] What error do you find in this code/program? Erro is it wont run unless you type a number in first

查看:140
本文介绍了你在这个代码/程序中发现了什么错误? Erro是不会运行,除非你先输入一个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我的问题是这样:
这个程序应该计算圆的面积
用户输入一个数字与答案出来
也任何无效的输入不允许i使用try-catch但它不工作...

So my question is on this: This program is supposed to calculate the area of circle the user inputs a number comes out with the answer also any invalid input is not allowed i use the try-catch but it wont work...

非常感谢大家的时间:))

Thank you so much for you time everyone :))

这里是代码:

import java.util.Scanner; 
import java.io;

/**
 *
 * @author Osugule
 */
public class AreaCircle { 
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
Scanner sc = new Scanner(System.in); // read the keyboard
System.out.println("This program will calculate the area of a circle");
System.out.println("Enter radius:");//Print to screen
double r = sc.nextDouble(); // Read in the double from the keyboard
double area = (3.14 *r * r); 
try {

}
catch( NumberFormatException e ) {
    System.out.println("Invalid Input, please enter a number");
    //put a message or anything you want to tell the user that their input was weird.
}

String output = "Radius: " + r + "\n";
output = output + "Area: " + area + "\n";
System.out.println("The area of the circle  is " + area);

    }
}


推荐答案

您必须捕获 InputMismatchException 异常,如下所示:

You must catch InputMismatchException exception like this:

import java.util.InputMismatchException;
import java.util.Scanner; 
public class AreaCircle { 
    public static void main(String[] args) {
        // TODO code application logic here
        Scanner sc = new Scanner(System.in); // read the keyboard
        System.out.println("This program will calculate the area of a circle");
        System.out.println("Enter radius:");//Print to screen
        try {
            double r = sc.nextDouble(); // Read in the double from the keyboard
            double area = (3.14 *r * r);

            String output = "Radius: " + r + "\n";
            output = output + "Area: " + area + "\n";
            System.out.println("The area of the circle  is " + area);

        }
        catch( InputMismatchException e ) {
            System.out.println("Invalid Input, please enter a number");
            //put a message or anything you want to tell the user that their input was weird.
        }
        catch( NumberFormatException e ) {
            System.out.println("Invalid Input, please enter a number");
            //put a message or anything you want to tell the user that their input was weird.
        }
    }
}

这篇关于你在这个代码/程序中发现了什么错误? Erro是不会运行,除非你先输入一个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆