Java关于如何取消系统输入的问题

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

Java Question on how to cancel system input

问题

import java.util.Scanner;

public class MiniTranslator {
    public static void main(String[] args) {
        String message = "";
        do {
            //Declaring scanner
            Scanner keyboard = new Scanner(System.in);

            //Printing greeting message

            System.out.println("---------------------------------------------------------\n"
                    + "\tLanguage Translator Program\n"
                    + "---------------------------------------------------------");

            System.out.println("Please enter the input sentence (press q to exit): \n");
            message = keyboard.nextLine();
            String[] arr = message.split("[ ,.]+", 8);
            String name = arr[0];
            String city = arr[3];
            String country = arr[4];
            String year = arr[6];

            int noOfYears = 2020 - (Integer.parseInt(year));

            System.out.println("\n" + name + " stay in " + city + " for " + noOfYears + " years. "
                    + city + " is in " + country + ".");
            System.exit('q');
            keyboard.close();
        } while (message != "q");
        if (message == "q") {
            System.out.println("Thanks for using translator program");
        }
    }
}
英文:

I want to print last message when user inputs q but it gives an error.


Language Translator Program

Please enter the input sentence (press q to exit):

Robin came to Montreal, Canada in 2009.

Robin stays in Montreal for 11 years. Montreal is in Canada.

Please enter the input sentence (press q to exit):

Lucy came to Berlin, Germany in 2000.

Lucy stay in Berlin for 20 years. Berlin is in Germany.

Please enter the numbers along operation (press q to exit):

q

Thanks for using translator program.

import java.util.Scanner;

public class MiniTranslator {
	public static void main(String[] args) {
		String message ="";
		do {
			//Declaring scanner
			Scanner keyboard = new Scanner(System.in);

			//Printing greeting message

			System.out.println("---------------------------------------------------------\n" 
		                         +"\tLanguage Translator Program\n"
		                        +"---------------------------------------------------------");

			System.out.println("Please enter the input sentence (press q to exit): \n");
			message = keyboard.nextLine();
			String[] arr = message.split("[ ,.]+",8);
			String name = arr[0];
			String city = arr[3];
			String country = arr[4];
			String year = arr[6];

			int noOfYears =2020 - (Integer.parseInt(year));

			System.out.println("\n" + name +" stay in " + city +" for " + noOfYears +" years. " 
		                        + city +" is in " + country +".");
            System.exit('q');
			keyboard.close();
		}
		while(message!="q");
		if(message =="q") {
			System.out.println("Thanks for using translator program");
		}
	}
}

答案1

得分: 2

好的,以下是翻译好的部分:

"message!="q"" 不是在Java中比较 String 的方法,你应该使用 !"q".equals(message) 来进行比较(同样,== 也应该变成 "q".equals(message))。

但是,你的主要问题在这里...

System.out.println("请输入输入句子(按q退出): \n");
message = keyboard.nextLine();
String[] arr = message.split("[ ,.]+",8);
String name = arr[0];
String city = arr[3];
String country = arr[4];
String year = arr[6];

int noOfYears =2020 - (Integer.parseInt(year));

你假设了 message 包含的内容,而没有花时间确保它包含你认为的内容。

因此,当 messageq 时,你的数组将只包含一个元素,所以一旦执行 String city = arr[3];,你就会遇到数组越界问题。

一个“简单”的解决方案可能是在拆分之前检查 message 是否等于 q,但更好的解决方案是检查数组中的元素数量...

if (arr.length == 7) {
    // 处理结果
} else if (!"q".equals(message)) {
    // 无效输入
}

另外,正如已经提到的,你应该在循环外部创建你的 Scanner,而不要关闭它 - 因为这会终止不死的系统输入流,这并不好。

英文:

Ok, you have a number of immediate issues

message!="q" is not how you compare Strings in Java, you should be using !"q".equals(message) instead (same with ==, which would become "q".equals(message) for example)

But, your main problem is here ...

System.out.println("Please enter the input sentence (press q to exit): \n");
message = keyboard.nextLine();
String[] arr = message.split("[ ,.]+",8);
String name = arr[0];
String city = arr[3];
String country = arr[4];
String year = arr[6];

int noOfYears =2020 - (Integer.parseInt(year));

You've made an assumption on what message contains, instead of taking the time to ensure if contains what you think.

So, when message is q, your array will contain only one element, so as soon as you do String city = arr[3]; you have an array index out of bounds issue.

A "simple" solution might be to check if message is equal to q before you split, but a better solution would be to check the number of elements in array...

if (arr.length == 7) {
    // Process the result
} else if (!"q".equals(message)) {
    // Invalid input
}

Also, as has been stated, you should create your Scanner once, outside of the loop and NOT close it - as you'd terminate the undying system input stream as well, which isn't pretty

huangapple
  • 本文由 发表于 2020年10月4日 09:14:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/64190339.html
匿名

发表评论

匿名网友

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

确定