有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

带数字的java If语句

我需要这样做,当用户输入单词2而不是数字2时,它会告诉用户数字需要是数字形式

package monthly.mortgage.rate;

import java.util.Scanner;


class MonthlyMortgageRate {

    public static void main(String[] args) {

        double Amount;
        double Rate;
        double Months;
        double outputNum1;
        boolean doagain;
        doagain = true;

        Scanner in = new Scanner(System.in);

        while (doagain) {

            System.out.print("Enter loan amount:");
            Amount = in.nextDouble();

            System.out.print("Enter rate:");
            Rate = in.nextDouble() / 100 / 12;

            System.out.print("Enter year:");
            Months = in.nextDouble() * 12;

            outputNum1 = Rate * Amount / (1 - Math.pow(1 + Rate, -Months));

            if (Amount <= 0)
                System.out.println("You must enter positive numeric data!");
            if (Rate <= 0)
                System.out.println("You must enter positive numeric data!");
            if (Months <= 0)
                System.out.println("You must enter positive numeric data!");
            else
                System.out.printf("Monthly payment is: $ %.2f%n", outputNum1);

            System.out.println("would you like to calculate again?(y/n)");

            if (in.next().toLowerCase().equals("y"))
                ;
            boolean y = doagain;

            if (in.next().toLowerCase().equals("n"))
                doagain = false;
            boolean n = false;

        }
    }
}

共 (1) 个答案

  1. # 1 楼答案

    我从你的问题中得到的是,你想知道是否有人输入了字符串作为数字,而不是int作为数字。基本上,您可以用每个字母创建一个数组:

    Array alphabet = {"a", "b"...}
    

    现在,看看输入是否包含字母表中的任何字符。。。或者在我们的例子中,Array alphabet。你可以使用.contains

    for(int i =0; i < alphabet.length; i++)
    {
        if(inputString.contains(alphabet[i]))
        {
            return true;
        }
    }
    

    这就是你可以看到他们是否输入了任何字母或字符串。。。比如two而不是2

    但是。。。以下可能是一种更简单的方法:

    你不想要字符串作为输入,对吗? 如果用户键入的是字符串而不是int,那么nextDouble()应该抛出一个异常供您捕获

    所以,要接受您的输入,请使用try-and-catch,并为未输入字符串的用户捕获异常

    try{
       }Catch(CATCH THE STRING){
    System.out.println("You should put in a number!");
     }