【发布时间】:2013-10-16 04:19:46
【问题描述】:
import java.util.Scanner;
public class Improved {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number operaion number: ");
int operand1 = Integer.parseInt(input.nextLine());
char expo1 = input.next().charAt(0);
int operand2 = Integer.parseInt(input.nextLine());
System.out.println( operand1 + expo1 + operand2 + "=");
if ( expo1 == '/' && operand2 == '0' ){
System.out.println("Cannot divide by zero"); }
else
if (expo1 == '-') {
System.out.println(operand1-operand2);
} else
if (expo1 == '+') {
System.out.println(operand1+operand2);
} else
if (expo1 == '/') {
System.out.println(operand1/operand2);
} else
if (expo1 == '%') {
System.out.println(operand1%operand2);
}
else{
System.out.println(" Error.Invalid operator.");
}
}
}
//This bottom works, but I found out that this is not what is supposed to be done with this problem
/*
public class Else {
public static void main(String[] args) {
int operand1;
char exp1;
int operand2;
if (args.length != 3 ) {
System.err.println("*** Program needs 3 arguements***");
System.err.println("Usage: java Else int1 exp int2");
System.exit(1);
}
operand1 = Integer.parseInt(args[0]);
exp1 = args[1].charAt(0);
operand2 = Integer.parseInt(args[2]);
System.out.print(args[0] + args[1] + args[2] + "=");
if(exp1 == '-') {
System.out.println(operand1 - operand2);
} else
if (exp1 == '+') {
System.out.println(operand1 + operand2);
} else
if (exp1 == '/') {
System.out.println(operand1 / operand2);
} else
if (exp1 == '%') {
System.out.println(operand1 % operand2);
}
else{
System.out.println(" Error.Invalid operator.");
}
}
}
*/
我希望程序做的是要求输入数学运算 1/2 或 1%2(不是乘法) , 但就像没有空格一样。不过,我想检查正在执行哪个操作,这就是我放置 if 语句的原因。我没有得到的是程序如何知道操作何时出现在字符串中。我什至不确定我是否设置正确。总的来说,我想要一个字符串,它先读取数字,然后再读取操作,然后再读取数字。如果这看起来像是在做我的硬件,我很抱歉,但我已经尝试过多次制作这个程序,但不明白我如何用字符串来做到这一点。我写了第二个来表明我已经多次这样做了,所以你可以忽略它。非常感谢!
【问题讨论】:
-
我认为
String text = input.nextLine();后跟text = text.replaceAll("\s", "");会消除用户输入的文本中的所有空格。您可以使用进一步的正则表达式来分解String,提取您需要的部分或另一个Scanner来扫描每个元素(nextInt等...)
标签: java string conditional-statements