Java 中的循环、重复程序(Java 初学者问题)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5773082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Loop,Repeat Program in Java (Java Beginner question)
提问by Mohammad Fadin
I want when the user enter any choice (1,2,3,4) it will show the user (Still under constriction) then he gets back to the program again. how can I do that using if statment or a way other then SWTICH method??
我希望当用户输入任何选项 (1,2,3,4) 时,它会向用户显示(仍然受到限制),然后他再次返回程序。我如何使用 if 语句或 SWTICH 方法以外的方法来做到这一点?
import java.util.Scanner;
public class Tt {
public static void main(String [] args) {
Scanner kb= new Scanner (System.in);
int choice;
do{
System.out.println("Please enter your choice from the following menu:");
System.out.println("1. Enter student tanscript");
System.out.println("2. Display transcript summary");
System.out.println("3. Read student transcript from a file");
System.out.println("4. Write 1transcript summary to a file");
System.out.println("5. Exit");
choice = kb.nextInt();
switch (choice) {
case 1:
case 2:
case 3:
case 4:
System.out.println("Under construction");
System.out.println();
break;
case 5:
break;
}
}while (choice > 0 && choice < 5);
}
}
回答by Tom Wadley
if (choice == 1 || choice == 2 || choice == 3 || choice == 4) {
System.out.println("Under construction");
System.out.println();
}
or
或者
if (choice >= 1 || choice <= 4) {
System.out.println("Under construction");
System.out.println();
}
EDIT: If you want space to implement each option (similar to what your switch statement gives you now), you could write it like this:
编辑:如果你想要空间来实现每个选项(类似于你现在的 switch 语句给你的),你可以这样写:
if (choice == 1) {
System.out.println("Under construction");
System.out.println();
} else if (choice == 2) {
System.out.println("Under construction");
System.out.println();
} else if (choice == 3) {
System.out.println("Under construction");
System.out.println();
} else if (choice == 4) {
System.out.println("Under construction");
System.out.println();
} else {
System.out.println("Unrecognised selection");
System.out.println();
}
回答by Suroot
Instead of switch you could have an array of option executors. When the user hits a number (i.e. 1) it relates to the array element 0 which then gets executed. This allows for more extensibility as you can just create new Executors.
您可以拥有一组选项执行器,而不是 switch。当用户点击一个数字(即 1)时,它与然后被执行的数组元素 0 相关。这允许更多的可扩展性,因为您可以创建新的 Executor。
private interface Executor {
public void run();
}
...
public static void main(String[] str) {
Executor temp = new Executor() {
public void run() {
System.out.println("Under Construction");
}
}
Executor[] ex = {temp, temp, temp, temp};
while(true) {
System.out.println("Please enter your choice from the following menu:");
System.out.println("1. Enter student transcript");
System.out.println("2. Display transcript summary");
System.out.println("3. Read student transcript from a file");
System.out.println("4. Write 1transcript summary to a file");
System.out.println("5. Exit");
choice = kb.nextInt();
if(choice > 0 && choice < ex.length) {
ex[choice - 1].run();
} else {
break;
}
}
}
回答by ICR
I'm not too sure exactly what you mean by the question. Do you want to allow the user to choose again if they choose an 'under construction' option? In that case I would break it out into a method that can be re-called to show the menu again.
我不太确定你问的问题到底是什么意思。如果用户选择“建设中”选项,您是否要允许他们再次选择?在这种情况下,我会将其分解为一种可以重新调用以再次显示菜单的方法。
public static void main(String [] args) {
showMenu();
}
public static void showMenu() {
Scanner kb = new Scanner (System.in);
int choice;
System.out.println("Please enter your choice from the following menu:");
System.out.println("1. Enter student tanscript");
System.out.println("2. Display transcript summary");
System.out.println("3. Read student transcript from a file");
System.out.println("4. Write 1transcript summary to a file");
System.out.println("5. Exit");
choice = kb.nextInt();
switch (choice) {
case 1:
case 2:
case 3:
case 4:
System.out.println("Under construction");
System.out.println();
showMenu();
return;
case 5:
return;
default:
showMenu();
return;
}
}
If you want to remove the lengthy switch statement, you could possibly create a Map<int, MenuAction>
, where MenuAction
is an interface that has a method DoAction
that performs the behavior.
如果您想删除冗长的 switch 语句,您可以创建一个Map<int, MenuAction>
, where MenuAction
is 一个具有DoAction
执行该行为的方法的接口。
public interface MenuAction {
void doAction();
}
public UnderConstructionAction implements MenuAction {
public void doAction() {
System.out.println("Under construction");
System.out.println();
}
}
public ExitAction implements MenuAction {
public void doAction() {
}
}
public class MainClass {
static {
Map<Integer, MenuAction> menuActions = new HashMap<Integer, MenuAction>();
menuActions.put(1, new UnderConstructionAction());
menuActions.put(2, new UnderConstructionAction());
menuActions.put(3, new UnderConstructionAction());
menuActions.put(4, new UnderConstructionAction());
menuActions.put(5, new ExitAction());
}
public static void main(String [] args) {
showMenu();
}
public static void showMenu() {
Scanner kb = new Scanner (System.in);
int choice;
System.out.println("Please enter your choice from the following menu:");
System.out.println("1. Enter student tanscript");
System.out.println("2. Display transcript summary");
System.out.println("3. Read student transcript from a file");
System.out.println("4. Write 1transcript summary to a file");
System.out.println("5. Exit");
choice = kb.nextInt();
if (!menuActions.containsKey(choice)) {
showMenu();
return;
}
menuActions.get(choice).doAction();
}
}
You could even go further and create a StudentTranscriptAction
, TranscriptSummaryAction
etc. that inherits from UnderConstructionAction
, but has a Description
field and use those to build up the menu output.
你甚至可以走得更远,创造StudentTranscriptAction
,TranscriptSummaryAction
等等,从继承UnderConstructionAction
,但有一个Description
领域,并利用这些建立起来的菜单输出。
Note: I've done little Java, and haven't tested this code at all.
注意:我只做过一点 Java,根本没有测试过这段代码。
回答by extraneon
An alternative to ICR's answer is using the Observer pattern. If a selection is made an event is generated (like when a JButton is pushed), and other objects can subscribe to that event.
ICR 答案的替代方法是使用Observer 模式。如果进行了选择,则会生成一个事件(例如按下 JButton 时),并且其他对象可以订阅该事件。
You can choose to locally handle the event, like the Java Swing architecture does, or go for a central Event Bus like architecture.
您可以选择在本地处理事件,就像 Java Swing 架构那样,或者选择像架构一样的中央事件总线。
On the one hand, the observer pattern is more easily extensible because you would not have to change the MainClass code at all, on the other hand it might make the code less transparent as all depends on the runtime configuration - which listeners have registered themselves.
一方面,观察者模式更容易扩展,因为您根本不必更改 MainClass 代码,另一方面,它可能会使代码不那么透明,因为所有这些都取决于运行时配置 - 哪些侦听器已自行注册。
Also have a look at the examples at the ultimate site of knowledge, wikipedia:)
还可以查看知识的最终站点维基百科上的示例:)
An example:
一个例子:
public class Foo extends Observable {
// The Observers would normally be in their own file
static class OneHandler implements Observer {
public void update(Observable o, Object val) {
if (val != null && val.equals(1)) {
System.out.println("One pressed");
}
}
}
static class TwoHandler implements Observer {
public void update(Observable o, Object val) {
if (val != null && val.equals(2)) {
System.out.println("Two pressed");
}
}
}
static class EverythingHandler implements Observer {
public void update(Observable o, Object val) {
if (val != null) {
System.out.println(val + " pressed");
} else {
System.out.println("Null pressed");
}
}
}
public void askQuestion() {
// ask the question
System.out.println("Ask Question");
setChanged(); // otherwise observers are not notified
notifyObservers(1); // in this example 1 is pressed (will be autoboxed to Integer)
}
public static void main(String[] args) {
// main and Foo would usually not be in the same class
Foo foo = new Foo();
// Register observers.
// Note that you do not bind OneHandler to 1 here, but that OneHandler
// itself knows when to react. It could be that more Observables would react
// to the same event
// You would not know the order in which they are called.
foo.addObserver(new OneHandler());
foo.addObserver(new TwoHandler());
foo.addObserver(new EverythingHandler());
foo.askQuestion();
}
}
回答by Jason
Maybe pattern matching?
也许模式匹配?
String pattern = "[1234]";
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
input = br.readLine();
if(input.matches(pattern)) {
// construction
}