【问题标题】:Adding constraints to integers向整数添加约束
【发布时间】:2014-02-21 03:10:52
【问题描述】:

我试图将输入数字限制为大于 0 和整数。

代码在这里:

import java.util.Scanner;

public class PROB4_CHAL1   // Sum of Numbers
{
public static void main(String[] args)
{

 int sum = 0;
 int count = 1;
 int number = 1;

 Scanner input = new Scanner(System.in);

 System.out.println("Enter an integer " + 
              "greater than 0.");
 number = input.nextInt();

 while (number >= count) 
 {
  sum += count;
  count ++;
 }

 System.out.println("Sum equals " + sum);


}
}

Java 新手,所以任何事情都会有所帮助!

【问题讨论】:

  • 调用nextInt()后检查号码是否有效,如果不是,再次询问。
  • 如果用户输入一个负整数,你希望发生什么?程序是否应该返回并要求他们重新输入?如果是这样,您将需要某种循环,例如 do-while。
  • 我的回答解决了你的问题吗?
  • 是的,它运行良好。谢谢
  • 没问题 - 很乐意提供帮助。

标签: java loops java.util.scanner


【解决方案1】:

您可以在 while 循环中获取输入,如下所示:

int number = 0; // start at 0 so the while loop is true for the first time

while (number < 1) {

    System.out.println("Enter an integer " + 
                       "greater than 0.");
    number = input.nextInt();
}

这样它会一直要求他们输入一个数字,直到他们输入的数字大于0。

【讨论】:

  • 我正在尝试将 1,2,3,4,5... 添加到输入数字中。该代码将带来总和 0
  • @nerd4life:我的代码与您收集总和的方法无关。不要替换您当前的 while 循环,只需将您的 number = input.nextInt(); 替换为我的循环即可。
猜你喜欢
  • 2016-01-17
  • 1970-01-01
  • 1970-01-01
  • 2013-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多