如何使用int打印字符串

时间:2015-01-09 04:41:45

标签: java string int

我正在尝试运行此代码并基本上解决方程式。所以,我让用户写了一个等式。它看起来像这样:

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

但我无法让用户写一个字符串和一个int。我需要说String回答还是int回答?

3 个答案:

答案 0 :(得分:0)

当您希望用户输入数字时使用int,但在这里您要查找数字和其他字符的组合,因此您需要使用字符串。当你将方程存储在一个字符串中时,你可以使用其他方法将方程式分解成可解决的方法,然后将答案设置为答案。

答案 1 :(得分:0)

更简单的一方是,用户需要输入字符串,用户将输入等式。

然后是解决/计算方程式的复杂部分。

1。)创建自己的解析器以传递operands/operator

2。)为某些API提供值的等式,您可以使用MVELANTLR

答案 2 :(得分:0)

这是一个小程序,它演示了一种获取方程并分为数值/非数值的方法,前提是方程输入是空格分隔的。然后,您可以确定非数字值是什么,然后从那里继续。

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