import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
Scanner scanner =new Scanner(System.in);
System.out.println("请输入第一个数");
double one= scanner.nextDouble(); //捕获输入数
System.out.println("请输入第二个数");
double two= scanner.nextDouble();
System.out.println("请选择运算符");
System.out.println("1:加 2:减 3:乘 4除");
double operator=scanner.nextDouble();
while (operator==4&&two==0){
System.out.println("被除数不能为零,请重新输入");
two= scanner.nextDouble();
}
while (operator>4||operator<1){
System.out.println("运算符不合理请重新输入");
System.out.println("1:加 2:减 3:乘 4除");
operator=scanner.nextDouble();
}
double result=0;
double remainder=0;
switch ((int)operator){ //case 是整型,需要强制转化
case 1:
result=one+two;
break;
case 2:
result=one-two;
break;
case 3:
result=one*two;
break;
case 4:
result=one/two;
remainder=one%two;
break;
}
if (operator==4){
System.out.println("结果为"+result+"余数为"+remainder);
}else {
System.out.println("结果为"+result);
scanner.close();
}
}
}
[区分使用方法](https://www.runoob.com/java/java-scanner-class.html)
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// 从键盘接收数据
// next方式接收字符串
System.out.println("next方式接收:");
// 判断是否还有输入
if (scan.hasNext()) {
String str1 = scan.next(); //scan.nextLine()
System.out.println("输入的数据为:" + str1);
}
scan.close();
}
}
``
scanner类 区分next()和nextLine()方法
最新推荐文章于 2024-06-14 15:02:13 发布