【发布时间】:2018-01-13 11:50:37
【问题描述】:
感谢您查看我的问题。我想问一下,我可以在不使用扫描仪的情况下将字符或算术运算符作为用户的输入吗?
这是我编写程序的代码,该程序使用算术运算符对两个数字执行代数运算。 (代数运算为+、-、*、/、%)
import java.util.Scanner;
class q4
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in );
int a, b;
char operator;
System.out.print("Enter A : ");
a=s.nextInt();
System.out.print("Enter B : ");
b=s.nextInt();
System.out.print("Enter operator (+, -, *, /)");
operator = s.next().charAt(0);
double addition = a+b;
double subtraction = a-b;
double multiplication = a*b;
double division = a/b;
switch(operator)
{
case '+' :
{
System.out.print("Total after Addition is : "+addition);
break;
}
case '-' :
{
System.out.print("Total after Subtraction is : " +subtraction);
break;
}
case '*' :
{
System.out.print("Total after Multiplication is : "+multiplication);
break;
}
case '/' :
{
System.out.print("Total after Division is : "+division);
break;
}
default :
{
System.out.print("Please select proper operator");
return;
}
}
}
}
感谢您在很忙的时候回复我:)
【问题讨论】:
-
你为什么不想使用扫描仪?
-
您可以随意使用
System.in字段。这是一个普通的InputStream,它有一个方法read()从输入流中读取下一个字节。但这里的问题到底是什么? -
代数?无论如何...如果您使用 Java SE6 或更高版本,您可以使用 BufferedReader 类并将其与 InputStreamReader 类甚至 Console 类一起包装(见SO Post)。或者创建一个 GUI。甚至可能坚持使用 Scanner 类,它的效果相当不错。 :)
标签: java