[英]Java Array Help Needed
I am building a Java Array where the odd columns will output the #1 and the even columns will output the #0. 我正在构建一个Java数组,其中奇数列将输出#1,偶数列将输出#0。 Here is what i have so far.
这是我到目前为止所拥有的。 I'm certain my mistake is trivial but if you could help it would be greatly appreciated!
我敢肯定我的错误是微不足道的,但是如果您能提供帮助,将不胜感激!
import java.util.Scanner;
public class TestArray2 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int [][] a = new int[5][5];
for(int i=0; i<a.length;i++){
for(int j=0;j<a[0].length;j++){
int x = j;
if(x%2 == 0){
a[i][j] = 0;
}
else {
a[i][j] = 1;
}
}
input.close();
}
}
public class Array2 {
public static void printArray(int[][]a){
for(int i=0;i<a.length;i++){
for(int j=0; j<a[0].length;j++){
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}
Array2.printArray(a);
}
}
Actually you have two different problems. 实际上,您有两个不同的问题。 The first one is that you are using a matrix not an array.
第一个是您使用的是矩阵而不是数组。 The second one is that you are trying to call the method on the second class when it does not have the
a
variable defined for that. 第二个是,你试图调用在第二类中的方法时,它不具备
a
为定义的变量。
Try the following: 请尝试以下操作:
import java.util.Scanner;
public class TestArray2 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int [] a = new int[input];
for(int i=0; i<a.length;i++){
if(i%2 == 0){
a[i] = 0;
} else {
a[i] = 1;
}
}
input.close();
printArray(a);
}
public static void printArray(int[]a){
for(int i=0;i<a.length;i++){
System.out.print(a[i]+" ");
}
System.out.println();
}
}
This should work, I skipped the second class 这应该工作,我跳过了第二节课
public class TestArray2 {
public static void main(String[] args){
int [][] a = new int[5][5];
for(int i=0; i<a.length;i++){
for(int j=0;j<a[i].length;j++){
int x = j;
if(x%2 == 0){
a[i][j] = 0;
}
else {
a[i][j] = 1;
}
}
}
printArray(a);
}
public static void printArray(int[][] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.