简体   繁体   中英

Why does this throw an error/not run at all?

I'm running this in VS code and compiling and running through terminal with the proper JDK installed but nothing seems to run it just goes blank and then I type "clear" and a mismatch exception is thrown. Can someone explain why? Thank you:)

import java.util.Scanner;
class realTime {

    public static void Time(int seconds) {

        int min = 0, hours = 0;

        min = (int)seconds / 60;
        hours = (int)seconds / 3600;

        System.out.println("Hours: " + hours);
        System.out.println("Minutes: " + min);

    }

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        int seconds = scan.nextInt();

        Time(seconds);
    }
}

I know that it will not calculate the min and hours correctly I'm just putting code down to test whether it runs.

Because the terminal is waiting for some value, in this lines:

Scanner scan = new Scanner(System.in);
int seconds = scan.nextInt();

Basically you're creating a Scanner object, and declaring an int variable waiting for a value, in this case a next integer, to do something.

Just type some integer number in your terminal and it should be working fine.

In the terminal the scanner is waiting for the user input which is of type int, you need to enter the seconds in the terminal.

The error is showing because you are entering String type value but the scanner is expecting int type.

Hope this resolve the issue.

The solution is already present in other answers, but why the InputMismatchException is what this answer is about.

From the docs,

For example, this code allows a user to read a number from System.in:

 Scanner sc = new Scanner(System.in); int i = sc.nextInt();

For nextInt()

public int nextInt()

Scans the next token of the input as an int.

Throws: InputMismatchException - if the next token does not match the Integer regular expression, or is out of range

Here "clear" does not match the regular expression of Integer.

Since you are not passing any radix to nextInt() method, it expects the input to have only 0-9 (Decimal Number System- Base 10 is the default). Had it been nextInt(16) , It would accept any HexaDecimal (0-F, Base 16) Number and so on.

It is worth noting the another case where you can get the same Exception, This happens if the input > Integer.MAX_VALUE .

You need to have a prompt for the user to enter in there time in seconds so your scanner can actually get something to put in for your seconds int. Do something like this:

System.out.println("Enter seconds to convert");
   int seconds = scan.nextInt();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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