Institute of Computer Science
  1. Courses
  2. 2017/18 spring
  3. Object-Oriented Programming (Narva College) (P2NC.01.083)
ET
Log in

Object-Oriented Programming (Narva College) 2017/18 spring

  • Home
  • Materials
  • Java Glossary
  • Source Example
  • Cheat sheet (S1-S6)
  • Grading
  • Links
Session 1

Scanner

Input and output (I/O) operations are very complicated, both at the software and at the hardware level. Part of the problem is that the way in which data is organized outside the computer is different from the way it is organized inside the computer. Lots of computation is needed to convert data between its various forms. Luckily, most of the complication has been hidden inside methods that our program can use.

In this session, we will use methods of the class java.util.Scanner for input. Scanner is not a part of the fundamental Java language, but is part of a package java.util that we can include in our program. A package is a collection of classes which can be used in any program.

After Python, it may seem odd that Java does not have I/O built into it. The reason for this is that there are lots of different ways to get input from users – keyboards, mice, touch screens, speech, etc. Java uses different classes of objects to handle this variety of different input mechanisms, and Java allows the programmer to pick the right I/O package for the job.

Example:

//Import the package to work with the console input
import java.util.Scanner;  

public class Data_Input {
  public static void main(String[] args) {
    //Create own Scanner object with a name (e.g. "scan") and 
    //tell it to read text from the keyboard System.in
    Scanner scan = new Scanner(System.in);

    System.out.println("Enter your name");
    //Get a string from the input
    String userName = scan.nextLine();

    System.out.println("Enter an integer");
    //Get an integer from the input
    int myInt = scan.nextInt();

    System.out.println("Enter a double");
    //Get a double from the input
    double myDouble = scan.nextDouble();

    System.out.println(userName + " your entered integer: " + myInt);
    System.out.println(" and double: " + myDouble);
  } 
}
Session 1
  • Institute of Computer Science
  • Faculty of Science and Technology
  • University of Tartu
In case of technical problems or questions write to:

Contact the course organizers with the organizational and course content questions.
The proprietary copyrights of educational materials belong to the University of Tartu. The use of educational materials is permitted for the purposes and under the conditions provided for in the copyright law for the free use of a work. When using educational materials, the user is obligated to give credit to the author of the educational materials.
The use of educational materials for other purposes is allowed only with the prior written consent of the University of Tartu.
Terms of use for the Courses environment