读取用户的输入,直到输入quit时退出

今天面试时碰到了一个机试题,记录一下:

读取用户的输入,直到输入quit时退出

把String类型转换为Integer类型

当输入为1时,返回true,输入不为1时返回false
不可用一个try、catch捕获所有异常 单独处理为空时的错误

public static void main(String[] args) {
		String l_input;
		Integer a = null;
		BufferedReader bufferedReader = null;
		System.out.println("请输入字符串:");

		try {
			while (true) {
				bufferedReader = new BufferedReader(new InputStreamReader(System.in));
				l_input = bufferedReader.readLine();

				if(l_input.equals("quit")) {
					System.out.println("finish");
					break;
				}

				// 判断字符串是否可以转换为Integer类型
				try {
						a = Integer.parseInt(l_input);
					// 判断输入是否为1,若为1,输出true,否则输出false
					if (a == 1) {
						System.out.println(true);
					} else {
						System.out.println(false);
					}
				} catch (NumberFormatException e) {
					System.out.println("转换失败:");
				}

				System.out.println("您输入了:" + l_input);
			}

		} catch (IOException e) {
			e.printStackTrace();
		}

	}
String转换为Integer类型两种方式:
int a = Integer.parseInte(str);
int a = Integer.valueOf(str).intValue();
注意:String类型转换为int类型时记得捕获异常,
NumberFormatException



猜你喜欢

转载自blog.csdn.net/qq_14994863/article/details/80053738
今日推荐