我的意思是在case里写输入语句
时间: 2023-08-11 16:17:48 浏览: 44
是的,您可以在Switch语句的case语句中使用输入语句。这可以让您在每个case语句中向用户请求输入,以便他们可以提供不同的输入值,而不是在Switch语句之前一次性输入所有输入值。
以下是一个示例代码,展示了如何在Switch语句的case语句中使用输入语句:
```
import java.util.Scanner;
public class SwitchExample {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num;
System.out.println("请选择一个选项:");
System.out.println("1. 显示日期");
System.out.println("2. 显示时间");
System.out.println("3. 显示天气预报");
num = input.nextInt();
switch (num) {
case 1:
System.out.println("您选择了显示日期");
System.out.println("请输入当前年份:");
int year = input.nextInt();
System.out.println("请输入当前月份:");
int month = input.nextInt();
System.out.println("请输入当前日期:");
int day = input.nextInt();
System.out.println("当前日期是:" + year + "年" + month + "月" + day + "日");
break;
case 2:
System.out.println("您选择了显示时间");
System.out.println("请输入当前小时数:");
int hour = input.nextInt();
System.out.println("请输入当前分钟数:");
int minute = input.nextInt();
System.out.println("请输入当前秒数:");
int second = input.nextInt();
System.out.println("当前时间是:" + hour + "时" + minute + "分" + second + "秒");
break;
case 3:
System.out.println("您选择了显示天气预报");
System.out.println("请输入您所在城市名称:");
String city = input.nextLine();
System.out.println("今天的天气预报是:晴,温度25℃");
break;
default:
System.out.println("输入非法选项");
}
}
}
```
在这个示例代码中,我们在每个case语句中使用了输入语句,以便用户可以提供不同的输入值。注意,对于字符串输入,我们使用了`input.nextLine()`方法来接受输入,因为`nextInt()`方法只会读取输入中的整数部分,而忽略任何后续的换行符或空格。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)