[英]Printing int[] array from a display method
I am trying to print an int[] array from a seperate method in the same class. 我正在尝试从同一类的单独方法中打印int []数组。
public class LargeInteger {
public LargeInteger(String s) {
int[] intArray = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
intArray[i] = Character.digit(s.charAt(i), 10);
}
}
public Object display() {
for (int i = 0; i < intArray.length; i++) {
System.out.print(intArray[i]);
}
}
}
My intArray is clearly being hidden from the display method, but I am not sure what to do 我的intArray很明显从显示方法中隐藏了,但是我不确定该怎么办
I will give you the answer but you should first invest some time to look up your problem on google. 我会给你答案,但是您应该首先花一些时间在Google上查找问题。 Google knows "almost" everything...
Google几乎“了解”一切...
public class LargeInteger {
private int[] intArray;
public LargeInteger(String s) {
intArray = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
intArray[i] = Character.digit(s.charAt(i), 10);
}
}
public void display() {
for (int i = 0; i < intArray.length; i++) {
System.out.print(intArray[i]);
}
}
}
And your display method should be void if it isn't returning anything.. 如果您的显示方法未返回任何内容,则它应该为空。
intArray
is a local variable in the constructor. intArray
是构造函数中的局部变量 。
It doesn't exist anywhere else. 它在其他任何地方都不存在。
You need to make a private field instead. 您需要改成私有字段。
You need to declare the array outside of LargeInteger
method, eg 您需要在
LargeInteger
方法外部声明数组,例如
private int[] intArray;
public LargeInteger(String s){
this.intArray = new int[s.length()];
}
public class LargeInteger {
private int[] intArray;
public LargeInteger(String s) {
this.intArray = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
intArray[i] = Character.digit(s.charAt(i), 10);
}
}
public Object display() {
for (int i = 0; i < this.intArray.length; i++) {
System.out.print(intArray[i]);
}
}
}
Make intArray
a member of the LargeInteger
class instead of a local to the constructor: 使
intArray
成为LargeInteger
类的成员,而不是构造函数的本地成员:
public class LargeInteger {
private int[] intArray;
public LargeInteger(String s) {
intArray = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
intArray[i] = Character.digit(s.charAt(i), 10);
}
}
public Object display() {
for (int i = 0; i < intArray.length; i++) {
System.out.print(intArray[i]);
}
}
}
Just declare int[] intArray
out of the constructor. 只需从构造函数中声明
int[] intArray
。
It should be 它应该是
public class LargeInteger {
private int[] intArray;
public LargeInteger(String s) {
intArray = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
intArray[i] = Character.digit(s.charAt(i), 10);
}
}
public Object display() {
for (int i = 0; i < intArray.length; i++) {
System.out.print(intArray[i]);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.