2016-10-01 64 views
0

我試圖在for循環中編寫一個數組,看起來沒有任何意義。這一行中的「int」是什麼?

String[][] userName; 

userName = new String[3][4]; 

for(int x=1; x<= 4; x++) { 
    for(int y=-1; y <= 3; y++) { 
     System.out.println("Enter student name for row "+x+"column "+y+" ==>"); 
     userName[x-1][y-1] = (String) System.in.read(); 
    } 
} 

對於行:

userName[x-1][y-1] = (String) System.in.read() 

它給出了一個錯誤:

Incompatible types: int cannot be converted to String 

但是,在該行被列爲int?我所知道的唯一的是[x-1][y-1],但它們是在數組中找到位置的數字,而且我甚至刪除了它們,並且它仍然表示同樣的錯誤。

什麼是歸類爲int,我該如何解決這個錯誤?

+0

JavaScript不是Java。 – Li357

+0

哦...好的。不知道。抱歉。 – L7vanmatre

+0

我......呃,我不確定我在學習什麼。對不起。 – L7vanmatre

回答

1
1 for(int x=1; x<= 4; x++) 
2 { 
3 for(int y=-1; y <= 3; y++) 
4 { 
5 System.out.println("Enter student name for row "+x+"column "+y+" ==>"); 
6 userName[x-1][y-1] = (String) System.in.read(); 
7 } 
8 } 

由位允許分裂該環位批量數據。 在第6行,您正在通過System.in.read()行進行整數輸入,但您的數組基本上是String數據類型!所以,你把它轉換成String。但是,如果沒有Integer.toString(System.in.read()),則無法將int插入到字符串中。這是正常的方式!但是,最簡單的方法是

userName[x-1][y-1] = "" + System.in.read(); 

Java從右向左讀取一行。所以它需要一個輸入並將其追加到一個空字符串,然後將其放入userName數組中!

(感謝Pavneet Singh用於察覺我) (感謝Erwin Bolwidt糾正我。我沒有注意到這是字符串!)

或者,你可以使用Scanner class

爲此,您需要添加以下代碼。 你的班線之前,添加以下(公共課)

import java.util.Scanner; 

然後,當你類中開始公共靜態無效的主要(..),在第一行或函數之前任何方便的線,你會寫下面一行

Scanner sc = new Scanner(System.in); 

它初始化掃描儀。然後你可以使用掃描儀類!

userName[x-1][y-1] = sc.next(); 

看透掃描儀類,您將需要指定您將提供的數據類型!所以,如果你/用戶提供了String或者float或者boolean值,它會拋出一個錯誤,程序將會結束/崩潰!如果您試圖避免錯誤的數據類型,那麼相當有效。

最後,你可能有一個錯誤在第3行 您的循環聲明可以從Ÿ運行循環= -1但是,在Java中,數組索引從0開始所以,不存在指數y - 1 = - 1 - 1 = -2,它會拋出一個錯誤!爲了避免這一切,你只需要從y = 1申明你的循環。

for(int y = 1, y <= 3; y++) 

快樂的編程!乾杯!

+0

不錯的個人資料圖片。 +海賊王 – Zarwan

+0

@Zar,謝謝。^_^ –

+1

你不必轉換它'(int)System.in.read()'它已經是一個int –

2

因爲System.in.read()將讀取的字節將在0-255範圍返回值,所以你不需要它,你想讀的字符串,然後要麼使用ScannerStreams

Scanner scan =new Scanner(System.in); 

for(int x=1; x<= 4; x++) { 
    for(int y=-1; y <= 3; y++) { 
     System.out.println("Enter student name for row "+x+"column "+y+" ==>"); 
     userName[x-1][y-1] = scan.read(); 
    } 
} 

掃描儀(進口爪哇。 util.Scanner)

Scanner scan =new Scanner(System.in); 

scan.read(); // read the next word 
scan.readLine(); // read the whole line 

InputStreamReader r=new InputStreamReader(System.in); 
BufferedReader br=new BufferedReader(r); 
String str=br.readLine(); 

掃描儀是容易的,帶有許多功能link to doc,流可以被用來讀取有時不能由掃描器讀取

0

在使用System.in.read()之前,您應該對此進行一些研究。 System.in.read()方法從輸入流中讀取數據字節並將數據作爲整數返回。所以你只能使用整數或字符變量來存儲數據。字符串變量不能存儲方法System.in.read()返回的數據。這就是爲什麼你得到的異常

incompatible types: int cannot be converted to String

而且還使用try catch塊當您使用System.in.read()方法的原因。