我希望程序在用户输入小于零的值时立即结束,但此程序会一直询问所有三个值然后退出。
例如,如果我输入-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.
更多推荐
发布评论