![](/img/trans.png)
[英]How do I Throw an IllegalArgumentException that won't terminate my program?
[英]Why won't my program terminate when i input END?
我正在嘗試在控制台中輸入“ END”時終止我的代碼,但是我的代碼無法正常運行,而且似乎看不到哪里出了問題,順便說一句,到目前為止我還沒有學會如何調試這在很大程度上與為什么我不知道這一點有關。 如果可以的話,請提供幫助。
import java.util.*;
class Main
{
public static void main(String args[])
{
int j = 0;
while (j++ <= 3) {
// Create Scanner object to take input from command prompt
Scanner s=new Scanner(System.in);
// Take input from the user and store it in st
String st = "";
while (!st.equals("END")) {
{
st=s.nextLine();
// Initialize the variable count to 0
int count=0;
// Convert String st to char array
char[] c=st.toCharArray();
// Loop till end of string
for(int i=0;i<st.length();i++)
// If character at index 'i' is not a space, then increment count
if(c[i]!=' ') count++;
// Print no.of spaces
System.out.printf("[%4d] spaces in ", +(st.length()-count));
// Print no.of spaces
System.out.println('"' + st + '"');
}
j++;
}
}
}
由於您有while (j++ <= 3) { ... }
如果您兩次輸入“ END”,則程序將結束。
因為您有兩個while循環嵌套。 您在第二個while循環中輸入“ END”,然后第二個循環結束是正確的。 但是,正如您所看到的,它結束后將開始第一個循環,即while (j++ <= 3) {
並且在此while循環中,它等待用戶輸入3次,這對應於Scanner s=new Scanner(System.in);
,因此程序不退出是正常的。 如果您希望程序在某些輸入后完成,則可能需要使用System.exit(-1);
命令。 我已經根據您的評論添加了代碼。
import java.util.*;
class Main {
public static void main(String args[]) {
int j = 0;
while (j++ <= 3) {
// Create Scanner object to take input from command prompt
Scanner s = new Scanner(System.in);
// Take input from the user and store it in st
String st = s.nextLine();
if (!st.equals("END")) {
// Initialize the variable count to 0
int count = 0;
// Convert String st to char array
char[] c = st.toCharArray();
// Loop till end of string
for (int i = 0; i < st.length(); i++)
// If character at index 'i' is not a space, then increment count
{
if (c[i] != ' ') {
count++;
}
}
// Print no.of spaces
System.out.printf("[%4d] spaces in ", +(st.length() - count));
// Print no.of spaces
System.out.println('"' + st + '"');
} else {
System.exit(-1);
}
}
}
}
我只是添加了一個if條件,而不使用循環。
public static void main(String args[]) {
int j = 0;
while (j++ <= 3) {
// Create Scanner object to take input from command prompt
Scanner s = new Scanner(System.in);
// Take input from the user and store it in st
String st = "";
st = s.nextLine();
if (st.equalsIgnoreCase("END")) {
j = 5;
}
// Initialize the variable count to 0
int count = 0;
// Convert String st to char array
char[] c = st.toCharArray();
// Loop till end of string
for (int i = 0; i < st.length(); i++) // If character at index 'i' is not a space, then increment count
{
if (c[i] != ' ') {
count++;
}
}
// Print no.of spaces
System.out.printf("[%4d] spaces in ", +(st.length() - count));
// Print no.of spaces
System.out.println('"' + st + '"');
j++;
}
}
當我得到輸入端時,基本上我會做的就是將j的值更改為5,以便終止第一個循環。 別再服葯了
您需要這種解決方案還是需要輸入3次?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.