输入负数后,循环不会结束,直到用户输入所有值。(Loop doesn't end upon entering negative number until user finish enteri

编程入门 行业动态 更新时间:2024-10-18 19:28:44
输入负数后,循环不会结束,直到用户输入所有值。(Loop doesn't end upon entering negative number until user finish entering all values.)

我希望程序在用户输入小于零的值时立即结束,但此程序会一直询问所有三个值然后退出。

例如,如果我输入-3,2,1,程序在第一个高度输入-3后不显示错误,而是取所有三个值然后显示“无效高度”消息。

一旦用户输入负值,如何使程序显示无效高度的错误消息?

//Program Asking user to input three different heights HeightOne = Integer.parseInt(JOptionPane.showInputDialog("Enter Height of First Tower")); HeightTwo = Integer.parseInt(JOptionPane.showInputDialog("Enter Height of Second Tower")); HeightThree = Integer.parseInt(JOptionPane.showInputDialog("Enter Height of Third Tower")); If (centimeterHeightOne < 0 || centimeterHeightTwo < 0 || centimeterThree < 0) { JOptionPane.showMessageDialog(null, "Invalid height"; } else { conditions... }

I want the program to end as soon as user enters a value which is less than zero but this program keep asking all three value then exits.

For instance, if I enter -3, 2, 1, The program doesn't display error after entering -3 for the first height, instead it takes all three values then display the "invalid height" message.

How do I make it program display error message of invalid height as soon as user enters a negative value?

//Program Asking user to input three different heights HeightOne = Integer.parseInt(JOptionPane.showInputDialog("Enter Height of First Tower")); HeightTwo = Integer.parseInt(JOptionPane.showInputDialog("Enter Height of Second Tower")); HeightThree = Integer.parseInt(JOptionPane.showInputDialog("Enter Height of Third Tower")); If (centimeterHeightOne < 0 || centimeterHeightTwo < 0 || centimeterThree < 0) { JOptionPane.showMessageDialog(null, "Invalid height"; } else { conditions... }

最满意答案

输入负数后,循环不会结束,直到用户输入所有值。

因为那正是你正在做的事情。 如果您想在一个负值后终止,请在您要求每个输入后立即输入:

heightOne = Integer.parseInt(JOptionPane.showInputDialog("Enter Height of First Tower")); if(heightOne < 0) { displayError(); //return; ? } heightTwo = ... if(heightTwo < 0) { displayError(); } ...

请遵循Java命名约定并将HeightOne更改为heightOne 。

Loop doesn't end upon entering negative number until user finish entering all values.

Because that's exactly what you're doing. If you want to terminate after one negative value, put if right after you ask for each input:

heightOne = Integer.parseInt(JOptionPane.showInputDialog("Enter Height of First Tower")); if(heightOne < 0) { displayError(); //return; ? } heightTwo = ... if(heightTwo < 0) { displayError(); } ...

Please follow Java Naming Conventions and change HeightOne to heightOne.

更多推荐

本文发布于:2023-08-05 22:10:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1440879.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:负数   结束   用户   Loop   entering

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!