使用do while循环通过用户输入运行程序

时间:2016-11-04 20:33:08

标签: java loops while-loop

我似乎没有遇到过这个问题,希望这个问题以前没有被问过一百万次。我通过do while循环再次运行程序时遇到了麻烦,这将是一个非常方便的代码片段,但我无法弄明白,任何帮助都将不胜感激!这段代码只是为了提出这个问题..

import java.util.Scanner;
public class hello1{
public static void main(String[]args)
{

 Scanner scan = new Scanner(System.in);
 String s1 = scan.nextLine();

    do
    {
        System.out.println("Do you want to continue? Y/N");
    }

    while(s1=="Y");
 }
}

3 个答案:

答案 0 :(得分:1)

你想这样做:

String s1 = "Y";
do
{
    System.out.println("Do you want to continue? Y/N");
    s1 = scan.nextLine();
}while(s1.equalsIgnoreCase("Y"));

您不想使用String来比较==,您应该使用.equals().equalsIgnoreCase() ...

此外,每次循环时都应提示用户输入。

答案 1 :(得分:1)

我认为你的代码现在无限运行,因为[[[1, 2, 3], [0]], [[1, 2, 3], [1]], [[1, 2, 3], [1]], [[1, 2, 3], [1]]] 永远不会被重新分配。尝试将s1移至String s1 = scan.nextLine();区块。

do{}

答案 2 :(得分:0)

您需要在问题后得到回复的行 如果你需要这样做,你只需要在问题之后将scan.nextline放在do中......所以

public static void main(String[]args)
{

 Scanner scan = new Scanner(System.in);
 String s1 =""; 
    do
    {
        System.out.println("Do you want to continue? Y/N");//Print
        s1 =scan.nextLine();//Read

    }

    while(s1=="Y");

} }