java hasnext 怎么用,Java - 如何在使用hasNext()条件时突破?

本文介绍如何在Java程序中使用Scanner获取输入时避免无限循环,并提供两种方法:使用break语句根据条件结束循环,或创建一个辅助方法判断是否继续迭代。通过实例演示如何在获取数字输入时实现有效控制。
摘要由CSDN通过智能技术生成

I am writing a simple program to calculate the average of a set of numbers. You get the numbers using Scanner, so I am using while loop with .hasNext() as a condition. However the loop is infinite.

Is it possible to break out of it without writing some certain word like "stop" in the input?

public class main {

public static void main(String[] args){

Scanner Input = new Scanner(System.in);

int count = 0;

int temp;

int sum = 0;

while(Input.hasNextInt()){

count++;

temp = Input.nextInt();

sum += temp;

System.out.println(temp);

System.out.println(count);

} // End of while

double average = sum / count;

System.out.println("The average is: " + average);

} // End of method main

}

解决方案

The break; statement can be sued to... well... break out of an iteration. And by iteration I mean you can get out of a for too, for example.

You have to define WHEN do you want to break out of the iteration and then do something like this:

while(Input.hasNextInt(Input)){

if(condition())

break;

count++;

temp = Input.nextInt();

sum += temp;

System.out.println(temp);

System.out.println(count);

}

Otherwise, you can make an auxiliary method that defines if the iteration should keep on going, like this one:

private boolean keepIterating(Scanner in) {

boolean someOtherCondition = //define your value here that must evaluate to false

//when you want to stop looping

return Input.hasNextInt() && someOtherCondition;

}

Method that you will have to invoke in your while:

while(keepIterating()){

count++;

temp = Input.nextInt();

sum += temp;

System.out.println(temp);

System.out.println(count);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值