程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了提示用户只输入正数大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决提示用户只输入正数?

开发过程中遇到提示用户只输入正数的问题如何解决?下面主要结合日常开发的经验,给出你关于提示用户只输入正数的解决方法建议,希望对你解决提示用户只输入正数有所启发或帮助;

这个基本的 JAVA 程序应该提示用户,并打印“不允许使用负数”,直到用户输入正数。这必须通过使用 while 循环来处理。它是如何工作的 ?这是我在堆栈溢出中的第一篇文章。

  public static voID main(String[] args) 
  {
        System.out.print("Welcome to Box Price Calculator");
        System.out.print(System.lineseparator());
        System.out.print(System.lineseparator());
        
        int BoxVol = 20 ;
        double price_each_Box = 2.99;
        System.out.print("Bottles :");
        Scanner input = new Scanner(system.in);
        int numberOfbottles = 1;
        numberOfbottles = input.nextInt();
        
        boolean valID = false;
        
      
        while (input.nextInt() < 0){
            System.out.println("Negative numbers are not allowed");
            numberOfbottles = input.nextInt();
        }       
        
        int Box = (numberOfbottles / BoxVol);
        System.out.println("Box Needed : " + Box);
        double totPrice = (Box * price_each_Box);
        
        System.out.println("Total Cost : $" + totPrice);
        int leftOver = (numberOfbottles -(Box * BoxVol));
        System.out.println("UnBoxed :" + leftOver);
        
    }  
}

解决方法

这里的问题是,在 while 条件中,您正在阅读并再次与 input.nextInt() 进行比较,而不是与 numberOfbottles 进行比较。您应该做的是使用 do...while 并将其与您的变量 numberOfbottles 进行比较:

public static void main(String[] args) 
{
    System.out.print("Welcome to Box Price Calculator");
    System.out.print(System.lineSeparator());
    System.out.print(System.lineSeparator());
    
    int boxVol = 20 ;
    double price_each_box = 2.99;
    
    java.util.Scanner input = new java.util.Scanner(System.in);
  
    int numberOfbottles;
  
    do
    {
        
        System.out.println("Bottles (Negative numbers are not allowed):");
        numberOfbottles = input.nextInt();
    
    }
    while (numberOfbottles < 0);
    
    int box = (numberOfbottles / boxVol);
    System.out.println("Box Needed : " + box);
    double totPrice = (box * price_each_box);
    
    System.out.println("Total Cost : $" + totPrice);
    int leftOver = (numberOfbottles -(box * boxVol));
    System.out.println("Unboxed :" + leftOver);   
}

大佬总结

以上是大佬教程为你收集整理的提示用户只输入正数全部内容,希望文章能够帮你解决提示用户只输入正数所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: