我正在编写一个程序,要求我向中心显示一组语句 用户然后询问他是否想要返回主屏幕 但是因为我使用了一个案例,所以我无法将控制权转回给它之前的代码。我想知道如何做到这一点。以下是代码:
import java.io.*;
public class main
{
public static void main() throws IOException
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.println("START");
int ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:System.out.println("HI");
break;
/*I want a way to transfer the control from the case
such that it is transferred to
the print statement START.*/
}
}
}
答案 0 :(得分:1)
您应该使用循环,以便在System.out.println()
ch == 1
时再次控制{。}}。
import java.io.*;
public class main
{
public static void main() throws IOException
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
int ch;
do {
System.out.println("START");
int ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:System.out.println("HI");
break;
}
} while (ch == 1);
}
}
答案 1 :(得分:0)
这将工作并编译(我已经更改了主方法签名,因此您可以尝试)。
import java.io.*;
public class Test {
public static void main(String[] args) throws IOException{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
int ch;
do {
System.out.println("START");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:System.out.println("HI");
break;
}
} while (ch == 1);
System.out.println("1 was not entered, exiting");
}
}
答案 2 :(得分:-1)
有很多方法可以做到这一点。一个是将它放在一个循环中,并不断询问用户是否想要一个新的输入。
import java.io.*;
public class main
{
public static void main() throws IOException
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
int ch;
int input;
while(true)
{
System.out.println("Do you want to return to main screen. Press 1 for Yes, 0 for No");
input = Integer.parseInt(br.readLine());
if(input == 1)
{
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:System.out.println("HI");
break;
}
}
else
{
break;
}
}
即使我上面的答案是正确的,但这可能会给用户更多的可用性。 希望这会有所帮助!!