【问题标题】:**HELP** Calculating mixed fraction in Java Code**帮助** 在 Java 代码中计算带分数
【发布时间】:2014-12-26 00:52:27
【问题描述】:

我想计算1_1/2 * 1_1/2。我不知道该怎么做,但下面是我当前的代码,下面是我对此实现的想法代码。我知道我的代码仅限于基本的 num1 操作。和 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]);

怎么样?你会怎么做?我使用范围对吗?在哪里?

【问题讨论】:

  • 感谢@kickbuttowski 的编辑。你能帮帮我吗?
  • 其他人请你解释一下 1_1/2 在你的代码中是什么意思?
  • 还有什么人?我知道这意味着什么。我只是很困惑。 1 是一个整数,它是之前标记的一部分,然后 _ 是告诉 1/2 是分数的拆分。我想将 1 转换为 2/2 并将其添加到 1/2 为 3/2 并除以 1.5 以遵循输入的表情花色
  • 您可以将每个操作与操作员分开,在操作员处理之前得到结果,然后在第二次操作中使用它,我将为此提供代码
  • 谢谢。在这一点上,我只想看看这一切是如何完成的。 (自学java)

标签: java arrays scope calc


【解决方案1】:

从这段代码中得到想法,你的代码是错误的先生,你会遇到很多麻烦,所以我建议你改变你的整个代码

*不要用很多 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)

  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 

           }
       }

【讨论】:

  • 这让我更加困惑。我的代码整体有什么问题?
  • @Integral 我更新了我的答案,得到一些想法并尝试自己做
【解决方案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();

如果您只想要原始结果,您可以实现简单地除除数和除数并将结果作为双精度返回的函数

例如:1_1/2 使用该方法会被处理如下(解析后): a 号:1/1 b 号:1/2 作用:加法 如果加法正确执行,它将返回 3/2 作为结果。

在您的应用程序模型中,我不建议将 3/2 更改为 1.5 。这种或多或少的一种方式转换应该在应用程序的 wiev 部分完成。这样,您可以灵活地显示结果。您可以以用户想要的任何方式提供它,就像在真正的高级计算器中一样。

【讨论】:

  • 非常有帮助,但我的问题是解析方程并且它能够正确地进行计算。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-07
  • 1970-01-01
  • 2020-02-22
  • 1970-01-01
相关资源
最近更新 更多