Java 变量赋值与循环
不久前,我正在编写一个程序,该程序将值散列到一个哈希表中(我不记得细节,细节本身与手头的问题无关)。无论如何,我有以下代码作为“recordInput”方法的一部分:Java 变量赋值与循环,java,loops,variable-assignment,Java,Loops,Variable Assignment,不久前,我正在编写一个程序,该程序将值散列到一个哈希表中(我不记得细节,细节本身与手头的问题无关)。无论如何,我有以下代码作为“recordInput”方法的一部分: tempElement=新的hashElement(someInt); while(in.hasNext()==true) { int firstVal=in.nextInt(); 如果(firstVal==-911) { 打破 } tempElement.setKeyValue(firstVal,0); 对于(int i=1;i
tempElement=新的hashElement(someInt);
while(in.hasNext()==true)
{
int firstVal=in.nextInt();
如果(firstVal==-911)
{
打破
}
tempElement.setKeyValue(firstVal,0);
对于(int i=1;i为什么要将变量声明保留在while循环之外?无论如何,只要每次都将其分配给新的hashElement,就可以:
hashElement tempElement;
while (/*...*/) {
tempElement = new hashElement();
//...
当然不是“更好”尽管如此。一般来说,变量的作用域尽可能窄。这不是关于变量的声明,而是关于您创建的对象。java中的数组只包含对对象的引用,因此如果您确实希望在数组中有不同的对象,则需要在循环中的某个位置使用new
创建它们
tempElement = new WhateverClass();
您最好了解Java编码约定:。类名应以大写字母开头。或者干脆elementArray[placeValue]=new…
并完全跳过临时变量。在调用setter时不会这样做。调用像elementArray[placeValue].setwhater(whater)这样的setter是丑陋的,应该受到严厉的惩罚。我认为临时变量是必要的,因为OP正在对它进行操作,这些操作需要在构造之后完成。@Andrew,unbeli:必要的,不;丑陋…视情况而定。我同意这可能是不好的样式。但是数组通常是丑陋的,我看不出为什么它不应该是一个列表,而应该是一个列表用add
@Mark标记分配任务,数组非常漂亮、快速和高效。而且,更改为列表并不能解决问题
tempElement = new WhateverClass();
Element tempElement;
while(condition){
tempElement = new HashElement();
//do more stuff
elementArray[index] = tempElement;
}