【问题标题】:My array is full of null我的数组充满了 null
【发布时间】:2017-12-10 18:10:18
【问题描述】:
package assign;

import java.util.Scanner;

public class tests {
public static void main(String[] args) {
Scanner s = new Scanner (System.in);
System.out.println("How many sous chef do we have?");
int two = s.nextInt();
if(two <= 0) { 
    do { 
    System.out.println("Please enter a valid number:");
    two = s.nextInt();
    }while (two <= 0); 
    }
String [] souschef = new String[two];
for (int m = 0; m < souschef.length; m++) { 
    System.out.println("Enter the name of sous chef"+ m + ":");
    String f = s.next();
    f = souschef [m];
}
for (int i = 0; i < souschef.length; i++) {
    System.out.println(souschef[i]);
}
}
}

不管我输入多少名字,输出都是空的。 for 循环没有填充数组吗?例如,我输入 3 个名字:John、Jack 和 Bob。不应该

for (int i = 0; i < souschef.length; i++) {
        System.out.print(souschef[i]);
    } 

循环给我

约翰·杰克·鲍勃

但是输出是

null null null

谢谢!!

【问题讨论】:

标签: java arrays loops for-loop


【解决方案1】:

改变

f = souschef[m];

souschef[m] = f;

您想用从输入 (f) 中读取的内容填充 souchef 数组,而不是相反。

【讨论】:

  • 非常感谢。我第一次写的时候就像你说的那样。好像我无缘无故改了,
【解决方案2】:

只需将循环更改为:

for (int m = 0; m < souschef.length; m++) { 
    System.out.println("Enter the name of sous chef"+ m + ":");
    String f = s.next();
    souschef [m]=f; //Assign f to String array
}

在您的程序中,您在变量 f 中从用户那里获取输入,但使用 f=souschef [m]; 将其分配给 null

【讨论】:

  • 非常感谢。我第一次写的时候就像你说的那样。好像我无缘无故改了。
猜你喜欢
  • 1970-01-01
  • 2012-09-02
  • 2017-07-24
  • 1970-01-01
  • 2018-06-14
  • 2020-02-13
  • 1970-01-01
  • 1970-01-01
  • 2020-01-19
相关资源
最近更新 更多