2015-10-19 380 views
0
import java.io.*; import java.util.*; 
public class Test{ 
public static void main(String args[]){ 
    while(true) 
    { 
     Scanner kbReader=new Scanner(System.in); 
     System.out.println("Whats your name?"); 
     String s=kbReader.nextLine(); 
     String at=s.substring(0,1); 
     if(at.equalsIgnoreCase("t")) 
     { 
      System.out.println("You're AWESOME!!!"); 
     } 
     else 
     { 
      System.out.println("You suck"); 
     } 
    } 
} 
} 

我的代碼是一個簡單的輸入代碼,它要求輸入您的姓名並只查看第一個字母,並通過if語句運行該代碼。我使用一個while循環無限循環代碼。如果他們想要退出while循環,我會如何獲得一行代碼來要求輸入字符串的代碼?while循環和While循環的退出

回答

0

只要爲一個特定字符或字符串做一個if並使用returnbreak

例如:

if (at.equalsIgnoreCase("Q")) { 
    break; 
} 

編輯:選擇可以是在循環結束時再次詢問用戶是否希望繼續:

System.out.println("Do you want to continue ? [Y]/N"); 
String s=kbReader.nextLine(); 
if (at.equalsIgnoreCase("N")) { 
    break; 
} 
0

可以終止循環通過捕捉一個特定的角色。你可以提供查詢的名稱上println聲明字符:

while(true) 
{ 
    Scanner kbReader=new Scanner(System.in); 
    System.out.println("Whats your name? Or type # to end"); 
    String s=kbReader.nextLine(); 
    String at=s.substring(0,1); 
    if(at.equalsIgnoreCase("#")) 
    { 
     break; 
    } 
    else if(at.equalsIgnoreCase("t")) 
    { 
     System.out.println("You're AWESOME!!!"); 
    } 
    else 
    { 
     System.out.println("You suck"); 
    } 
} 
0

包括轉義序列,如一個整數,到工作流程:

String s=kbReader.nextLine(); 
if (s.equalsIgnoreCase("0") { // hopefully no one is named zero :) 
    break; 
} 
String at=s.substring(0,1); ... 
0
中,你可以做一個更優雅的方式

菜單:

import java.io.*; import java.util.*; 
public class Test{ 
public static void main(String args[]){ 
    while(true) 
    { 
     Scanner kbReader=new Scanner(System.in); 
     System.out.println("Whats your name?\nPress 0 to quit program"); 
     String s=kbReader.nextLine(); 
     String at=s.substring(0,1); 
     if(at.equalsIgnorecase("0")){ 
     break; 
     } 
     if(at.equalsIgnoreCase("t")) 
     { 
      System.out.println("You're AWESOME!!!"); 
     } 
     else 
     { 
      System.out.println("You suck"); 
     } 
    } 
} 
}