[英]Using scanner in a switch statement but my program only keeps printing the default
我是一名正在學習編程的大學新生,顯然,我對此並不陌生,但我已經參與了 switch 語句。
我的程序的目標是像一本字典。 當用戶輸入術語時,程序應輸入其含義。 但我的程序一直打印default
。 你覺得我錯過了什么? 這是我的代碼:
Scanner scn = new Scanner(System.in);
System.out.print("Enter the term:");
String term = scn.nextLine();
switch(term) {
case "Programming":
System.out.println("It is the process of creating a set of instructions to tell the computer how to do a task.");
break;
case "Java":
System.out.println("A popular high-level and object-oriented programming language developed by Sun Microsystems in 1995 and now, owned by Oracle.");
break;
case "print":
System.out.println("A method in Java that is used to display a text on the console.");
break;
case "scanner":
System.out.println("It is used to get an input data from the user, and found in the java.util package.");
break;
case "packages":
System.out.println("It organizes Java classes into namespaces, providing a unique namespace for each type it contains.");
break;
case "IDE":
System.out.println("also known as Integrated Development Environment, a software app that enables us to write & debug programs more easily.");
break;
case "switch":
System.out.println("Unlike conditionals, these statements only checks equality and only works strings, char, int and enums.");
break;
case "function":
System.out.println("A block of organized, reusable code that is used to perform a single, related action.");
break;
case "Conditional Statements":
System.out.println("It allows a program to take action based on the given condition.");
break;
case "IF-statements":
System.out.println("It is one of the conditional statement that handles one conditional expression. It either does SOMETHING or NOTHING.");
break;
default:
System.out.println("Sorry, we don't have any information about that.");
}
scn.close();
對不起,如果這是一個冗長的程序,我想盡可能地把它做成十個項目。 我也忘了告訴你,我曾嘗試刪除Scanner
並只聲明變量,程序工作(只是為了讓你知道我的程序也工作並打印字符串)。
無論如何,對於那些會回應的人,非常感謝您!
Posted 工作正常,至少對於輸入Java
參見IDEone 。
很可能輸入不正確 - switch
需要完全相同的文本:大小寫很重要,空格很重要,...
建議:在錯誤消息中包含輸入:
default:
System.out.println("Sorry, we don't have any information about '"
+ term + "'");
因此該消息可以幫助用戶(和開發人員)查看出了什么問題(甚至/特別是在生產代碼中)。
正如評論的那樣,對於這個用戶案例,最好忽略以下情況:
switch (term.toLowerCase()) {
case "programming": \\ the labels must all be lowercase too
...
case "java":
...
如果輸入末尾有空格,則可以修剪該term.trim()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.