[英]Why it tells me to convert time to int? the format of time is XX:XX, what this type of this variable should be?
import javax.swing.JOptionPane;
public class filmboxoffice {
public static void main (String[] args)
{
String [] filmname = new String [4];
String [] filmtime = new String [4];
String name;
String time;
int result;
for(int i=1; i<5; i++)
{
name = JOptionPane.showInputDialog("What is the film on Screen "+i+" today?");
result = i;
time = JOptionPane.showInputDialog("What time does it start?");
}
JOptionPane.showMessageDialog(null,"Screen "+ result +": "+" "+filmtime [time]);
}
}
錯誤堆棧:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from String to int
at filmboxoffice.main(filmboxoffice.java:22)
問題是這個表達式:
filmtime [time]
filmtime
是一個數組 -數組始終通過索引(它是一個int
。 time
是String
類型的變量,因此不能將其用作數組索引。
也許您想要Map<String, String>
或更好的方法是使用Joda Time , Map<LocalTime, Film>
?
實際上,再次閱讀此內容后,看起來實際上應該具有以下內容:
for (int i = 0; i < 4; i++) {
JOptionPane.showMessageDialog(null,"Screen "+ i +": "+" "+filmtime[i]);
}
……當然會。 (在提示用戶輸入time
之后,您當前正在忽略它的time
。)
請注意,Java中的數組從0開始,因此new String[4]
有效索引為0、1、2和3,因此您當前的循環將引發異常-尚不清楚result
是什么,假設在當前循環的末尾它將始終為4。
因為可變時間是String類型的。 您需要將其解析為Integer才能訪問數組的該元素,可能類似於:
filmtime[Integer.parseInt(time)]
並且您的錯誤將得到糾正。
您有String [] filmtime = new String [4];
因此,在您的代碼中,filmtime [time]:time應該是in類型,即Array中的索引。
但是,您的時間變量是String類型。
嘗試這個:
JOptionPane.showMessageDialog(null,"Screen "+ result +": "+" "+filmtime [result]);
您已將time
定義為String
並嘗試在數組元素的index
使用。 數組索引是從0
開始的整數值,用於引用數組中的第一個元素。
請在filmtime [time]
語句中使用正確的索引元素。
我懷疑您想將result
用作filmtime [result]
。
for(int i=1; i<5; i++)
{
name = JOptionPane.showInputDialog("What is the film on Screen "+i+" today?");
result = i;
filmname[i-1] = new String(name);
time = JOptionPane.showInputDialog("What time does it start?");
filmtime[i-1] = new String(time);
}
從您的問題來看,我認為這就是您的意思。
這應該是:
for(int i = 0; i < 4; i++){
JOptionPane.showMessageDialog(null,"Screen "+ (i + 1) +": "+ filmname[i]+ " "+filmtime[i];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.