我的代码在出现空值后不会继续运行。

huangapple go评论144阅读模式
英文:

My code wont continue after null shows up

问题

以下是您的代码翻译部分:

import java.util.Scanner;

public class Paint1 {

    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);
        double wallHeight = 0.0;
        double wallWidth = 0.0;
        double wallArea = 0.0;
        double gallonsPaintNeeded = 0.0;

        final double squareFeetPerGallons = 350.0;

        try {
            System.out.println("输入墙的高度(英尺):");
            wallHeight = scnr.nextDouble();

            if (wallHeight <= 0){
                throw new Exception("无效的数字");
            }

            System.out.println("输入墙的宽度(英尺):");
            wallWidth = scnr.nextDouble();

            if (wallWidth <= 0) {
                throw new Exception("无效的数字");
            }

            wallArea = wallHeight * wallWidth;
            System.out.println("墙面积:" + wallArea + " 平方英尺");
        }
        catch (Exception excpt) {
            System.out.println(excpt.getMessage());
            System.out.println("无法计算墙面积");
        }

        gallonsPaintNeeded = wallArea / squareFeetPerGallons;
        System.out.println("所需油漆:" + gallonsPaintNeeded + " 加仑");

        // 这里是您提到的问题,您需要添加代码来处理输入为 "thirty" 的情况
        // 由于这不是您原始代码的一部分,我无法直接提供代码。您可以尝试以下方法:
        // 在读取 wallWidth 之前,使用 scnr.next() 读取输入,然后将其转换为数字。
        // 您可以使用条件语句来处理 "thirty",例如,如果输入是 "thirty",则将 wallWidth 设置为 30。

    }
}

请注意,由于您的问题涉及到对输入 "thirty" 的处理,这部分内容不在原始代码中,因此我无法为您提供完整的解决方案。您可以根据我在注释中的建议尝试处理这种情况。如果您需要更详细的帮助,请随时提问。

英文:

here is my code

import java.util.Scanner;
public class Paint1 {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double wallHeight = 0.0;
double wallWidth = 0.0;
double wallArea = 0.0;
double gallonsPaintNeeded = 0.0;
final double squareFeetPerGallons = 350.0;
// Implement a do-while loop to ensure input is valid
// Prompt user to input wall&#39;s height
try {
System.out.println(&quot;Enter wall height (feet): &quot;);
wallHeight = scnr.nextDouble();
if (wallHeight &lt;= 0){
throw new Exception(&quot;Invalid number&quot; );
}
// Implement a do-while loop to ensure input is valid
// Prompt user to input wall&#39;s width
System.out.println(&quot;Enter wall width (feet): &quot;);
wallWidth = scnr.nextDouble();
if (wallWidth &lt;= 0) {
throw new Exception(&quot;invalid number&quot;);
}
// Calculate and output wall area
wallArea = wallHeight * wallWidth;
System.out.println(&quot;Wall area: &quot; + wallArea + &quot; square feet&quot;);
}
catch (Exception excpt) {
System.out.println(excpt.getMessage());
System.out.println(&quot;Cannot compute wall area&quot;);
}
// Calculate and output the amount of paint (in gallons) needed to paint the wall
gallonsPaintNeeded = wallArea/squareFeetPerGallons;
System.out.println(&quot;Paint needed: &quot; + gallonsPaintNeeded + &quot; gallons&quot;);

my code works fine for the first sets of input which are 30, and 25. I dont know how to make my code continue after the next input is "thirty" and 25. the program just stops, after giving me null but it needs to continue after "thirty". does anyone have any idea how to help me out.

答案1

得分: 1

你需要在调用 nextDouble 之前检查扫描器是否具有适当的令牌 hasNextDouble,并且忽略类似这样的不正确输入:

while (!scnr.hasNextDouble()) {
    scnr.next(); // 跳过“不是数字”令牌
}
wallHeight = scnr.nextDouble();

然后,无效的“非双精度”输入将被静默丢弃,直到输入数字为止,之后您会验证其是否正确(大于 0)。

类似地,您会等待直到输入有效的数字,然后只输出参数无效的消息。

一旦两个输入值都有效,您将计算必要的输出并在不处理异常的情况下退出(如果发生异常,将会重新抛出)。

完整代码:

public static void main(String[] args) {
    Scanner scnr = new Scanner(System.in);
    double wallHeight = 0.0;
    double wallWidth = 0.0;
    double wallArea = 0.0;
    double gallonsPaintNeeded = 0.0;
    
    final double squareFeetPerGallons = 350.0;
    // 循环获取高度
    while (wallHeight <= 0.0) {
        System.out.print("输入墙壁高度(英尺):");
        while (!scnr.hasNextDouble()) {
            scnr.next();
        }
        wallHeight = scnr.nextDouble();
        
        if (wallHeight <= 0){
            System.out.println("无效的墙壁高度");
        }
    }
    // 循环获取宽度
    while (wallWidth <= 0) {  
        System.out.print("输入墙壁宽度(英尺):");
        while (!scnr.hasNextDouble()) {
            scnr.next();
        }
        wallWidth = scnr.nextDouble();
        
        if (wallWidth <= 0) {
            System.out.println("无效的墙壁宽度");
        }
    }      
    wallArea = wallHeight * wallWidth;
    System.out.println("墙面积:" + wallArea + " 平方英尺");
        
    // 计算并输出涂刷墙壁所需的油漆量(以加仑为单位)
    gallonsPaintNeeded = wallArea/squareFeetPerGallons;
    System.out.println("所需油漆量:" + gallonsPaintNeeded + " 加仑");
}

示例输出:

输入墙壁高度(英尺):twelve
-20
无效的墙壁高度
输入墙壁高度(英尺):20
输入墙壁宽度(英尺):no
0
无效的墙壁宽度
输入墙壁宽度(英尺):15
墙面积:300.0 平方英尺
所需油漆量:0.8571428571428571 加仑
英文:

You need to check if the scanner has appropriate token hasNextDouble before calling nextDouble and swallow incorrect input like this:

while (!scnr.hasNextDouble()) {
    scnr.next(); // skip &quot;not a number&quot; token
}
wallHeight = scnr.nextDouble();

Then invalid "non-double" input will be quietly discarded until a number is entered and after that you validate if it's correct (greater than 0).

Similarly you wait until a valid number is entered and just output the message that the parameter is invalid.

As soon as both input values are valid, you calculate necessary outputs and exit without handling exceptions (if any occurs it will be rethrown).

Full code:

public static void main(String[] args) {
    Scanner scnr = new Scanner(System.in);
    double wallHeight = 0.0;
    double wallWidth = 0.0;
    double wallArea = 0.0;
    double gallonsPaintNeeded = 0.0;
    
    final double squareFeetPerGallons = 350.0;
    // loop for height
    while (wallHeight &lt;= 0.0) {
        System.out.print(&quot;Enter wall height (feet): &quot;);
        while (!scnr.hasNextDouble()) {
            scnr.next();
        }
        wallHeight = scnr.nextDouble();
        
        if (wallHeight &lt;= 0){
            System.out.println(&quot;Invalid wallHeight&quot;);
        }
    }
    // loop for width
    while (wallWidth &lt;= 0) {  
        System.out.print(&quot;Enter wall width (feet): &quot;);
        while (!scnr.hasNextDouble()) {
            scnr.next();
        }
        wallWidth = scnr.nextDouble();
        
        if (wallWidth &lt;= 0) {
            System.out.println(&quot;invalid wallWidth&quot;);
        }
    }      
    wallArea = wallHeight * wallWidth;
    System.out.println(&quot;Wall area: &quot; + wallArea + &quot; square feet&quot;);
        
    // Calculate and output the amount of paint (in gallons) needed to paint the wall
    gallonsPaintNeeded = wallArea/squareFeetPerGallons;
    System.out.println(&quot;Paint needed: &quot; + gallonsPaintNeeded + &quot; gallons&quot;);
}

Example output

Enter wall height (feet): twelve
-20
Invalid wallHeight
Enter wall height (feet): 20
Enter wall width (feet): no
0
invalid wallWidth
Enter wall width (feet): 15
Wall area: 300.0 square feet
Paint needed: 0.8571428571428571 gallons

答案2

得分: 0

我假设您希望您的应用程序继续运行并提示用户再次输入相同的内容?可以通过一个 while 循环来实现,该循环将继续评估您已经编写的代码。类似下面的代码应该可以实现这一点:

import java.util.Scanner;

public class Stack {

  static Scanner scnr = new Scanner(System.in);

  public static void main(String[] args) {
    while(true) {
      computePaint();
    }
  }

  private static void computePaint() {
      double wallHeight = 0.0;
      double wallWidth = 0.0;
      double wallArea = 0.0;
      double gallonsPaintNeeded = 0.0;

      final double squareFeetPerGallons = 350.0;

      // 使用 do-while 循环确保输入有效
      // 提示用户输入墙的高度
      try {
        System.out.println("输入墙的高度(英尺):");
        wallHeight = scnr.nextDouble();

        if (wallHeight <= 0) {
          throw new Exception("无效的数字");
        }

        // 使用 do-while 循环确保输入有效
        // 提示用户输入墙的宽度

        System.out.println("输入墙的宽度(英尺):");
        wallWidth = scnr.nextDouble();

        if (wallWidth <= 0) {
          throw new Exception("无效的数字");
        }

        // 计算并输出墙体面积
        wallArea = wallHeight * wallWidth;
        System.out.println("墙体面积:" + wallArea + " 平方英尺");
      } catch (Exception excpt) {
        System.out.println(excpt.getMessage());
        System.out.println("无法计算墙体面积");
      }

      // 计算并输出涂料(以加仑为单位)所需的数量
      gallonsPaintNeeded = wallArea / squareFeetPerGallons;
      System.out.println("所需涂料:" + gallonsPaintNeeded + " 加仑");
    }
  }
}

实际上,如果有必要的话,应该有一些中断执行的方法,但我认为 while(true) 可以说明这一点。

英文:

I assume you want your application to keep running and prompt the user for the same inputs again? This can be accomplished with a while loop that just continues to evaluate the code you've already written. Something like this should do:

import java.util.Scanner;
public class Stack {
static Scanner scnr = new Scanner(System.in);
public static void main(String[] args) {
while(true) {
computePaint();
}
}
private static void computePaint() {
double wallHeight = 0.0;
double wallWidth = 0.0;
double wallArea = 0.0;
double gallonsPaintNeeded = 0.0;
final double squareFeetPerGallons = 350.0;
// Implement a do-while loop to ensure input is valid
// Prompt user to input wall&#39;s height
try {
System.out.println(&quot;Enter wall height (feet): &quot;);
wallHeight = scnr.nextDouble();
if (wallHeight &lt;= 0) {
throw new Exception(&quot;Invalid number&quot;);
}
// Implement a do-while loop to ensure input is valid
// Prompt user to input wall&#39;s width
System.out.println(&quot;Enter wall width (feet): &quot;);
wallWidth = scnr.nextDouble();
if (wallWidth &lt;= 0) {
throw new Exception(&quot;invalid number&quot;);
}
// Calculate and output wall area
wallArea = wallHeight * wallWidth;
System.out.println(&quot;Wall area: &quot; + wallArea + &quot; square feet&quot;);
} catch (Exception excpt) {
System.out.println(excpt.getMessage());
System.out.println(&quot;Cannot compute wall area&quot;);
}
// Calculate and output the amount of paint (in gallons) needed to paint the wall
gallonsPaintNeeded = wallArea / squareFeetPerGallons;
System.out.println(&quot;Paint needed: &quot; + gallonsPaintNeeded + &quot; gallons&quot;);
}
}

Really there should be something to interrupt this execution if necessary, but I think while(true) illustrates the point.

答案3

得分: 0

你正在将一个字符串值传递给一个双精度数。
这就是你得到错误的原因。
你可以修改代码为 -

public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);
        double wallHeight = 0.0;
        double wallWidth = 0.0;
        double wallArea = 0.0;
        double gallonsPaintNeeded = 0.0;

        final double squareFeetPerGallons = 350.0;

        // 使用do-while循环来确保输入有效
        // 提示用户输入墙的高度
        try {
            while (wallHeight <= 0)
                wallHeight = getNumber(scnr, "Enter wall height (feet): ");
            while (wallWidth <= 0)
                wallWidth = getNumber(scnr, "Enter wall width (feet):  ");
            // 计算并输出墙面积
            wallArea = wallHeight * wallWidth;
            System.out.println("Wall area: " + wallArea + " square feet");
        } catch (Exception excpt) {
            System.out.println(excpt.getMessage());
            System.out.println("Cannot compute wall area");
        }

        // 计算并输出涂刷墙面所需的油漆量(以加仑为单位)
        gallonsPaintNeeded = wallArea / squareFeetPerGallons;
        System.out.println("Paint needed: " + gallonsPaintNeeded + " gallons");
    }

    private static double getNumber(Scanner scnr, String message) throws Exception {
        double number = 0.0;
        try {
            boolean isValidNumber = false;
            while (!isValidNumber) {
                System.out.println(message);
                String value = scnr.next();
                number = Double.parseDouble(value);
                isValidNumber = true;
            }
        } catch (Exception e) {
            System.out.println("Value entered is not correct.");
            return -1;
        }
        return number;
    }
英文:
You are providing a string value to a double.
So thats the reason you are getting the error.
You can modified the code to -
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double wallHeight = 0.0;
double wallWidth = 0.0;
double wallArea = 0.0;
double gallonsPaintNeeded = 0.0;
final double squareFeetPerGallons = 350.0;
// Implement a do-while loop to ensure input is valid
// Prompt user to input wall&#39;s height
try {
while (wallHeight &lt;= 0)
wallHeight = getNumber(scnr, &quot;Enter wall height (feet): &quot;);
while (wallWidth &lt;= 0)
wallWidth = getNumber(scnr, &quot;Enter wall width (feet):  &quot;);
// Calculate and output wall area
wallArea = wallHeight * wallWidth;
System.out.println(&quot;Wall area: &quot; + wallArea + &quot; square feet&quot;);
} catch (Exception excpt) {
System.out.println(excpt.getMessage());
System.out.println(&quot;Cannot compute wall area&quot;);
}
// Calculate and output the amount of paint (in gallons) needed to paint the wall
gallonsPaintNeeded = wallArea / squareFeetPerGallons;
System.out.println(&quot;Paint needed: &quot; + gallonsPaintNeeded + &quot; gallons&quot;);
}
private static double getNumber(Scanner scnr, String message) throws Exception {
double number = 0.0;
try {
boolean isValidNumber = false;
while (!isValidNumber) {
System.out.println(message);
String value = scnr.next();
number = Double.parseDouble(value);
isValidNumber = true;
}
} catch (Exception e) {
System.out.println(&quot;Value entered is not correct.&quot;);
return -1;
}
return number;
}

huangapple
  • 本文由 发表于 2020年10月9日 06:27:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/64271481.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定