Java 如何在数组中搜索和计算值?
我有一个名为theRooms[]的数组,它包含10个房间。有些是单人床,有单人床;有些是双人床,有双人床。 我需要知道我在休息室有多少间单人房Java 如何在数组中搜索和计算值?,java,arrays,Java,Arrays,我有一个名为theRooms[]的数组,它包含10个房间。有些是单人床,有单人床;有些是双人床,有双人床。 我需要知道我在休息室有多少间单人房 public int getSingleCount() { int singleCount for(int i = 0; i < theRooms.length; i++) { if (theRooms[i] == 1) singleCount++
public int getSingleCount()
{
int singleCount
for(int i = 0; i < theRooms.length; i++)
{
if (theRooms[i] == 1)
singleCount++
}
return singleCount;
}
public int getSingleCount()
{
整数单计数
for(int i=0;i
您只需要遍历数组
int count = 0;
for (Room room : theRooms)
if (room.isSingleCount())
count++;
假设TheRoom包含一个房间对象数组,该数组具有一个名为bedCount的方法,该方法返回一个与其可以容纳的人数相对应的数字
int count = 0;
for (int i = 0; i < theRooms.length; i++) {
count += theRooms[i].bedCount;
}
int count=0;
for(int i=0;i
假设对象房间中有方法计数,则可以执行以下操作
int count = 0;
for (rooms room : theRooms){
if (room.count() == 1)
count++;
}
System.out.println(count);
需要更多括号:-P@Duncan虽然我更喜欢大括号,但没有大括号也行,因为
for
和if
@GriffeyDog中只有一条语句,我的评论更像是一个笑话:-)我投了反对票,因为没有证据表明你在提问之前试过任何东西。你的问题也很不清楚。一个代码示例可能有助于解决这两个问题。这是我尝试过的,但它不起作用:public int getSingleCount(){int singleCount for(int i=0;i