简体   繁体   English

do-while 循环中的 Try-catch 块未正确循环并保留最后的输入结果

[英]Try-catch blocks within do-while loops are not looping properly and carrying over the last input result

Scanner scan = new Scanner(System.in);   
        int year = -1;
        int yearDuplicate = -1;
        System.out.println("This calculator tells you whether a year that you "
                + "enter is a leap year.\nPlease enter a year:");
        
        do{
            try{
                year = scan.nextInt();
            }catch(Exception e){
                System.out.println("ERROR. Please enter a numerical digit "
                        + "without decimals:");
                scan.next();
            }    
            
        }while(year % 1 != 0);
            
        
        do{
            if(yearDuplicate % 4 == 0){ 
                if(yearDuplicate % 100 == 0){
                    if(yearDuplicate % 400 == 0){
                        System.out.println(yearDuplicate + " is a leap year.");
                    }else{
                        System.out.println(yearDuplicate + " is not a leap year.");
                    }
                }else{
                    System.out.println(yearDuplicate + " is a leap year.");
                }
            }else{
                System.out.println(yearDuplicate + " is not a leap year.");
            }
            
            System.out.println("Enter another year or enter '-1' to quit:");
            try{
                yearDuplicate = scan.nextInt();
            }catch(Exception e){
                System.out.println("ERROR. Please enter a numerical digit "
                        + "without decimals:");
                scan.next();
            }
            
        }while(yearDuplicate != -1);

I am trying to make a leap year calculator that also tells you whether you accidentally typed in a string or double instead of an integer.我正在尝试制作一个闰年计算器,它还会告诉您是否不小心输入了字符串或双精度而不是整数。 What I would want this program to do is run the "ERROR. Please enter a numerical digit without decimals:" over and over again until the user enters in an integer.我希望这个程序做的是一遍又一遍地运行“错误。请输入一个没有小数的数字:”,直到用户输入一个整数。 However, currently, for the first try catch block, if I input two wrong input types, it gives me this error message:但是,目前,对于第一个 try catch 块,如果我输入了两个错误的输入类型,则会显示以下错误消息:

test
ERROR. Please enter a numerical digit without decimals:
-1 is not a leap year.
Enter another year or enter '-1' to quit:
test
ERROR. Please enter a numerical digit without decimals:
BUILD SUCCESSFUL

The second one is at least slightly better, it keeps repeating the result of the last integer I put in (year "is a/not a leap year") but at least it repeats forever unlike the first one.第二个至少稍微好一点,它不断重复我输入的最后一个整数的结果(年份“是/不是闰年”),但至少它与第一个不同,它永远重复。

test
ERROR. Please enter a numerical digit without decimals:
10 is not a leap year.
Enter another year or enter '-1' to quit:
test
ERROR. Please enter a numerical digit without decimals:
10 is not a leap year.
Enter another year or enter '-1' to quit:

All I want in for error message to get replayed until you input in the correct number.所有我想要的错误消息都会重播,直到您输入正确的数字。 How do I get rid of the previous input result and how do I fix the fact that the first try catch block only runs twice?如何摆脱先前的输入结果,以及如何解决第一个 try catch 块仅运行两次的事实?

I looked online but it seems if I change one small part of this program, something else breaks.我在网上看了一下,但似乎如果我改变这个程序的一小部分,其他东西就会中断。 It does exactly what I want it to if I make the condition of the first while loop to be while(year % 1 == 0);如果我将第一个 while 循环的条件设为 while(year % 1 == 0); but then that means that if it is an integer, the while loop repeats which is the exact opposite of what I want it to do.但这意味着如果它是一个整数,while 循环会重复,这与我想要它做的完全相反。 If I mess with the scan.next();, it'll give me an infinite error loop.如果我弄乱了 scan.next();,它会给我一个无限的错误循环。

Btw, there are two try catch blocks since there are two opportunities for the user to enter in a year and two places where I might have to correct them.顺便说一句,有两个 try catch 块,因为用户有两次机会在一年内进入,我可能需要在两个地方更正它们。 If I put them both in the same while loop, it'll work the first time but then after that, every time I need to enter in two numbers (one for the first try catch which gets overwritten by the second try catch).如果我将它们都放在同一个 while 循环中,它会在第一次工作,但之后,每次我需要输入两个数字时(第一个 try catch 被第二个 try catch 覆盖)。

Edit: I changed the starting values of year and yearDuplicate to 0, declared the scanner inside the try catch block and got rid of the scan.next();编辑:我将 year 和 yearDuplicate 的起始值更改为 0,在 try catch 块内声明扫描仪并摆脱了 scan.next(); in both try catch blocks.在两个 try catch 块中。 Now, I'm getting a loop with the first try catch block but it's still carrying over my previous input.现在,我得到了一个包含第一个 try catch 块的循环,但它仍在继承我之前的输入。

Your basic 'read until you get an integer' block should look like this:您的基本“读取直到获得整数”块应如下所示:

    do {
        try {
            year = scan.nextInt();
            if (year <= 0) { // see comment
                System.out.println("ERROR. Please enter positive number");
            }
        } catch(Exception e){
            System.out.println("ERROR. Please enter a number "
                               + "without decimals");
            scan.next();
            year = -1;
        }                
    } while (year <= 0);

So if there's non-numeric input, you actively set a value that will cause you to loop, rather than relying on what might have been there already.因此,如果有非数字输入,您会主动设置一个会导致循环的值,而不是依赖可能已经存在的值。

Also, you want to make sure the input was positive.此外,您要确保输入是正的。

Given that you should be able to figure out the entire program.鉴于您应该能够弄清楚整个程序。

Where I said "see comment", perhaps you might want to check for a reasonable year;在我说“查看评论”的地方,也许您可​​能想要查看合理的年份; maybe throw out anything before about 1752 (when Britain and the US adopted the Gregorian calendar).可能会在 1752 年左右(当时英国和美国采用公历)之前扔掉任何东西。

Your original problem likely was due to the year % 1 != 0 condition.您最初的问题可能是由于year % 1 != 0条件造成的。 That means "remainder when dividing year by 1 is not 0".这意味着“将年份除以 1 的余数不是 0”。 It's always true for non-negative values.对于非负值总是如此。 I'd have to look up how Java implements % for negative values to answer in that case.在这种情况下,我必须查找 Java 如何为负值实现%来回答。

Fixed the code.修复了代码。

int year = 0;
        int yearDuplicate = 0;
        System.out.println("This calculator tells you whether a year that you "
                + "enter is a leap year.\nPlease enter a year:");
        
        do{
            Scanner scan = new Scanner(System.in);
            try{
                yearDuplicate = scan.nextInt();
                if(yearDuplicate % 4 == 0){ 
                    if(yearDuplicate % 100 == 0){
                        if(yearDuplicate % 400 == 0){
                            System.out.println(yearDuplicate + " is a leap year.");
                        }else{
                            System.out.println(yearDuplicate + " is not a leap year.");
                        }
                    }else{
                        System.out.println(yearDuplicate + " is a leap year.");
                    }
                }else{
                    System.out.println(yearDuplicate + " is not a leap year.");
                }
                System.out.println("Enter another year or enter '-1' to quit:");  
                
            }catch(Exception e){
                System.out.println("ERROR. Please enter a numerical digit "
                        + "without decimals:");
                scan.next();
            }
            
        }while(yearDuplicate != -1);

Basically removed the first try catch block.基本上删除了第一个 try catch 块。 Made the second try catch block include the entire do while loop.使第二个 try catch 块包含整个 do while 循环。 If anyone know what mistakes I made before and why they were wrong, I'd still like to know.如果有人知道我以前犯过哪些错误以及错误的原因,我仍然想知道。

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

相关问题 Java:Do-While循环中的Try-Catch语句 - Java: Try-Catch statement within a Do-While loop 带有 do-while 循环的 Java try-catch 输入验证 - Java try-catch input validation with do-while loop 使用try-catch块的while循环在循环一次后不会等待try块中的输入 - While loop with try-catch blocks doesn't wait for input in the try block after looping once 嵌套在do-while循环中的try-catch实际上没有循环有原因吗? - Is there a reason why a try-catch nested within a do-while loop not actually loop? Java try-catch 在 do-while 循环内 - Java try-catch inside of a do-while loop 同时执行,尝试捕获循环错误 - Do-while, try-catch loop error Java Do-While Try-Catch 异常处理循环错误和符号:变量错误 - Java Do-While Try-Catch exception handling loop error and symbol: variable error 在Java中的try-catch块中嵌入try-catch块 - Embedding try-catch blocks within try-catch blocks in Java 当无限循环时,为什么while和do-while循环优先于for循环? - Why are while and do-while loops preferred over for loops when looping infinitely? 如何修复do-while循环中的逻辑,然后应用try-catch块来捕获并显示来自另一个类的错误消息? - How to fix the logic in my do-while loop, and then applying the try-catch block to catch and display an error message from another class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM