Java 如果输入是字符而不是数字,我如何使用测试代码来测试

Java 如果输入是字符而不是数字,我如何使用测试代码来测试,java,numbers,logic,Java,Numbers,Logic,这是代码,我试图测试在另一个类文件中输入的用户输入是否具有整数或双精度以外的字符。我需要这段代码在这里工作,我已经在下面创建了一个draw类,我想如果我能让它在一个中工作,那么它在另一个中也会工作。 提前谢谢 以下是请求的代码: public void deposit (double amount){ if (amount >= 0) { balance = balance + amount; } else { System.out.println(

这是代码,我试图测试在另一个类文件中输入的用户输入是否具有整数或双精度以外的字符。我需要这段代码在这里工作,我已经在下面创建了一个draw类,我想如果我能让它在一个中工作,那么它在另一个中也会工作。 提前谢谢

以下是请求的代码:

public void deposit (double amount){
    if (amount >= 0) {
    balance = balance + amount;
    } else {
        System.out.println("Your deposit is a negative number, If you would like to withdraw please enter '0' and select Withdraw.");
    }
        while (!double || !int) {
            System.out.println("Invalid Input. Try again");
        }
    }
下面是代码第一部分的全部内容:

import java.util.Scanner;
public class Bank {
double balance = 0;

Scanner in = new Scanner(System.in);
int userChoice;
BankAccount account1 = new BankAccount();
boolean quit = false; {
do {
System.out.println("Your Choice: ");
System.out.println("For Deposit type 1");
System.out.println("For Withdraw type 2");
System.out.println("For Check Balance type 3");
System.out.println("Type 0 to quit");
userChoice = in.nextInt();
switch (userChoice){
case 1: 

    //Deposit Money
    System.out.println("How Much would you like to deposit?");
    double amount;
    amount = in.nextDouble();
    System.out.println("Depositing: " + amount);
    account1.deposit(amount);
    //balance = amount + balance;
    break;
case 2: 
    //Withdraw money
    System.out.println("How much would you like to withdraw?");
    amount = in.nextDouble();
    System.out.println("Withdrawing: " + amount);
    account1.withdraw(amount);
    //balance = balance - amount;
    break;
case 3: 
    //check balance
    System.out.println("Checking Balance.");
    account1.getBalance();

    System.out.println(account1.balance);
    break;
case 0: 
    System.out.println("Thanks for Using BankAccount Banking System!");
    quit = true;
    break;
default: 
    System.out.println("Error: Choice not recognized please choose again.");
    continue;
}

if (userChoice ==  0)
    quit = true;
}while 
(!quit);
}
}
公共类银行账户{
公共双平衡;
public int-sulficientfunds=1;
公共资金不足=-1;
公共银行账户(){
余额=0;
}
公共银行账户(双倍初始余额){
平衡=初始平衡;
}
公共作废保证金(双倍金额){
如果(金额>=0){
余额=余额+金额;
}否则{
System.out.println(“您的存款是负数,如果您想取款,请输入'0'并选择取款。”);
}
而(!double | |!int){
System.out.println(“输入无效,请重试”);
}
}
公共双支取(双倍金额){
余额=余额-金额;
如果(余额==金额){
返回足够的资金;
}否则如果(余额>金额){
返回足够的资金;
}否则,如果(余额<金额){
System.out.println(“资金不足”);
返还资金不足;
}
退货金额;
}
公共双getBalance(){
收益余额;
}

}

Java是一种强类型语言,因此amount变量除了包含一个double以外不可能包含任何内容,double是一个数字。

好的,因此在接受
amount
的输入时,用try-catch块将其包围,而不是简单地

public class BankAccount {

public double balance;
public int sufficientFunds = 1;
public int insufficientFunds = -1;

public BankAccount(){
    balance = 0;
}


public BankAccount (double initialBalance){
    balance = initialBalance;
}


public void deposit (double amount){
    if (amount >= 0) {
    balance = balance + amount;
    } else {
        System.out.println("Your deposit is a negative number, If you would like to withdraw please enter '0' and select Withdraw.");
    }
        while (!double || !int) {
            System.out.println("Invalid Input. Try again");
        }
    }



public double withdraw (double amount){
    balance = balance - amount;

    if (balance == amount){
        return sufficientFunds;
    }else if (balance > amount){
        return sufficientFunds;
    }else if (balance < amount){
        System.out.println("INSUFFICENT FUNDS");
        return insufficientFunds;
    }
    return amount;

}


public double getBalance(){
    return balance;
}
你会得到

amount = in.nextDouble();
此外,您还需要将其包装在do while循环中,以便程序再次询问,直到接受有效输入:

try{
    amount = in.nextDouble();
}catch(InputMismatchException ime){
    //What to do if this is not a numerical value
}

编辑:由于.nextDouble()中的
,程序可能会持续尝试读取缓冲区中的
\n
(当用户按下
回车时)。为了避免这种情况,在初始化
扫描器
对象之后(如果是类变量,则是方法中的第一件事),添加

到Java以在该位置结束输入并忽略换行符。

将此用于bank

in.useDelimiter("\n");
在BankAccount中更新此帐户

import java.util.Scanner;

public class Bank {
    double balance = 0;

    Scanner in = new Scanner(System.in);
    int userChoice;
    BankAccount account1 = new BankAccount();
    boolean quit = false;
    public void thisShouldBeAMethod(){
        do {
            System.out.println("Your Choice: ");
            System.out.println("For Deposit type 1");
            System.out.println("For Withdraw type 2");
            System.out.println("For Check Balance type 3");
            System.out.println("Type 0 to quit");
            //userChoice = in.nextInt();
            String regex = "[0-9]+";
            String input = in.next(); 
            if(input.matches(regex)){
                userChoice = Integer.parseInt(input);
                switch (userChoice) {
                case 1:

                    // Deposit Money
                    System.out.println("How Much would you like to deposit?");
                    double amount;
                    amount = in.nextDouble();
                    System.out.println("Depositing: " + amount);
                    account1.deposit(amount);
                    // balance = amount + balance;
                    break;
                case 2:
                    // Withdraw money
                    System.out.println("How much would you like to withdraw?");
                    amount = in.nextDouble();
                    System.out.println("Withdrawing: " + amount);
                    account1.withdraw(amount);
                    // balance = balance - amount;
                    break;
                case 3:
                    // check balance
                    System.out.println("Checking Balance.");
                    account1.getBalance();

                    System.out.println(account1.balance);
                    break;
                case 0:
                    System.out
                            .println("Thanks for Using BankAccount Banking System!");
                    quit = true;
                    break;
                default:
                    System.out
                            .println("Error: Choice not recognized please choose again.");
                    continue;
                }

                if (userChoice == 0)
                    quit = true;
            }
            else{
                 System.out.println("Invalid Input. Try again");
            }

        } while (!quit);
    }
}
和测试

public void deposit (double amount){
        if (amount >= 0) {
        balance = balance + amount;
        } else {
            System.out.println("Your deposit is a negative number, If you would like to withdraw please enter '0' and select Withdraw.");
        }
//          while (!double || !int) {
//              System.out.println("Invalid Input. Try again");
//          }
        }

这根本不是Java。。。尤其是while“循环”。你能给我们看一下调用这个代码的代码吗?哪一个“输入输入到另一个类中”?@RudolphEst这是java。我想我用过了!双倍!int告诉我们while循环条件中应该包含什么,表示他们想要一个当amount不是double或int变量时返回true的条件。还有@marksaidcamilelleri是的,这就是我想要的。被接受的答案实际上是一个坏例子。这不是验证应该如何进行的。智能选择。我正在键入一个解决方案:)。Spot on+1我基本上只需要它来从我而不是我正在使用的Java IDE(Eclipse)生成一条错误消息。好的,我实现了这一点,但是当输入了错误的输入时,它会循环不断地反复打印错误。我会包括“休息”吗在while部分之后的语句是否停止此操作?换句话说,它不是暂停下一次输入,它只是循环打印语句。好的,对不起,我忘记了扫描仪的问题。这是一个非常普遍的问题。请参阅编辑以获取解决方案。我添加了该选项,现在它停止了整个程序,但出现以下异常:线程“main”java.lang中的异常。错误:未解决的编译问题:令牌上的语法错误。“@应在该令牌语法错误后插入“SimpleName”以完成QualifiedName语法错误,插入“Identifier(”要完成MethodHeaderName语法错误,请在Bank.main(BankRunner.java:5)的Bank.java:8处插入“)”以完成MethodDeclaration。此外,所有这些错误都来自.useDelimiter(“\n)”中的语句;是否将其添加到方法中?我刚刚注意到,
中的
是一个类变量(所以我编辑了编辑以反映您需要在方法中为分隔符添加类似的内容)。此外,您是否将其编写为
“\n”
boolean inputInvalid=false;in.usedimiter(“\n”);do{System.out.println(“您想存多少?”);尝试{amount=in.nextDouble();}catch(inputmatchException-ime){System.out.println(“无效输入。重试”);inputInvalid=true;}}}while(inputInvalid);System.out.println(“存款:+amount);account1.deposit(amount);//balance=amount+balance;break;
这是我的代码以及我是如何实现分隔符语句的
public void deposit (double amount){
        if (amount >= 0) {
        balance = balance + amount;
        } else {
            System.out.println("Your deposit is a negative number, If you would like to withdraw please enter '0' and select Withdraw.");
        }
//          while (!double || !int) {
//              System.out.println("Invalid Input. Try again");
//          }
        }
public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Bank bank = new Bank();
        bank.thisShouldBeAMethod();
    }


}