0

の計算をしたい1_1/2 * 1_1/2。その方法を理解できませんでしたが、以下は私の現在のコードであり、その下はこの実装のための私の考えたコードです。私のコードが基本的な num1 op に制限されていることはわかっています。そしてnum2。num1またはnum2が1_1/2に等しい場合、1は整数のように見えて2/2になり、1/2に追加されて3/2になり、除算を行って1.5になり、次のようになります方程式のスーツ。

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]);

どのように?あなたならどうしますか?スコープを正しく使用していますか? どこ?

4

2 に答える 2

0

このコードからアイデアを得てください。あなたのコードは間違っています。多くの問題に直面することになるので、コード全体を変更することをお勧めします

* if はあまり使わないで、 switch に置き換えてください

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 

}

コードを改良するための私のアドバイス

    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);          
        }

このコードをすべて , に置き換えます (比較が多数ある場合は、ネストされた if を使用せず、スイッチを使用します)

  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.";
    }

ここでは、操作を 3 つの要素だけに制限し、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 

           }
       }
于 2014-11-02T09:57:51.670 に答える
0

方程式を解析するのに助けが必要ないことを本当に願っています。すべてを機能させるだけです。それが本当なら、私の答えが役に立つかもしれません。

number の新しいクラスを作成してみてください。この新しいクラスには 2 つのフィールドがあります。

int divisor
int divident

整数もこのように保存されます: 1 = 1/1, 2=2/1.

正規化機能、25/5 を 5/1 に変更する機能を提供する必要があります。あなたがしなければならないことは、それらの数の最大公約数を見つけて、それらを割るだけなので、これは比較的簡単です。

加算、乗算、除算などの操作をオーバーライドする必要があります。例: (加算の疑似コード)

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

生の結果だけが必要な場合は、被除数と除数を単純に除算し、結果を double として返す関数を実装できます。

例: 1_1/2 このメソッドを使用すると、次のように処理されます (解析後): 数値 a: 1/1 数値 b: 1/2 アクション: 加算 加算が正しく実装されている場合、結果として 3/2 が返されます。

アプリケーションのモデルでは、 3/2 を 1.5 に変更することはお勧めしません。この種の多かれ少なかれ一方向の変換は、アプリケーションの一部で行う必要があります。このようにして、結果の表示に関して柔軟に対応できます。実際の高度な電卓と同じように、ユーザーが望む方法でそれを与えることができます。

于 2014-11-03T06:24:25.363 に答える