我正在尝试运行这段代码,并且基本上解决了一个方程。所以,我要求用户写一个方程式。它看起来是这样的:
System.out.println("Write an equation and I will solve for x.");
int answer = in.nextLine();
但是我不能让用户写一个字符串和一个int。我需要说字符串答案还是整型答案?
发布于 2015-01-09 04:49:05
当您希望用户输入一个数字时,可以使用int,但这里您要查找的是数字和其他字符的组合,因此需要使用字符串。当您将方程存储在字符串中时,您可以使用其他方法将方程拆分为可解的内容,然后将int answer设置为任何结果。
发布于 2015-01-09 04:55:01
发布于 2015-01-09 07:03:34
下面是一个小程序,它演示了一种获取公式并将其分成数值/非数值的方法,前提是公式输入是以空格分隔的。然后,您可以确定非数字值是什么,并从那里继续。
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
https://stackoverflow.com/questions/27853946
复制