A. java隨機生成一個5行六列的二維數組,怎麼行列轉換
<pre t="code" l="java">思路:
1、首先聲明一個6行5列的數組
2、先循環行,再循環列,再賦值為隨機數(使用 Random 類)
3、再遍歷
代碼如下:
public static void main(String[] args) {
//聲明一個6行5列的數組
int[][] array=new int[6][5];
for(int i=0,j=array.length;i<j;i++){
for(int h=0,k=array[i].length;h<k;h++){
array[i][h]=new Random().nextInt(100); //賦值:100以內的隨機數
}
}
//遍歷
for(int i=0,j=array.length;i<j;i++){
System.out.println();
for(int h=0,k=array[i].length;h<k;h++){
System.out.print(array[i][h]+"\t");
}
}
}
B. Java將二維數組的行列元素進行轉換
假設,原數組為a[],再聲明一個數組b[]。m,n分別為原數組的行和列。
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
b[j][i] = a[i][j];
}
}
C. java程序設計 為每一名雇員計算一周的工作時間 數組存儲7名員工的工作時間,以降序顯示每個雇員的總時間
public class TestEmploee {
private static int[][] emploees ;
private static int[][] results = new int[7][2];
private static int emploeeIndex = 0;
private static int totalWorkTimeIndex = 1;
public static void main(String[] args){
init();
sumWorkTime();
sortByWorkTime();
printResult();
}
private static void printResult() {
for(int row = 0 ; row < results.length; row++ ){
System.out.println("emploee " + results[row][emploeeIndex] + " : " + " work time is : " + results[row][totalWorkTimeIndex] );
}
}
//排序
private static void sortByWorkTime() {
//冒泡法排序
for(int row = 0 , flag = 0 ; row < results.length ; row ++, flag ++ ){
for( int index = results.length -1 ; index >flag ; index -- ){
if(results[index][totalWorkTimeIndex] > results[index-1][totalWorkTimeIndex]){
int[] temp = results[index-1] ;
results[index-1] = results[index];
results[index] = temp;
}
}
}
}
//計算工作時間
private static void sumWorkTime() {
for(int row = 0 ; row < emploees.length ; row++ ){
for(int col = 0 ; col < emploees[row].length ; col++ ){
results[row][totalWorkTimeIndex]+=emploees[row][col];
}
results[row][emploeeIndex] = row;
}
}
//初始化emploee數組
private static void init() {
emploees = new int [][]{ {4,3,4,5,4},{9,3,5,3,7},{8,4,7,2,4},{5,1,3,7,7},{4,3,5,7,2},{2,1,5,3,8},{8,6,4,3,2} };
}
}
D. java 數組行列轉換
你這個的程序,只能成功運行 n*n的情況,也就是行數和列數相等的二維數組才能成功。
如果 n*m 也就是行數和列數不相同的情況就可能出錯。
因為 n*m 是沒有對角線的,也就是 i = j不一定出現在對角線上,所以出現了你上面的問題。
E. 用java怎樣將一個文件中特定行列的數據讀取出來
你可以這樣組織數據,在列名的行前面加個標志符,用於表明是列名:
#Number Name A B Value;
當讀到某行是以#開始的,表明這個不是數據,而是列名,然後把讀取的列存放到一個數組中,你可以在列名之間使用分隔符,比如:
# Number : Name : A : B : Value;
通過讀取指定的列名,你可以得到,列名在數組中對應的索引值。
對於存放數據的列就不加#,或者換成其他的標識符,同樣把讀取的數據行拆分存放到數組中,然後這樣就很方便的找到列名所對應的列的數據了。
如果是讀取行,那也很方便。
建議別使用,String col [] = row.split(":");來拆分數組,最好使用StringBuffer,或char數據來進行拆分操作。
F. Java語言設計,將一個二維數組的行和列元素互換,存到另一個二維數組中
import java.util.Arrays;
public class A{
public static void main(String[] args){
int[][] array1 = new int[][]{{1,2,3},{4,5,6},{7,8,9}};
int row = array1.length;
int column = array1[0].length;
int[][] array2 = new int[row][column];
for(int i=0; i<row; i++) {
for(int j=0;j<column;j++){
array2[i][j] = array1[j][i];
}
}
for(int i=0;i<row;i++){
System.out.println(Arrays.toString(array2[i]));
}
}
}