【问题标题】:How can I input only integer and this integer will be only ending with zero? [closed]我怎样才能只输入整数,而这个整数只会以零结尾? [关闭]
【发布时间】:2015-01-08 20:10:02
【问题描述】:

我正在尝试验证输入值以仅传递可被 10 整除的整数。下面的代码失败了。

 public static void main(String args[]) {
    Scanner scan =new Scanner(System.in);
    ArrayList<Integer> liste = new ArrayList<Integer>(); // I have filled my array with integers
   int x=scan.nextInt();
int y=x%10;
do{
if(y==0){
liste.add(x);}
else if(y!=0){
System.out.println("It is not valid"); continue;
} 
else 
{System.out.println("Enter only integer"); continue;
}

}while(scan.hasNextInt()); }

        System.out.println(liste);
        System.out.println("Your largest value of your arraylist is: "+max(liste));

【问题讨论】:

  • enter code herepublic static void main(String args[]){ 是无效的方法签名;)
  • 为什么不将scan.nextInt() 的结果存储在一个变量中,而不是调用它两次?

标签: java loops if-statement try-catch


【解决方案1】:

您拨打了两次scan.nextInt()。每次调用它时,它都会从输入中读取另一个 int。因此,如果您的输入类似于

10
5
13

那么 10 将通过 scan.nextInt()%10==0 检查,然后 5 将被添加到列表中。先把scan.nextInt()的结果存到一个变量里,这样值就不会变了。

代替

if(scan.nextInt()%10==0){
liste.add(scan.nextInt());}

int num = scan.nextInt();
if(num%10 == 0){
    liste.add(num);
}

【讨论】:

  • 是的,你是对的,它通过了我的第一个值
  • 用代码编辑答案。
猜你喜欢
  • 2021-07-30
  • 2023-02-04
  • 2017-04-27
  • 2021-10-15
  • 2022-01-13
  • 1970-01-01
  • 1970-01-01
  • 2018-02-25
  • 2014-01-07
相关资源
最近更新 更多