簡體   English   中英

如何讓這個程序終止

[英]How make this program terminate after

下面是我寫的一個簡單的程序,它會要求輸入密碼。 如果輸入的密碼不正確,系統將提示您“密碼錯誤,您是否想再試一次?”,如果輸入的密碼不正確或其他不是以“ y”開頭的內容,它將終止程序。 問題是,如果我輸入正確的密碼“ Noah”,則會顯示“ Passwordcorrect”,然后再次循環回到“ Enter password”。 輸入正確的密碼后,如何使該程序終止? 謝謝。

import java.util.Scanner;
public class methods
{
   public static void main (String [] args)
   {
      Scanner sc = new Scanner(System.in);
      String response = "yes";
      System.out.println("Enter password:");
      while(response.charAt(0)=='y')
      {
         String input = sc.nextLine();
         if(input.equalsIgnoreCase("Noah")==true)
         {
            System.out.println("Password correct");
         }
         else if(input.equalsIgnoreCase("Noah")==false)
         {
            System.out.println("Password incorrect, would you like to try again?");
            response = sc.nextLine();
         }
      }
   }
}

使用break; 然后你可以終止。

if("Noah".equalsIgnoreCase(input)){
    System.out.println("Password correct");
    break;
}
  while(response.charAt(0)=='y')
      {  System.out.println("Enter password")
         String input = sc.nextLine();
         if(input.equalsIgnoreCase("Noah")==true)
         {
            System.out.println("Password correct");
            break;
         }
         else if(input.equalsIgnoreCase("Noah")==false)
         {
            System.out.println("Password incorrect, would you like to try again?");
            response = sc.nextLine();
         }
      }

有幾種方法。 越來越嚴重:

1)使用break語句。 這會將程序控制流帶到while循環結束之后。

2)使用return語句。 這將退出該功能,並在您的特定情況下,將結束該程序。

3)插入System.exit(n) ,其中n是一個數字,可能非零,以指示返回狀態。 這將終止Java虛擬機,並將值n返回給操作系統。

在你的情況下,我傾向於(1)或(2)。

if(input.equalsIgnoreCase("Noah")==true) { System.out.println("Password correct"); break;
}

或者您可以添加response ="no";

if(input.equalsIgnoreCase("Noah")==true) { System.out.println("Password correct"); response ="no";
}

“不”或任何不以“y”字母開頭的東西。

經過幾次更改后,我想這就是您要尋找的東西:

import java.util.Scanner;

公共類方法{

public static void main (String [] args){

    Scanner sc = new Scanner(System.in);
    String response = "yes";

    while(response.charAt(0)=='y'){
         System.out.println("Enter password:");
        String input = sc.nextLine();
        if(input.equalsIgnoreCase("Noah")==true){
            System.out.println("Password correct");
            break;
        }
        else if(input.equalsIgnoreCase("Noah")==false){
            System.out.println("Password incorrect, would you like to try again?");
            response = sc.nextLine();
        }
    }
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM