只允许java扫描程序允许数字

时间:2017-01-13 04:12:56

标签: java

我一直在捕捉非数字的问题。

我尝试了try / catch,但我无法抓住它。如果有什么我得到它来捕捉非数字,但不允许用户再次尝试输入...它只是完全停止我的代码。

这是我的代码:

package triangle;

import java.util.Scanner;

public class traingle {

public static void main(String[] args){ 
    //explaining what the program is going to do 
System.out.println("You will be able to enter 3 angles to equal the sum of a triangle,\nthis automated program will tell you if the angle you entered is issosoliese, eqilateral or scalene");
//creating input 1,2,3 for user

Scanner angle1 = new Scanner(System.in);  // Reading from System.in
System.out.println("Enter angle degree number 1: ");
int n = angle1.nextInt();

Scanner angel2 = new Scanner(System.in);
System.out.println("Enter angle degree number 2: ");
int n2 = angel2.nextInt();

Scanner angel3 = new Scanner(System.in);
System.out.println("Enter angle degree number 3: ");
int n3 = angel3.nextInt();
//this is just telling how much degrees the user had in total if they didnt match up to triangle standards

2 个答案:

答案 0 :(得分:0)

这应该让你开始。

package triangle;

import java.util.Scanner;

public class triangle {

    public static void main(String[] args){ 
         //explaining what the program is going to do 
        System.out.println("You will be able to enter 3 angles to equal the sum of a triangle,\n");
        System.out.println("this automated program will tell you if the angle you entered is isoceles, eqilateral or scalene");
        //creating input 1,2,3 for user

        Scanner s = new Scanner(System.in);  // Reading from System.in

        String line;
        int [] angles = new int [3];
        int count = 0;

        do {
            System.out.print("Enter angle degree number " + (count+1) + ": ");
            line = s.nextLine();
            while (true ) {
                try {
                    angles[count] = Integer.parseInt(line);
                    System.out.println("You entered " + angles[count]);
                    count++;
                    break;
                } catch (NumberFormatException e ) {
                    System.out.println("Invalid number: try again: ");
                    line = s.nextLine();
                }
            }
        } while (count < 3);


    }
}

答案 1 :(得分:-1)

你有一个简单的问题..你只需要在main方法中使用一个Scanner代码。

 package triangle;

 import java.util.Scanner;

 public class traingle {

 public static void main(String[] argc){
 System.out.println("You will be able to enter 3 angles to equal the sum of a triangle,\nthis automated program will tell you if the angle you entered is issosoliese, eqilateral or scalene");

 Scanner angle1 = new Scanner(System.in);  

 System.out.println("Enter angle degree number 1: ");

 int n = angle1.nextInt();

 System.out.println("Enter angle degree number 2: ");

int n2 = angel2.nextInt();

System.out.println("Enter angle degree number 3: ");

int n3 = angel3.nextInt();