简体   繁体   English

Java While循环以负数中断

[英]Java While Loop breaking with a negative

I am having a problem with this java project I am working on for tomorrow. 我明天要处理的这个Java项目有问题。 I am supposed to make a while loop that prompts the user for the prices of items and end the loop with any negative number, that negative number cannot be counted. 我应该做一个while循环,提示用户输入商品价格,并以任何负数结束循环,该负数无法计数。 Then I have to prompt the user for their membership discount level plat 15% off/gold 7%/silver 3%/non member 0% off using variables 3,2,1,0 respectively. 然后,我必须使用变量3、2、1,0提示用户分别提供15%的折扣/黄金7%/白银的3%/非会员0%的折扣。 For invalid input of status of membership, the user needs to enter again with a valid one using a do-while loop. 对于无效的成员身份输入,用户需要使用do-while循环以有效的身份再次输入。 Then I use the appropriate discount % off the sum of the items then tax it. 然后,我从项目总和中使用适当的折扣百分比,然后对它征税。 The last few steps are simple enough, but I am stuck at the loops. 最后几步很简单,但是我陷入了循环。

I did some searching and found this block of code on this site that does the job for the first while loop but does not end in the way I need it to. 我进行了一些搜索,并在此站点上找到了此代码块,该代码块可以在第一个while循环中完成工作,但并未以我需要的方式结束。 Using While Loop instead of a For Loop in Java to ask User Input 在Java中使用While循环而不是For循环来询问用户输入

I modified it to fit my needs but I still cannot find a way to make the throwable = to any negative number ie <0. 我对其进行了修改以满足自己的需求,但仍然找不到将throwable =设置为任何负数(即<0)的方法。 Is that even possible? 那有可能吗? I am pretty sure there is a way to do this much simpler without try/catch which I have not learned yet. 我非常确定,有一种方法可以更简单地完成我还没有学到的try / catch。 Here is my very slightly modified version 这是我的稍加修改的版本

Scanner askPrice = new Scanner(System.in);
BigDecimal totalPrice = new BigDecimal("0");
Scanner keyboard = new Scanner(System.in);
while (true) {
    System.out.println("Enter item price or negative number to quit:") ;
    try {
        double price = askPrice.nextDouble();
        totalPrice = totalPrice.add(new BigDecimal(String.valueOf(price)));
    }
    catch (Throwable t) {
        break;
    }
    System.out.println(totalPrice.toString());
}

I tried turning the try and catch statements into if / else and replacing the catch throwable with else(askPrice <0), but I was getting tons of errors. 我尝试将try和catch语句转换为if / else,并用else(askPrice <0)替换catch throwable,但是我遇到了很多错误。

I greatly appreciate any help that can be offered. 我非常感谢您可以提供的任何帮助。 Thanks. 谢谢。

This sounds like homework. 这听起来像作业。 I know a lot of teachers are against students using 'break' to exit a loop. 我知道很多老师反对使用“休息”退出循环的学生。 Here is how I would do it. 这就是我要怎么做。 A try-catch statement is unnecessary. 无需try-catch语句。

public static void main(String[]args) {

Scanner keyboard = new Scanner(System.in);
    double input = 0.0;
    double totalPrice = 0.0;

    do {
        totalPrice += input;
        input = keyboard.nextDouble();
    }

    while(input >= 0);
}

Using a while loop: 使用while循环:

public static void main(String[]args) {

Scanner keyboard = new Scanner(System.in);
    double totalPrice = 0.0;
    double input = keyboard.nextDouble();

    while(input >= 0) {
    totalPrice += input;
    input = keyboard.nextDouble();
    }
}

Here is a simple do while loop that you are looking for 这是您正在寻找的一个简单的do while循环

double price = 0;
do {
    try {
        price = askPrice.nextDouble();
        // if the price was  > 0 we need to add it to the total
        if(price > 0)
            totalPrice = totalPrice.add(new BigDecimal(String.valueOf(price)));  
    } catch(InputMismatchException e) {
        // exit our loop, if the user entered an invalid double. Maybe you want to display a message instead?
        price = -1; 
    }
} while(price >= 0);

The key is a do-while loop vs a while loop. 关键是do-while循环与while循环。 The do-while loop will always run one time prior to analysing the loop condition. 在分析循环条件之前,do-while循环将始终运行一次。 This allows you to accept the users input inside the loop and keep your code clean. 这使您可以接受循环内的用户输入并保持代码干净。 I belive it is good practice to avoid using the break statement when possible. 我相信,最好避免在可能的情况下使用break语句。 It will generally keep you from writing bad code (with the exception of switch statements of course). 通常,它将使您不必编写错误的代码(当然,switch语句除外)。

Edit: For the record I think the try catch statement is not only necessary but mandatory for any user input. 编辑:为了记录,我认为try catch语句不仅对于任何用户输入都是必需的,而且是必需的。 When a user enters an invalid number do you want a nasty error with a stack trace being thrown or your program to gracefully handle the bad input and notify the user. 当用户输入一个无效数字时,您是否想要一个令人讨厌的错误并抛出堆栈跟踪,或者您的程序要妥善处理错误的输入并通知用户。 Most important it gets new programmers thinking about error handling, a very important part of software development. 最重要的是,它使新程序员思考错误处理,这是软件开发中非常重要的一部分。

Try/catch is for handling exceptions and totally unnecessary here. Try / catch用于处理异常,这里完全不需要。

    Scanner askPrice = new Scanner(System.in);
    BigDecimal totalPrice = new BigDecimal("0");
    Scanner keyboard = new Scanner(System.in);

    while (true) {

        System.out.println("Enter item price or negative number to quit:") ;
        double price = askPrice.nextDouble(); 
        if (price<0)
            break;
        else {
            totalPrice = totalPrice.add(new BigDecimal(String.valueOf(price)));       
        }
        System.out.println(totalPrice.toString());
   } 

You don't you check for negative number. 您不检查负数。

And you need to move your last System.out outside the loop 而且您需要将最后一个System.out移出循环

    Scanner askPrice = new Scanner(System.in);
    BigDecimal totalPrice = new BigDecimal("0");

    while (true) {

        System.out.println("Enter item price or negative number to quit:");
        try {
            double price = askPrice.nextDouble();
            if (price < 0)
                break;

            totalPrice = totalPrice.add(new BigDecimal(String.valueOf(price)));
        } catch (Throwable t) {
            break;
        }
    }
    System.out.println(totalPrice.toString());

I'm not sure of understand, but if you want exit with a negative number as input, use this: 我不确定是否可以理解,但是如果要退出时输入负数,请使用以下命令:

    Scanner askPrice = new Scanner(System.in);
    BigDecimal totalPrice = new BigDecimal("0");
    Scanner keyboard = new Scanner(System.in);
    double price = 0.0d;
    try {
        while (0.0d <= price) {
         System.out.println("Enter item price or negative number to quit:") ;
         price = askPrice.nextDouble();        
         totalPrice = totalPrice.add(new BigDecimal(String.valueOf(price)));       
        }
     }catch (Throwable t) {           
        System.err.println(t.getMessage());         
     }
     System.out.println(totalPrice.toString());

Some points: 一些要点:

  • try/catch always out of a cycle, beacuase the code is more readable and faster 尝试/捕获始终不在一个周期内,因为代码更具可读性和速度
  • inside catch, you have to put a syserr, not sysout 内部捕获,您必须放置一个syserr而不是sysout
  • in the orginal code, the eternal lopp finish when the user put a dollar char, what throw an Exception in converting as number with instruction 在原始代码中,当用户放入美元字符时,永恒的结束完成,在指令转换为数字时抛出异常

    askPrice.nextDouble() askPrice.nextDouble()

In your case, the instructions 就您而言,说明

 double price = askPrice.nextDouble();        
 totalPrice = totalPrice.add(new BigDecimal(String.valueOf(price))); 

don't throw any exception with negative number. 不要抛出任何带有负数的异常。

Normally it is better to write your own code instead of copying code for simple examples. 通常,对于简单的示例,最好编写自己的代码,而不是复制代码。 That way you will learn a lot. 这样,您将学到很多东西。 In the code you have a missing closing brace for while loop, I hope there is a brace closing later. 在代码中,您缺少while循环的右括号,我希望稍后有一个右括号。

You can temporarily fix the code by throwing an exception after getting the price: 您可以通过在获得价格后引发异常来临时修复代码:

double price = askPrice.nextDouble();
if(price < 0) throw new ArithmeticException("Negative Price!");

I am not sure whether that is what you want. 我不确定这是否是您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM