【发布时间】:2016-09-16 18:43:34
【问题描述】:
总的来说,我是一个新程序员,如果这个问题有点基础,请原谅我。
该程序的目标是简单计算“最佳体重”,并在运行时不断抛出异常,超过第 35 行中的 a 和 b 字符串比较。我尝试删除逻辑运算符,但似乎仍然没有成为问题。我哪里错了?
import java.util.*;
public class WeightCalc {
//Initialize variables
static int feet = 0, inches = 0, totalWeight = 0;
static boolean isMale;
public static void optimalWeight(){
// Calculate optimal weight
if (isMale == true){
if (feet >= 5){
totalWeight = 106 + 6*(inches);
} else{
System.out.print("Error, you're a midget.");
}
}
if (isMale == false){
if (feet >= 5){
totalWeight = 100 + 5*(inches);
} else{
System.out.print("Error, you're a midget.");
}
}
}
public static void main(String[] args){
String a = "Male", b = "male";
// Initialize kboard Scanner
Scanner kboard = new Scanner(System.in);
// Ask for gender and assign isMale
System.out.println("What is your gender? ");
String gender = kboard.nextLine();
if (gender.equals(a) || gender.equals(b)){
isMale = true;
}else {
isMale = false;
}
// Ask for height, first feet, then inches
System.out.println("What is your height in regards to feet? ");
kboard.nextInt(feet);
System.out.println("What is your remaining h eight in inches? ");
kboard.nextInt(inches);
//Call optimalWeight method and run
optimalWeight();
// Print the output
System.out.println("Your optimal weight should be " + totalWeight + ".");
// Set isMale opposite to what it was before and calculate opposite sex's potential weight
isMale = !isMale;
optimalWeight();
// Print the output of the second run
System.out.println("If you were of the opposite sex, your weight would be " + totalWeight + ".");
// Close the Scanner variable
kboard.close();
}
}
【问题讨论】:
-
第 35 行是哪一行?
if (gender.equals(a) || gender.equals(b)){?还有什么例外? -
不要使用
a == true或a == false比较布尔值。只需使用a或!a。 -
再次检查您的行号,因为
if (gender.equals(a) || gender.equals(b))行中有no 正则表达式处理。更有可能的是,它在kboard.nextInt(feet)行中,应该是feet = kboard.nextInt()。 -
我认为这实际上是 OpenJDK 中的一个错误——与其说是行为,不如说是神秘的错误。似乎
setRadix方法可以检查radix < 2。但是,这可能不是常见的问题。 -
@AndyTurner
Integer.parseInt(String s, int radix)定义它将抛出NumberFormatException用于错误的基数值,nextInt(int radix)定义它将调用parseInt(),所以他们可能依赖于它的验证,而不是意识到正则表达式对于0基数会变坏之前它可以调用parseInt()。
标签: java regex patternsyntaxexception