2014-10-30 7 views
0

1_1/2 * 1_1/2의 계산을하고 싶습니다. 내가 할 수있는 방법을 설명 할 수는 없지만, 아래는 현재 코드이고, 아래는이 구현을위한 내 생각 코드이다. 내 코드가 기본 num1 연산으로 제한된다는 것을 알고 있습니다. 및 num2. num1 또는 num2가 1_1/2와 같으면 1을 정수로 생각하고 2/2로 만들고 1/2에 3/2로 나누고 1.5로 나누고 따르도록합니다. 방정식.** ** Java 코드로 혼합 소수 계산하기

static int DO_DEBUG = 0; // set to 1 for messages on, or 0 for messages off 

static final boolean BASIC_VERSION = true; 


public static void main(String[] args) { 

    calculator(); 
    //test(); 
} 


public static void test() { 
    String[] tests = { 
      "1+1", 
      "12 * 12", 
      "1_1/2 * 1_1/2", 
      "12 + mom", 
      "12/3/3", 
      "1_/3 + 5", 
      "1 & 4", 
      "12 +5", 
      "1/3 - 1_4/5/6" 
    }; 
    for (int i = 0; i < tests.length; i++) { 
     System.out.println("TESTING: " + tests[i]); 
     processInput(tests[i]); 
    } 

} 
static void calculator() { 

    Scanner console = new Scanner (System.in); //turing input on 

    System.out.println(); 
    String level = "Basic"; 
    if (! BASIC_VERSION) { 
     level = "Advanced"; 
    } 
    System.out.println("Welcome to the " + level + " Calculator");// have the option to pick basic or advance 

    String input = ""; 
    while (true) { 
     printPrompt();//this prompt is introduced in a different method 
     input = console.nextLine(); 
     if (isQuitRequest(input)) {//method to quit, says 'bye' 
      break;//ends 
     } 
     processInput(input);// doing the task 
    } 
    System.out.println("bye"); 
    System.out.println(); 
    console.close(); // quite keyword that closes console 
} 

static boolean isQuitRequest(String input) { 
    return input.equalsIgnoreCase("quit"); 
} 

static void processInput(String input) { 

    if (isQuitRequest(input)) { // if quit, does not reach here 
     return; 
    } 

    String error = null; 

    String[] tokens = input.split(" "); 
    if (tokens.length < 3) { 
     error = "Not enough entires."; 
    } else if (tokens.length > 3) { 
     error = "Too many entries."; 
    } 
    if (error != null) { 
     printError(input, error); 
     return; 
    } 

    String operator = tokens[1]; 
    String addition = "+"; 
    String subtraction = "-"; 
    String multiplication = "*"; 
    String division = "/"; 
    double num1 = Double.parseDouble(tokens[0]); 
    double num2 = Double.parseDouble(tokens[2]); 
    double result; 
    String number1 = tokens[0]; 
    String operation = tokens[1]; 
    String number2 = tokens[2]; 
    debug("processInput: parse result number1='" + number1 + "' " 
      + "number2='" + number2 + "' " 
      + "operation='" + operation + "'." 
     ); 

    if ((! isNumberValid(number1)) 
      || (! isNumberValid(number2) 
      || (operation.length() != 1) 
      || ("+-*/".indexOf(operation) < 0))) { 
     error = "Syntax error."; 
    } 
     // If there is an error, print it, 
     // else print the parse results. 
    if (error != null) { 
     printError(input, error); 
    } else { 
     //System.out.println("Numbers are " + number1 + " and " 
      // + number2 + ". Operation is " + operation +"."); 

     if (operator.equals(addition)){ 
      result = num1 + num2; 
      System.out.println("Answer is " + result);   
     } 
     else if (operator.equals(subtraction)){ 
      result = num1 - num2; 
      System.out.println("Answer is " + result);   
     } 
     else if (operator.equals(multiplication)){ 
      result = num1 * num2; 
      System.out.println("Answer is " + result);   
     } 
     else if (operator.equals(division)) { 
      result = num1/num2; 
      System.out.println("Answer is " + result);   
     } 
     else { 

     } 

      } 
    } 



//just validating -_- 
static boolean isNumberValid(String numstr) { 
    boolean isValid = true; 
    if (BASIC_VERSION) { 
     isValid = isValidInt(numstr); 
    } else { // ADVANCED version. 
     isValid = isValidMixedFraction(numstr);; 
    } 
    return isValid; 
} 

//This is to assure that everything entered is valid 
static boolean isValidInt(String numstr) { 
    boolean isValid = true; 
    for(int i = 0; i < numstr.length(); i++) { 
     char c = numstr.charAt(i); 
     if (! Character.isDigit(c)) { 
      isValid = false; 
     } 
    } 
    return isValid; 
} 


// formating of mixed numbers 
static boolean isValidMixedFraction(String numstr) { 
    boolean isvalid = true; 

     // get parts this string around the _ 
    String[] underscoreTokens = numstr.split("_"); 
    String firstPart = underscoreTokens[0]; 
    String secondPart; 
    if(underscoreTokens.length == 1) { 
     secondPart = null; 
    } else if(underscoreTokens.length == 2) { 
     secondPart = underscoreTokens[1]; 
    } else { // underscoreTokens.length > 2 length matters 
     return false; 
    } 


    debug("isValidMixedFraction: firstPart='"+ firstPart + "', secondPart='" 
      + secondPart +"'");   
    if (secondPart == null) { 
     // first part can be "n" or "n/n" 
     if((! isValidInt(firstPart)) && (! isValidFraction(firstPart))) { 
      isvalid = false; 
     } 
    } else { // 2nd part not null. 

     if (! isValidInt(firstPart)) { 
      isvalid = false; 
     } 
     if (! isValidFraction(secondPart)) { 
      isvalid = false; 
     } 
    } // end else second part not null 
    return isvalid; 
} 

//validating the format of the fraction if it is to be valid 
static boolean isValidFraction(String numstr) { 
    boolean isValid = true; 
     // get parts this string around the _ 
    String[] slashTokens = numstr.split("/"); 
    if(slashTokens.length != 2) { 
     return false; 
    } 

    String firstPart = slashTokens[0]; 
    String secondPart = slashTokens[1]; 

    if (! isValidInt(firstPart)) { 
     isValid = false; 
    } else if (! isValidInt(secondPart)) { 
     isValid = false; 
    } 
    return isValid; 
} 


static void printError(String input, String error) { 
    System.out.println("ERROR: " + error + " for input '" + input + "'."); 
} 

static void printPrompt() { 
    System.out.print("> "); 
} 

static void debug(String s) { 
    if (0 < DO_DEBUG) { 
     System.out.println("DBG: " + s);} 
    } 

} 

기타 :

String num1; 
String num2; 

d1 = Double.parse.Double(num 1); 
d1 = convtMixed(num1); 



double convertMixed(String fract) 
double result = 0; 
fract.split(_); 

result + = Double.parseDouble(token[0]); 

어떻게? 너는 무엇을 할 것이냐? 범위를 올바르게 사용하고 있습니까? 어디에?

+0

편집 해 주셔서 감사합니다. @kickbuttowski. 여기서 나를 도울 수 있니? – Integral

+0

다른 사람이 코드에서 1_1/2가 의미하는 바를 설명하도록 요청 했습니까? –

+0

다른 어떤 사람? 나는 그것이 무엇을 의미하는지 안다. 나는 혼란 스럽다. 1은 정수이고, 그것은 이전에 토큰이었던 것의 일부이며, 그 다음에 _ 1/2은 분수임을 나타내는 스플릿입니다. 1에서 2/2로 바꾸고 3/2로 1/2로 더하고, 1.5로 나누어 입력 된 표현식을 따라 가야합니다. – Integral

답변

0

그냥이 코드에서 아이디어를 얻을, 당신의 코드가 잘못 선생님은 당신에게 내 조언이 경우 많이 사용하지 않는 전체 코드

*을 변경할 수 있도록, 많은 문제에 직면 스위치

String number1 = tokens[0]; 
String operation = tokens[1]; 
String number2 = tokens[2]; 

if(number2 == '('){ 
tempNum = number1 ; 
tempOP =operation ; 

number1 = tokens[2]; 
operation = tokens[3]; 
number2 = tokens[4]; 
    } 

if(tokens[5] == ')'){ 
number1 = tempNum ; 
operation = tempOP ; 
number2 = result 

} 
로 대체 것이다 (당신은, 많은 경우 중첩 사용하지 않는 비교하여 사용 스위치가있는 경우)

내 조언은

012,351,641,
String addition = "+"; 
    String subtraction = "-"; 
    String multiplication = "*"; 
    String division = "/"; 



if (operator.equals(addition)){ 
      result = num1 + num2; 
      System.out.println("Answer is " + result);   
     } 
     else if (operator.equals(subtraction)){ 
      result = num1 - num2; 
      System.out.println("Answer is " + result);   
     } 
     else if (operator.equals(multiplication)){ 
      result = num1 * num2; 
      System.out.println("Answer is " + result);   
     } 
     else if (operator.equals(division)) { 
      result = num1/num2; 
      System.out.println("Answer is " + result);   
     } 

과 함께이 모든 코드를 바꿉니다 코드 수정하기
switch (operator) { 
    case "+": 
     result = num1 + num2; 
     System.out.println("Answer is " + result); 
    break; 
// other compare here 
    default: 
     break; 
    } 


String[] tokens = input.split(" "); 
    if (tokens.length < 3) { 
     error = "Not enough entires."; 
    } else if (tokens.length > 3) { 
     error = "Too many entries."; 
    } 

여기 당신은 단지 세 가지 요소로 작업을 제한 StringTokenizer

           // any input here 
StringTokenizer string = new StringTokenizer("1/(1/2)"); 
     for(int i = 0 ; i<string.countTokens() ; i++){ 
      // you can put result in array of string to refer to it alter 
      //String [] result , and fill it with tokens from StringTokenizer 
      String result = string.nextToken(); 
      if(result.equalsIgnoreCase("(")){ 
       // write my syntax here 

      } 
     } 
+0

으로 검색됩니다. 코드가 전체적으로 어떻게 잘못 되었습니까? – Integral

+0

@Integral 제 답변을 업데이트하고 아이디어를 얻으시고 직접 해보시기 바랍니다. –

0

정말 그냥 모든 일의 일을 만드는, 구문 분석 방정식의 도움을 필요로하지 않는 희망 사용합니다. 그것이 사실이라면, 제 대답이 유용 할 것입니다.

number에 대해 새 클래스를 만들어보세요. 이 새 클래스에는 두 개의 필드가 있습니다.

int divisor 
int divident 

숫자도 1 = 1/1, 2 = 2/1로 저장됩니다.

25/5를 5/1로 변경하는 정규화 기능을 제공해야합니다. 당신이해야 할 일은 그 번호의 gretest 일반적인 제수를 찾아서 그냥 나누는 것만 큼 쉬운 일입니다.

당신은 예를 들어 등을 추가, 곱하기, 나누기, 처럼 (또한 대한 의사)

Number a; 
Number b; 
divident = a.divident * b.divident; 
divisor = a.divisor * b.divident + b.divisor*a.divident; 
normalise(); 
에서

방금 ​​원시 결과를 원한다면 당신은 단순히 것입니다 기능을 구현 할 수 있습니다 작업을 재정의해야합니다 다음 (파싱 후) 1_1/2이 방법을 사용하여 처리 될 것이다 : divident 및 제수를 분할하고, 예를 들어 이중

으로 결과를 반환 번호 A : 1/1 수 b : 1/2 액션 : 추가 if 추가가 올바르게 구현되면 결과로 3/2가 반환됩니다.

응용 프로그램 모델에서 3/2를 1.5로 변경하는 것을 권장하지 않습니다. 그런 종류의 변환은 응용 프로그램의 일부로 수행되어야합니다. 이렇게하면 결과를 표시 할 때 유연해질 수 있습니다.당신은 실제 첨단 계산기에서와 같이 사용자가 원하는 어떤 방식 으로든 그것을 줄 수 있습니다.

+0

매우 유용합니다. 그러나 제 문제가 방정식을 파싱하고 정확하게 계산할 수 있습니다. – Integral