2017-11-16 13 views
1

사용자가 입력 한 내용에 + 기호가 있으면이 프로그램이 두 피연산자를 올바르게 실행할 수 있도록 만들고 싶습니다. 또한 사용자가 종료 할 때마다 프로그램을 종료 할 수 있도록하고 싶지만 첫 번째 줄에서 끝나면 작동합니다. 초보자 프로그래밍, 그래서 nooby 실수에 미리 사과.내 Java 콘솔 계산기에서 추가 기능이 작동하지 않는 이유는 무엇입니까? 그리고 어떻게 프로그램을 종료 할 때 "quit"명령을 항상 작동하게 할 수 있습니까?

package javaapplication59; 

import java.util.Scanner; 

public class JavaApplication59 { 

public static void main(String[] args) { 
    System.out.println("This is a calculator of singular expressions."); 
    calculator(); 

} 

public static void calculator() { 
    System.out.println("Enter an expression, or type \"quit\" to exit.\n"); 
    Scanner kbd; 
    kbd = new Scanner(System.in); 
    System.out.println(); 
    String text = kbd.nextLine(); 
    while (!text.equalsIgnoreCase("quit")) { 
     Scanner tokens = new Scanner(text); 
     if (tokens.hasNextInt()) { 
      twoOperand(tokens); 
     } else { 
      oneOperand(); 
     } 
    } 

    System.out.println("Farewell"); 
    System.exit(0); 
} 

public static void twoOperand(Scanner tokens) { 
    int firstNum = tokens.nextInt(); 
    String operator = tokens.next(); 
    int secondNum = 0; 
    if (tokens.hasNextInt()) { 
     secondNum = tokens.nextInt(); 
    } else { 
     System.out.println("Error, not valid expression"); 
     calculator(); 
    } 
    while (tokens.next().contains("+")) { 
     addition(); 
    } 
    while (tokens.next().contains("-")) { 
     subtraction(); 
    } 
    while (tokens.next().contains("*")) { 
     multiplication(); 
    } 
    while (tokens.next().contains("/")) { 
     division(); 
    } 
    while (tokens.next().contains("%")) { 
     modulus(); 
    } 
    while (tokens.next().contains("^")) { 
     exponentiation(); 
    } 
} 

public static void oneOperand() { 
} 

public static void addition() { 
    Scanner tokens; 
    tokens = new Scanner(System.in); 
    String name = tokens.next(); 
    int sum = 0; 
    while (tokens.hasNextInt()) { 
     int num = tokens.nextInt(); 
     sum += num; 
     System.out.println(sum); 
     calculator(); 
    } 
} 
} 
+0

당신은 아마 당신의 첨가 방법은 값을 반환합니다. 또한 추가 반복자 내부에서 계산기를 호출하고 while 루프에서 피연산자 함수를 호출합니다. 왜? 이 코드의 80 %는 복잡하지 않아도됩니다. 이것은 생각보다 훨씬 간단합니다. – G2M

+0

첫 번째 숫자, 연산자 및 두 번째 숫자를 변수에 넣으면 ... 이미 호출 한 연산자를 얻기 위해'next'를 다시 호출하면 NoSuchElementException이 발생합니다. –

답변

0

이것은 추가 기능과 곱셈 기능을 사용하여 찾고있는 기능을 빠르게 조합 한 버전입니다. 이렇게하면 운영 체제를 선택하고 엔터를 치고 수행 할 int를 선택하고, 중간 결과를 입력하고, 다음을 선택하고, 입력하는 등의 작업을 수행 할 수 있습니다. 또한 종료하려면 언제든지 quit을 입력하십시오. 원하는대로 수정하십시오. 행운을 빕니다. :)

import java.util.Scanner; 

public class Calculator { 
public static void main(String[] args) { 

    System.out.println("This is a calculator:"); 
    calc(); 

} 
public static void calc(){ 

    System.out.println("Press *,/,+,- to perform op on following ints:"); 
    Scanner sc = new Scanner(System.in); 
    String opString = sc.nextLine(); 

    if(opString.equalsIgnoreCase("quit")){ 
     System.out.println("Calculator quit!"); 
     sc.close(); 
     return; 
    } 
    switch (opString) { 
     case "*": multiplication(); 
     break; 
     case "/": division(); 
     break; 
     case "+": addition(); 
     break; 
     case "-": subtraction(); 
    } 
} 

public static int multiplication(){ 
    Scanner sc = new Scanner(System.in); 
    int op1 = 1, op2; 
    while (sc.hasNextInt()){ 
     op2 = sc.nextInt(); 
     op1 *= op2; 
     System.out.println("= " + op1); 
    } 
    sc.close(); 
    return op1; 
} 
public static int division(){ 
    return 0; 
} 
public static int addition(){ 
    Scanner sc = new Scanner(System.in); 
    int op1 = 0, op2; 
    while (sc.hasNextInt()){ 
     op2 = sc.nextInt(); 
     op1 += op2; 
     System.out.println("= " + op1); 
    } 
    sc.close(); 
    return op1; 

} 
public static int subtraction(){ 
    return 0; 
} 

은}

+0

고마워요! 그래도 전체 표현식이 한 줄에 표시되도록하려면 어떻게해야합니까? 나는 또한 프로그램을 끝내지 않고도 표현의 타이핑을 계속할 수 있기를 원한다. 나는 당신이 구현 한 명령 중 일부에 익숙하지 않고 이것들을 어떻게 바꾸어야할지 모르겠다. –

+0

@GeropSplydon 슬프게도 나는 더 이상 새로운 답변을 게시 할 수 있습니다 잠겨 있습니다 :(그러나 한 단계에서 뭔가를 계산할 수 있도록 : 5 * 4 당신은 피연산자까지 정수를 구문 분석해야합니다 저장, 피연산자를 구문 분석하고 다음 int를 구문 분석 한 다음 해당 값을 인수로 사용하는 메서드를 호출하십시오. 유일한 변경 사항은 파싱을 조사해야한다는 것입니다. http://www.ocpsoft.org/opensource/guide-to-regular -expressions-in-java-part-1/또한 3 * 4 + 5 또는 ((3 + 4) * 2)/2와 같은 것을 평가하려면 무언가 더 많은 작업이 필요하다는 것을 염두에 두십시오. 해피 코딩 :) – G2M

+0

네,이 포럼이 어떻게 작동하는지 모르겠습니다. 코딩에 익숙하지 않아 몇 가지 지침을 위반하면 놀라지 않을 것입니다. 도와 주실 시간을 내 주셔서 대단히 감사합니다. 아주 좋았어요. –