[英]I'm trying to make a loop
import javax.swing.JOptionPane;
public class New {
public static void main (String[] args) {
String name = JOptionPane.showInputDialog("Enter your name... ");
do{JOptionPane.showInputDialog( "YOUR NAME...");}
while(name.equals(""));
JOptionPane.showMessageDialog(null, "Hello and welcome!, "+name);
int age = Integer.parseInt(JOptionPane.showInputDialog("Enter your age... "));
if(age>=60) { JOptionPane.showMessageDialog(null, "Ok Boomer!");
System.exit(0);}
else if(age>=18) { JOptionPane.showMessageDialog(null, "You are an adult, Welcome!");
}
else { JOptionPane.showMessageDialog(null, "You are a kid!");
System.exit(0);}
String day = JOptionPane.showInputDialog("What's the day? ");
if(day.equals("Monday")) { JOptionPane.showMessageDialog(null, "Welcome to Java club!");
}
else {JOptionPane.showMessageDialog(null, "Try again later!");
}
}
}
我希望我的循環在沒有輸入名稱時開始並在有名稱時結束,即使我輸入名稱它也會讓我保持循環(我是初學者)
我想你忘了在 do while 循環中設置 name 變量。 嘗試這個:
import javax.swing.JOptionPane;
public class New {
public static void main (String[] args) {
String name = JOptionPane.showInputDialog("Enter your name... ");
while(name.equals("")){
name=JOptionPane.showInputDialog( "YOUR NAME...");
}
JOptionPane.showMessageDialog(null, "Hello and welcome!, "+name);
int age = Integer.parseInt(JOptionPane.showInputDialog("Enter your age... "));
if(age>=60) { JOptionPane.showMessageDialog(null, "Ok Boomer!");
System.exit(0);}
else if(age>=18) { JOptionPane.showMessageDialog(null, "You are an adult, Welcome!");
}
else { JOptionPane.showMessageDialog(null, "You are a kid!");
System.exit(0);}
String day = JOptionPane.showInputDialog("What's the day? ");
if(day.equals("Monday")) { JOptionPane.showMessageDialog(null, "Welcome to Java club!");
}
else {JOptionPane.showMessageDialog(null, "Try again later!");
}
}
}
您不會在循環中更新name
。
代替:
String name = JOptionPane.showInputDialog("Enter your name... ");
do{JOptionPane.showInputDialog( "YOUR NAME...");}
while(name.equals(""));
做:
String name;
do{
name = JOptionPane.showInputDialog("Enter your name... ");
while(name.equals(""));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.