如何在Java中使用Scanner读取字符串?

huangapple go评论72阅读模式
英文:

How do I get the Scanner in java to read a string?

问题

import java.util.*;

public class Main {

    public static void main(String[] args) {

        String input;
        Scanner scan = new Scanner(System.in);
        
        System.out.println("Enter your age, or enter 'q' to quit the program.");
        input = scan.next();
        
        if (input.equalsIgnoreCase("q")) {
            return;
        }

        int age = Integer.parseInt(input);
        
        System.out.println("Your age is " + age);
    }
}
英文:

How would I get my program to quit when the user enters q?
Is there something wrong with the scanner?


My code

import java.util.*;
public class Main{

         public static void main(String []args){
             
             int age;
             
            Scanner scan = new Scanner(System.in);
            System.out.println("Enter your age, or enter 'q' to quit the program.");
            age = scan.nextInt();
            
            
            if(age.equals("q") || age.equals("Q")){
                
                return 0;
                
            }
            
            
            
            System.out.println("Your age is " + age);
            
            
            
         }
    
    }

答案1

得分: 0

我在你的代码中主要看到两个问题:

  1. 代码缺少一个循环来重复询问年龄。有许多种方法(forwhiledo-while)可以编写循环,但我认为对于这种情况,do-while 是最合适的,因为它始终至少执行do块中的语句一次。
  2. age 的类型是 int,因此无法与字符串进行比较,例如你的代码 age.equals("q") 是不正确的。处理这种情况的一种好方法是将输入存储在类型为 String 的变量中,并在需要时检查其值,以确定是否应该允许/禁止处理它(例如尝试将其解析为 int)。

注意,当你尝试解析一个无法解析为 int 的字符串(例如 "a")时,会得到一个 NumberFormatException,你需要处理它(例如显示错误消息,更改某些状态等)。

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int age;
        String input;
        Scanner scan = new Scanner(System.in);
        boolean valid;

        do {
            // 假设输入是有效的
            valid = true;
            System.out.print("输入你的年龄,或输入 'q' 退出程序: ");
            input = scan.nextLine();

            if (!(input.equals("q") || input.equals("Q"))) {
                try {
                    // 尝试将输入解析为整数
                    age = Integer.parseInt(input);
                    System.out.println("你的年龄是 " + age);
                } catch (NumberFormatException e) {
                    System.out.println("无效输入");
                    // 将 valid 的值更改为 false
                    valid = false;
                }
            }
        } while (!valid || !(input.equals("q") || input.equals("Q")));
    }
}

一个示例运行:

输入你的年龄,或输入 'q' 退出程序: a
无效输入
输入你的年龄,或输入 'q' 退出程序: 12.5
无效输入
输入你的年龄,或输入 'q' 退出程序: 14
你的年龄是 14
输入你的年龄,或输入 'q' 退出程序: 56
你的年龄是 56
输入你的年龄,或输入 'q' 退出程序: q
英文:

I can see mainly two problems in your code:

  1. It lacks a loop to repeat asking for age again. There can be many ways (for, while, do-while) to write a loop but I find do-while most appropriate for such a case as it always executes the statements within the do block at least once.
  2. age is of type, int and therefore it can not be compared with a string e.g. your code, age.equals("q") is not correct. A good way to handle such a situation is to get the input into a variable of type, String and check the value if it should allow/disallow processing it (e.g. trying to parse it into an int).

Note that when you try to parse a string which can not be parsed into an int (e.g. "a"), you get a NumberFormatException which you need to handle (e.g. show an error message, change some state etc.).

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		int age;
		String input;
		Scanner scan = new Scanner(System.in);
		boolean valid;

		do {
			// Start with the assumption that input will be valid
			valid = true;
			System.out.print("Enter your age, or enter 'q' to quit the program: ");
			input = scan.nextLine();

			if (!(input.equals("q") || input.equals("Q"))) {
				try {
					// Try to parse input into an int
					age = Integer.parseInt(input);
					System.out.println("Your age is " + age);
				} catch (NumberFormatException e) {
					System.out.println("Invalid input");
					// Change the value of valid to false
					valid = false;
				}
			}
		} while (!valid || !(input.equals("q") || input.equals("Q")));
	}
}

A sample run:

Enter your age, or enter 'q' to quit the program: a
Invalid input
Enter your age, or enter 'q' to quit the program: 12.5
Invalid input
Enter your age, or enter 'q' to quit the program: 14
Your age is 14
Enter your age, or enter 'q' to quit the program: 56
Your age is 56
Enter your age, or enter 'q' to quit the program: q

huangapple
  • 本文由 发表于 2020年10月17日 05:33:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/64396673.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定