简体   繁体   中英

How to print a string with an int

I am trying to get this code to run and basically solve an equation. So, I asked the user to write an equation. It looked like this:

System.out.println("Write an equation and I will solve for x.");
int answer = in.nextLine(); 

But I can't get the user to write a string and an int. Do I need to say String answer or int answer?

An int is used when you want the user to enter a number, but here you're looking for a combination of numbers and other characters, so you will need to use a string. When you have the equation stored in a string, you can use other methods to split up the equation into something solvable, then set int answer to whatever the answer comes out to be.

On a simpler side, String will be required input from the user, User will enter the equation.

Then comes the complex part of solving/computing the equation.

1.) create your own parser to pass operands/operator .

2.) Provide a equation with values to some API , you can make use of MVEL or ANTLR

Here's a little program that demonstrates one way to get the equation and divide into numeric / non-numeric values provided the equation input is space delimited. You can then determine what the non-numeric values are and proceed from there.

import java.util.Scanner;

public class SolveX{

    public static void main(String[] a){

        Scanner in = new Scanner(System.in);
        System.out.println("Write an equation and I will solve for x.");
        String input = "";

        while( in.hasNext() ){
            input = in.next();
            try{  
                double d = Double.parseDouble(input);
                System.out.println("Double found at: " + input);
                //  Do what you need to with the numeric value
            }  
            catch(NumberFormatException nfe){
                System.out.println("No double found at: " + input);
              //    Do what you need to with the non numeric value 
            }
        }
    }//end main
}//end SolveX class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM