2016-03-16 2 views
1

Я пытаюсь ввести пользователя в несколько значений, и компьютер вернет ответ. Например, они вошли бы в 10 + 11 - 15/12? то он выдаст ответ. Я тестировал это, и он принимает только первое число и последний оператор, а последний введенный номер и вычисляет этот ответ. (выход от около 10/12). Из того, что я могу сказать, мои математические методы работают правильно, но я тоже их прикрепил. Как я могу заставить его продолжать читать в новых пользовательских вводах, а затем выполнить математику, чтобы выяснить ответ?Как я могу заставить мой цикл продолжать повторно вводить новые переменные и операторы, чтобы продолжать вычислять?

Это мой код:

static void evaluate(){ 
    // this loads a scanner and prompts the user for input 
    Scanner input = new Scanner(System.in); 
    System.out.println("Enter the expression: ");  
    int answer = 0; 
    int num = 0; 
    int input1, input2; 
    char operator = '+' ; 
    input1 = input.nextInt(); 
    operator = input.next().charAt(0); 
    input2 = input.nextInt(); 
    if(operator == '?') 
     return; 
    //this loop will continue until ? is entered 
    do{ 
    if(operator == '?') 
     break; 
    operator = input.next().charAt(0); 
    input2 = input.nextInt(); 
    // this will detect which operator is used 
    switch (operator) { 
     case '+': answer = addition(input1, input2); 
        break; 
     case '-': answer = subtract(input1, input2); 
        break; 
     case '*': answer = multiply(input1, input2); 
        break; 
     case '/': answer = division(input1, input2); 
        break; 
     case '%': answer = remainder(input1, input2); 
    } } while (operator != '?'); 
    System.out.println("The result is " + answer); 
} 

Эти методы для сложения, вычитания, деления, умножения и модуло.

// this is the math if a + is used as an operator 
static int addition (int num1, int num2){ 
    int add; 
    add = num1 + num2; 
    return add; 
} 
// this is the math if a - is used as an operator 
static int subtract (int num1, int num2){ 
    int minus; 
    minus = num1 - num2; 
    return minus; 
} 
// this is the math if a * is used as an operator 
static int multiply (int num1, int num2){ 
    int multi; 
    multi = num1 * num2; 
    return multi; 
} 
// this is the math if a/is used as an operator 
static int division (int num1, int num2){ 
    int div; 
    div = num1/num2; 
    return div; 
} 
// this is the math if a % is used as an operator 
static int remainder (int num1, int num2){ 
    int modulos; 
    modulos = num1 % num2; 
    return modulos; 
} 

ответ

0

Ваша логика прекрасно и все, что вам нужно сделать, это поставить это условие if(operator == '?') break; после того, как вы читаете значение в operator, делая operator = input.next().charAt(0);.

Другое дело, что вы никогда не меняете значение input1. Вы должны начать назначать answer до input1 после выполнения любой операции.

Вот модифицированный фрагмент кода:

public static void main(String[] args) 
{ 
    Scanner input = new Scanner(System.in); 
    System.out.println("Enter The Expression: ");  
    int answer = 0, num = 0, input1, input2; 
    char operator = '+' ; 

    /* Read Input 1 */ 
    input1 = input.nextInt(); 

    //this loop will continue until ? is entered 
    do { 
     /* Read Operator */ 
     operator = input.next().charAt(0); 
     if(operator == '?') break; 
     /* Read Input 2 */ 
     input2 = input.nextInt(); 
     // this will detect which operator is used 
     switch (operator) { 
      case '+': answer = addition(input1, input2); 
         break; 
      case '-': answer = subtract(input1, input2); 
         break; 
      case '*': answer = multiply(input1, input2); 
         break; 
      case '/': answer = division(input1, input2); 
         break; 
      case '%': answer = remainder(input1, input2); 
     } 
     /* Input1 will be the answer now */ 
     input1 = answer; 
    } while (operator != '?'); 
    System.out.println("Result: " + answer); 
} 

// this is the math if a + is used as an operator 
static int addition (int num1, int num2){ 
    int add; 
    add = num1 + num2; 
    return add; 
} 
// this is the math if a - is used as an operator 
static int subtract (int num1, int num2){ 
    int minus; 
    minus = num1 - num2; 
    return minus; 
} 
// this is the math if a * is used as an operator 
static int multiply (int num1, int num2){ 
    int multi; 
    multi = num1 * num2; 
    return multi; 
} 
// this is the math if a/is used as an operator 
static int division (int num1, int num2){ 
    int div; 
    div = num1/num2; 
    return div; 
} 
// this is the math if a % is used as an operator 
static int remainder (int num1, int num2){ 
    int modulos; 
    modulos = num1 % num2; 
    return modulos; 
} 

Вход:

10 + 11 - 15/2 ? 

Выход:

Result: 3 

Кроме того, я надеюсь, что вы помещаете пробелы между вашими входными числами, как что вы показали в вопросе выше. Обратите внимание, что так, как вы читаете ввод 10 + 11 - 15/12 ? будет работать нормально, но 10+11-15/12? не будет.

+0

Вот что я и подумал! но после того, как я попробовал, цикл продолжится, даже если я войду в? и он не будет компилировать математику. вот как это выглядит. \t \t 'operator = input.next(). CharAt (0); input2 = input.nextInt(); \t \t if (operator == '?') \t break; 'Также я помещал в белые пробелы между –

+0

@ 154guy Нет, он не будет продолжать цикл. Существует проблема с тем, как вы читаете ввод. Вы никогда не обновляете 'input1'. См. Обновленное решение. – user2004685

+0

Когда я ввел код, указанный вами по адресу http://ideone.com/pJR5lY, он говорит, что в основном методе есть ошибка, что существует исключение несоответствия. –

Смежные вопросы