[英]How do I make a list of multiple inputs by the user by using JOptionPane and arrays?
我必須更正我所有的 IT 級作業,但我在其中一項作業上掙扎。 給你一個簡短的細分; 我基本上必須使用JOptionPane.showInputDialog
來獲取他們最喜歡的 4 位音樂藝術家的用戶輸入。 此外,我必須將這些輸入保存在一個名為singers[]
的數組中; 我必須利用 for 循環詢問使用JOptionPane.showInputDialog
的 4 位藝術家的姓名,然后將該輸入保存在提到的數組中,並輸出 4 位藝術家,但是,如果藝術家名稱之一是“heino”,則程序必須通過System.exit(0)
立即關閉。
我已經完成了大部分工作,但是我很難獲得 4 個藝術家姓名的輸入和輸出。
import javax.swing.*;
public class Main {
public static void main(String[] args) {
String[] singer = new String[4];
for (int i = 0; i < singer.length; i++) {
singer[i] = JOptionPane.showInputDialog("How is your favourite artist called? :");
if(singer[i].equals("Heino")){
System.exit(0);
}
else{
singer[i] = JOptionPane.showInputDialog("Do you have any other favourite artists? : ");
}
for (String bestesinger : singer){
JOptionPane.showMessageDialog(null, "The name of your favourite artists are: " + singer[0] + singer[1] + singer[2] + singer[3]);
}
}
}
}
我已經改變了你的程序,如下所示。 現在它起作用了。 關鍵點是:
您嵌套了for
循環,但您應該使用 2 個單獨的for
循環。
在第一個for
循環中不需要else
塊。
第二個showMessageDialog()
調用移到第二個for
循環之外。 在第二個for
循環中,歌手姓名被收集到output
變量。
import javax.swing.*;
public class Singers {
public static void main(String[] args) {
String[] singer = new String[4];
for (int i = 0; i < singer.length; i++) {
singer[i] = JOptionPane.showInputDialog("How is your favourite artist called? :");
if (singer[i].equals("Heino")) {
System.exit(0);
}
}
String output = "";
for (String bestesinger : singer){
output = output + bestesinger + " ";
}
JOptionPane.showMessageDialog(null, "The name of your favourite artists are: " + output);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.