简体   繁体   English

扫描仪无法正常工作

[英]Scanner not working as expected

Hey everyone i am working on a personal project with java (I am still currently learning the language) and have come here with a question or two. 大家好,我正在用Java开发个人项目(我目前仍在学习该语言),来这里有一个或两个问题。

First Question 第一个问题

In my try block i am allowed to ask the user to input a value to be assigned to a variable and in my catch block, if the user inputs a wrong value or skips the entry, it throws an exception and informs the user that a default value has been set. 在我的try块中,允许我要求用户输入要分配给变量的值,而在我的catch块中,如果用户输入了错误的值或跳过了输入,它会引发异常并通知用户默认值值已设置。 This is a correct way to do this yes? 这是正确的方法吗?

Code Example 代码示例

(Note: I have many of these try/catch statements working the same way as the one below inside a method.) (注意:我有许多这样的try / catch语句,其工作方式与方法内部的以下语句相同。)

 try {
        System.out.print("Please enter a value for price of computer: ");
        price = sc.nextFloat();

    } catch (InputMismatchException ex) {    //Catch skip or error
        System.out.println("You entered an invalid value for price, it is assumed to be 0.");
        price = 0F;   //Assign a default value
    }

Second Question 第二个问题

When I compile and execue this it doesn't allow me to enter a variable, but instead skips right to the exception. 当我编译并执行此操作时,它不允许我输入变量,而是跳过该异常。 I am not sure what i am missing, so I would love any advice and thanks again to a great community. 我不确定自己缺少什么,因此我很乐意提供任何建议,并再次感谢一个很棒的社区。

Working code: 工作代码:

import java.util.*;

public class InputTest{
    public static void main(String args[]) {
        float price = -1F;
        try {
            Scanner sc = new Scanner(System.in);
            System.out.println("Please enter a value for price of computer: ");
            if (sc.hasNextFloat()){
                price = sc.nextFloat();
            }
        } catch (InputMismatchException ex) {    //Catch skip or error
            System.out.println("You entered an invalid value for price, it is assumed to be 0.");
            price = 0F;   //Assign a default value
        }catch(Exception err){
            err.printStackTrace();
        }
        System.out.println("price:"+price);

    }
}

output: 输出:

D:\Study\Java>java InputTest
Please enter a value for price of computer:
1
price:1.0

D:\Study\Java>java InputTest
Please enter a value for price of computer:
2
price:2.0

D:\Study\Java>java InputTest
Please enter a value for price of computer:
3.3
price:3.3

Change from your code snippet: 从您的代码段更改:

I have added sc.hasNextFloat() before assigning value to float variable. 我在向浮点变量赋值之前添加了sc.hasNextFloat() Do not enter f or F in input value when you are reading value from console. 从控制台读取值时,请勿在输入值中输入f或F。 I have provided sample input value for better understanding. 我提供了示例输入值,以更好地理解。

This code looks correct for the most part. 这段代码在大多数情况下看起来都是正确的。 Although, I am assuming your sc variable is the same Scanner Object through multiple inputs (as you stated), so its buffer may not be cleared as you would assume each time you use it by using the sc.nextFloat() method. 虽然,我假设您的sc变量通过多个输入(如您所述)是同一个Scanner Object,所以可能不会像每次使用sc.nextFloat()方法时所假定的那样清除其缓冲区。

You can avoid this by reinitializing the Scanner object before you use it again. 您可以通过在再次使用之前重新初始化Scanner对象来避免这种情况。 If I recall correctly, there is no way to clear the buffer of a Scanner Object explicitly, so it would have to be reinitialized to "clear" it. 如果我没记错的话,没有办法明确地清除Scanner Object的缓冲区,因此必须重新初始化它以“清除”它。

You can also use the sc.hasNextFloat() to verify a float value has been entered. 您也可以使用sc.hasNextFloat()验证是否已输入浮点值。

You can also use and Float.parseFloat(sc.nextLine()) to capture the entire input before a new line is entered. 您还可以使用Float.parseFloat(sc.nextLine())在输入新行之前捕获整个输入。

Okay, i have found my error thanks to everyone's help here at stackoverflow. 好的,由于在stackoverflow的每个人的帮助,我发现了自己的错误。

When i initialized my Scanner variable i did it like this: Scanner sc = new Scanner("System.in") 当我初始化Scanner变量时,它是这样的:Scanner sc = new Scanner(“ System.in”)

Which meant i wanted it to read a string and not the input from the user so it would automatically throw my exception. 这意味着我希望它读取字符串,而不是用户输入,因此它将自动引发我的异常。

To fix this i removed the quotes and it is now working properly! 为了解决这个问题,我删除了引号,现在可以正常使用了!

Thanks again to everyone! 再次感谢大家!

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM