我正在编写一个程序,它要求我向
然后用户问他是否要返回主屏幕。
但是由于我使用的是案例,因此无法将控制权转移回它之前的代码。我想知道我该怎么做。代码如下:
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.*/
}
}
}
你应该使用 loop,这样控制将在第一次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);
}
}
这将工作和编译(我已经更改了主方法签名,以便您可以尝试一下(。
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");
}
}
有很多方法可以做到这一点。一种是让它循环并不断询问用户是否想要新的输入。
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;
}
}
即使我上面的答案是正确的,但这可能会给用户带来更多的可用性。希望这有帮助!!