简体   繁体   中英

How to get the time that it took to type a sentence in Java

I have a kind of complex problem that I hope I can get some help on. My teacher has asked for a homework question that we find how long it took us to type a sentence "Hello World." and print it out in milliseconds using the Date class while also checking if it is correct. This is what I have so far

import java.util.*;
public class Date 
{
public static void main(String[] args) 
{
    Scanner hello = new Scanner (System.in);
    Date d1 = new Date();
    System.out.println("Your job is to type the sentence \"Hello World!\" as fast as you can.");
    System.out.println("When you are ready, press enter, type the sentence, and press enter again.");
    System.out.println("");
    String sen = hello.nextLine();
    if(sen == "Hello World!")
    {
        System.out.println(d1.getTime());
    }
    if (sen != "Hello World!")
    {
        System.out.println("Incorrect Input");
    }
}
}

I looked some stuff up and I'm trying to use the getTime method, but it just doesn't let me use it.

My main idea is to use getTime to check how long it took the user to input the sentence, but I am just not at all sure how to do that.

Count nanoseconds with System.nanoTime

I think you're close, but the method needs some improvement.

public static void main(String[] args)  {
    Scanner hello = new Scanner(System.in);
    // starting time
    long start = System.nanoTime();
    System.out.println("Your job is to type the sentence \"Hello World!\" as fast as you can.");
    System.out.println("When you are ready, press enter, type the sentence, and press enter again.\n");
    String sen = hello.nextLine();
    while (!sen.equals("Hello World!")) {
        System.out.println("Incorrect Input");
        sen = hello.nextLine();
    }
    // end time
    long elapsedTime = System.nanoTime() - start;
    System.out.println("It took you "elapsedTime"ns to type Hello World!");
}

The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API . For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7.

Using the modern date-time API:

import java.time.Instant;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner hello = new Scanner(System.in);
        System.out.println("Your job is to type the sentence \"Hello World!\" as fast as you can.");
        System.out.println("When you are ready, press enter, type the sentence, and press enter again.");
        System.out.println("");
        long start = Instant.now().toEpochMilli();
        String sen = hello.nextLine();
        if (sen.equals("Hello World!")) {
            System.out.println("You took " + (Instant.now().toEpochMilli() - start) + " milliseconds");
        } else {
            System.out.println("Incorrect Input");
        }
    }
}

A sample run:

Your job is to type the sentence "Hello World!" as fast as you can.
When you are ready, press enter, type the sentence, and press enter again.

Hello World!
You took 4711 milliseconds

Learn about the modern date-time API from Trail: Date Time .

Also, compare strings by using String#equals instead of == .

If at all you need to use java.util.Date :

import java.util.Date;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner hello = new Scanner(System.in);
        System.out.println("Your job is to type the sentence \"Hello World!\" as fast as you can.");
        System.out.println("When you are ready, press enter, type the sentence, and press enter again.");
        System.out.println("");
        Date date = new Date();
        long start = date.getTime();
        String sen = hello.nextLine();
        if (sen.equals("Hello World!")) {
            date = new Date();
            long end = date.getTime();
            System.out.println("You took " + (end - start) + " milliseconds");
        } else {
            System.out.println("Incorrect Input");
        }
    }
}

The other answers are correct that it's better to use System.nanotime() or Instant (so your teacher is wrong). In any case, since you have to use Date , I will try to explain what went wrong when you tried to use the getTime method. Because you are correct: if you're using the old and poorly designed Date class, then use its getTime method.

You have called your own class Date too. So there are two classes with the same class name in play here, which gives rise to the trouble. When you do this:

    Date d1 = new Date();

— then you are creating an instance of your own Date class, not of the java.util.Date class that your teacher (probably) meant. And when next you try for example (which you didn't show us in your question, but you should):

    long time = d1.getTime();

— then Java sees that your own Date class hasn't got a getTime method and issues an error message.

TL;DR The solution is to call your own class something else than Date .

PS There are ways to handle two classes with the same name, but it's never quite as easy to read and I don't recommend it here.

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