扫描仪跳过nextLine();在做while while循环之后

时间:2018-06-10 14:49:21

标签: java java.util.scanner

你可能会看到我是java的新手。下面是一个简单的计算器程序,要求用户输入符号,如+或 - 。然后,用户输入2个数字,并根据所选择的运算符符号调用方法。 do while循环允许用户重复该过程。问题是在程序循环之后,出现以下行:“String symb = inp.nextLine();”被跳过了。我已经尝试过搜索解决方案,但是如果在nextInt之后调用nextLine,我只找到了一个修复程序。提前感谢您的耐心等待。

import java.util.Scanner;

public class Calculator {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner inp = new Scanner(System.in);
    Methods operation = new Methods();
    boolean loop = false;




    do {

    System.out.println("Enter an operator symbol - +, -, * or /");
    String symb = inp.nextLine(); //this is the line which is skipped 


    System.out.println("Enter a number");
    int num1 = inp.nextInt();
    inp.nextLine();

    System.out.println("Enter a second number");
    int num2 = inp.nextInt();
    inp.nextLine();

    switch(symb) {
    case "+" : 

    operation.setA(num1);
    operation.setB(num2);
    int totalAddition = operation.addNums(num1,num2);
    System.out.println("The result is - " + totalAddition);
    break;

    case "-" : 
    operation.setA(num1);
    operation.setB(num2);
    int totalSubtract = operation.subtractNums(num1,num2);
    System.out.println("The result is - " + totalSubtract);
    break;

    case "*" : 
        operation.setA(num1);
        operation.setB(num2);
        int totalMult = operation.multNums(num1,num2);
        System.out.println("The result is - " + totalMult);
        break;

    case "/" : 
        operation.setA(num1);
        operation.setB(num2);
        int totalDiv = operation.divNums(num1,num2);
        System.out.println("The result is - " + totalDiv);
        break;
    }
    System.out.println("Would you like to exit? Y/N");
    char ans = inp.next().charAt(0);

    if(ans == 'Y' || ans == 'y') {
        loop = true;
        inp.close();
        System.exit(0);
    }
    else { 
        loop = false;
    }
    }
    while(loop == false);
    }
}

0 个答案:

没有答案