我正在使用foreach循环迭代一个空数组,并用对象填充它."Case"是一个具有多种方法和属性的类.
我的代码看起来像这样:
public class Test {
private Case [] list = new Case[5];
public Case [] test(){
for(Case myCase : list){
myCase = new Case();
}
return list; //This list contains 5 nulls, but should contain five "Case" objects.
}
public static void main(String[] args){
Test myTest = new Test();
myTest.test();
}}
Run Code Online (Sandbox Code Playgroud)
当我希望它包含5个实例化的"Case"对象时,从我的方法返回的列表包含5个空值.我怀疑这可能是某种可见性问题,但我无法弄清楚.
char suit = 'S';
int n = 2;
for (int k= 0; k<4; k++){
for (int i = 0; i < n; i++){
switch (k) {
case 0: suit = 'S';
case 1: suit = 'H';
case 2: suit = 'D';
case 3: suit = 'C';
}
Run Code Online (Sandbox Code Playgroud)
这是作业的代码摘录.
在switch语句之后,Suit被设置为'C',并且根据调试器,它在整个双循环中都不会改变.我对switch语句有什么误解?
我有这个方法:
public String scanInput()
{
String input = "";
Scanner skanner = new Scanner(System.in);
while(skanner.hasNextLine()){
input = skanner.nextLine();
}
skanner.close();
return input;
}
Run Code Online (Sandbox Code Playgroud)
第一次运行此方法时,程序停止,并且在进行操作之前,系统会提示我在控制台中输入一个输入.但是,第二次运行该方法时,它会在没有暂停的情况下闪烁,并且我的程序陷入无限循环.
此方法中的哪一行使程序暂停,为什么它只在第一次暂停?
这是我的方法:
public boolean checkIfFriend(Coin coin){
ArrayList <int []> testCoordinates = new ArrayList <int[]>();
testCoordinates = this.coordinates; //I copy my ArrayList <Coin> "coordinates" into another ArrayList, "testCoordinates".
testCoordinates.retainAll(coin.getCoordinates()); //I remove all elements from "testCoordinates" that do not exist in the ArrayList supplied as argument.
if (testCoordinates.size() > 1){ //On this line, "this.coordinates" has been emptied for all elements. Why?
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
在我调用"retainAll"方法之后,"this.coordinates"中有0个元素,而之前有29个元素.
我怀疑我可能误解了有关ArrayList声明或retainAll方法的内容.在我称之为"retainAll"方法之后,我不明白为什么"this.coordinates"被清空了.
谢谢大家的帮助!
我是大学新手Java程序员.我今天发现了一些关于Java语法如何工作的概念.
public class testClass {
ArrayList <String> persons = new ArrayList <String> ();
public void run(){
Stream <String> personstream = persons.stream();
}}
Run Code Online (Sandbox Code Playgroud)
stream()在ArrayList类中找不到该方法,但它可能看起来好像在那里.当我将鼠标移到stream()Eclipse中的-method上时,它表示它是Collections的一部分,但我stream()在其在线文档中找不到任何方法.
stream()如果它不是我从中调用它的类的一部分,为什么调用该方法呢?
我有两节课.超类:
public abstract class Question(){
public Question(String question, String answer, String... alts){...
}
Run Code Online (Sandbox Code Playgroud)
而子类:
public class StringOptionsQuestion extends Question {
public StringOptionsQuestion(String question, String answer, String... alts){
if (alts.length == 0){throw new IllegalArgumentException();} //The compiler doesn't like this line.
super(question, answer, alts);
}}
Run Code Online (Sandbox Code Playgroud)
我希望我的子类,在它传递给超类的构造函数之前StringOptionsQuestion验证其长度alts.但是,我不能这样做.我得到错误"构造函数调用必须是构造函数中的第一个语句".为什么会出现此错误?我怎么能绕过它呢?
java ×6
abstract ×1
arraylist ×1
arrays ×1
collections ×1
console ×1
constructor ×1
eclipse ×1
foreach ×1
java-stream ×1
loops ×1
null ×1
object ×1
superclass ×1
syntax ×1
validation ×1