Project 1. Java Data types and input/output 1/17/2014. Primitive data types (2) Primitive data types in Java

Similar documents
Full file at

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Programming with Java

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

ing execution. That way, new results can be computed each time the Class The Scanner

File I/O Array Basics For-each loop

Computational Expression

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Full file at

Java Input/Output. 11 April 2013 OSU CSE 1

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Object-Oriented Programming in Java

Chapter 2 ELEMENTARY PROGRAMMING

Chapter 2 Elementary Programming

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

Simple Java Input/Output

Lesson 3: Accepting User Input and Using Different Methods for Output

A variable is a name for a location in memory A variable must be declared

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Reading Input from Text File

2.5 Another Application: Adding Integers

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

CS313D: ADVANCED PROGRAMMING LANGUAGE

CSC 1214: Object-Oriented Programming

CS 251 Intermediate Programming Java I/O Streams

A+ Computer Science -

Lecture Set 2: Starting Java

Object-Oriented Programming and Data Structures

Fundamentals of Programming Data Types & Methods

Lecture Set 2: Starting Java

ECE 122 Engineering Problem Solving with Java

Java enum, casts, and others (Select portions of Chapters 4 & 5)

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

Chapter 4: Loops and Files

PIC 20A Streams and I/O

Chapter 4: Loops and Files

Object Oriented Programming. Java-Lecture 1

Chapter 2: Data and Expressions

HST 952. Computing for Biomedical Scientists Lecture 8

A token is a sequence of characters not including any whitespace.

Program Elements -- Introduction

Introduction to Java Applications; Input/Output and Operators

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming

Text User Interfaces. Keyboard IO plus

File Input/Output. Introduction to Computer Science I. Overview (1): Overview (2): CSE 1020 Summer Bill Kapralos. Bill Kapralos.

IT101. File Input and Output

Primitive Data Types: Intro

We now start exploring some key elements of the Java programming language and ways of performing I/O

A Quick and Dirty Overview of Java and. Java Programming

Section 2.2 Your First Program in Java: Printing a Line of Text

Starting Out with Java: From Control Structures Through Objects Sixth Edition

Basic I/O - Stream. Java.io (stream based IO) Java.nio(Buffer and channel-based IO)

Computational Expression

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

Section 2: Introduction to Java. Historical note

Chapter 2: Data and Expressions

Chapter 10. File I/O. Copyright 2016 Pearson Inc. All rights reserved.

APPENDIX A: SUMMARY OF IMPORTANT JAVA FEATURES

Introduction to Java Applications

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

I/O in Java I/O streams vs. Reader/Writer. HW#3 due today Reading Assignment: Java tutorial on Basic I/O

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

File I/O Introduction to File I/O Text Files The File Class Binary Files 614

Data Conversion & Scanner Class

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Elementary Programming

Dining philosophers (cont)

Data Types and the while Statement

Basic Computation. Chapter 2

Getting started with Java

Objec&ves. Review. Standard Error Streams

CMSC131. Introduction to your Introduction to Java. Why Java?

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

CS Programming I: File Input / Output

Using APIs. Chapter 3. Outline Fields Overall Layout. Java By Abstraction Chapter 3. Field Summary static double PI

Objects and Classes 1: Encapsulation, Strings and Things CSC 121 Fall 2014 Howard Rosenthal

09-1. CSE 143 Java GREAT IDEAS IN COMPUTER SCIENCE. Overview. Data Representation. Representation of Primitive Java Types. Input and Output.

Chapter. Let's explore some other fundamental programming concepts

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. A Guide to this Instructor s Manual:

CS Programming I: File Input / Output

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

Chapter 2: Basic Elements of Java

Any serious Java programmers should use the APIs to develop Java programs Best practices of using APIs

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

Program Fundamentals

Java API: Math, Wrapper Classes, StringBuffer Random Data Quiz2

AP Computer Science A

Lecture 11.1 I/O Streams

CS 106 Introduction to Computer Science I

Chapter 2: Using Data

Input. Scanner keyboard = new Scanner(System.in); String name;

Lesson 02 Data Types and Statements. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Object-Oriented Programming

Hello World. n Variables store information. n You can think of them like boxes. n They hold values. n The value of a variable is its current contents

Experiment No: Group B_4

Contents Chapter 1 Introduction to Programming and the Java Language

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

Using Java Classes Fall 2018 Margaret Reid-Miller

Chapter 2 Primitive Data Types and Operations. Objectives

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes

Transcription:

Java Data types and input/output Sharma Chakravarthy Information Technology Laboratory (IT Lab) Computer Science and Engineering Department The University of Texas at Arlington, Arlington, TX 76019 Email: sharma@cse.uta.edu Course Url: https://wweb.uta.edu/faculty/sharmac/courses/coursepage.asp URL: http://itlab.uta.edu/sharma Project 1 I want to make sure you understand project 1 and are making progress Are you able to figure out the algorithms for the methods to be implemented! Any questions? Make sure you test the code thoroughly (both yours and what we have provided) Make sure the output is clear, easy to understand, and can be used to check for correctness This will help you get a firm grip over java basics 2 Primitive data types in Java Data type size range byte 1 byte -128 to +127 short 2 bytes -32768 to +32767 int 4 bytes single precision long 8 bytes double float 4 bytes single double 8 bytes double //is default in Java Java is a strongly typed language float real; real = 34.33 //error, all floating point literals are considered double; declare real as double Primitive data types (2) Data type size range boolean 1 byte true or false char 2 byte any char (uses unicode) These data types are called primitive because you cannot create objects of this type. Objects have attributes and methods. With primitive data types, you can only create variables and a variable can hold a single value. Note that strings are not primitive in Java Implemented as a class (i.e., is an object) All floating point computations follow the IEEE 754 specification 1

Java Classes for primitive types Java does not allow you to store primitive types in some objects (e.g., ArrayList) Hence, if you want to store numbers, they have to be objects Java provides an object equivalent for all primitive types These are objects and hence can be stored in other objects The following object classes are provided by Java Integer //to store an integer Long Double Float Char Boolean See more on boxing and auto boxing Java Data Types There are 3 special floating point values to denote overflows and errors Positive infinity (Double.POSITIVE_INFINITY) Negative infinity (Double.NEGATIVE_INFINITY) NaN (not a number) (Double.NaN) If (x == NaN) // is never true All NaN values are considered distinct Use (Double.isNaN(x) //check whether x is NaN 5 6 Java Big Numbers If the precision of basic integer and floating point is not sufficient, there are classes in the java.math.package to help you BigInteger and BigDecimal classes manipulate numbers with arbitrarily long sequence of digits As they are not primitive types, you cannot use + and. Need to use methods of the class for manipulation BigInteger bi, ci = BigInteger.valueOf(200); BigInteger di = bi.add(ci); Notes on C and C++ In C and C++, int denotes an integer type that depends on the target machine 2 bytes on 16 bit processors and 4 bytes on 32 bit processors In Java, the size of all numeric types are platform independent Java has tried its best to be platform and OS independent! Look up javadoc BigInteger for more information 7 8 2

Basic Input/output in Java Input and outputs in Java are considered streams System.in is the object used for console input Need to import some classes (e.g., Scanner) Create an object of that class Use methods of that class to perform input/output Once you have the input, you can perform error checks 9 More about input/output We have seen how to output strings and numbers using Syste.out.println, print, and printf methods In Java, every class is expected to have a method to convert its attributes into a printable ascii form (tostring() method) The equivalent of this method is supplied by Java for primitive type and some non primitive types (e.g., String) So, you can write System.out.printf("%5d%10s", i, ", "); to output an integer i using a format However, doing input is a little more involved as you need to create objects that accept input from the keyboard (remember you can also read from a file which we will do later) 10 Input Create an object of type Scanner using Scanner input = new Scanner(System.in); Note that you have to add import java.util.scanner //at the top of the file Code fragment for accepting input and error checking // prompt for input, read, and validate do { System.out.print( "Enter lower number >= " + lowestvalue + ": "); lownum = input.nextint(); if (lownum < lowestvalue) System.out.println("input value: " + lownum + " is less than " + lowestvalue); } while (lownum < lowestvalue); Enter lower number >= 10: 19 //is ok Enter lower number >= 10: 5 //is not ok; will ask again 11 3

What happens if you type 45.23 instead of 45? or Type hello instead of 45? An InputMismatchException occurs when Scanner method nextint receives a String that does not represent a valid integer. More on input/output We will be using nextint() and oters for project 2 Similarly, there are methods of Scanner class for next() // returns next token as a String nextdouble() nextboolean() nextfloat() nextchar() nextlong() hasnext() // returns boolean hasnextline() //returns whether there is a line //terminator in the input nextline() More about input/output (2) Be careful when using the method nextline() Note that when you perform an enter from the keyboard, a newline char is inserted into the buffer nextint() and all other nextxyz() methods are designed to skip the nextline character that is sitting in the buffer. However, the nextline() method reads the nextline char and takes it as input! You will have to use an extra nextline() call to skip over the newline character sitting in the buffer! See page 80 in the text book (8 th ed) 4

Reading from a file Many a times, it is easier to read from a file rather than command prompt Avoids typing while debugging, and mistakes Create a FileReader object Use that to create a BufferedReader Object import java.io.*; FileReader freader = new FileReader( customers.txt ); BufferedReader inputfile = new BufferedReader(freader); can use inputfile.readline() to read a line of input (not including the newline character) into a String if the value of the string read is null, then it is end of file can use inputfile.close() for closing the file throws IOException Reading data from a file Some methods of BufferedReader class int read() //reads a single character and returns its Unicode value Int read(char[] array) //returns number of characters int read(char[] array, int offset, int length) // stores from offset, length chars String readline() close() long skip(long n) //skip n characters in the stream 18 Writing to a file Many a times, it is easier to write to a file rather than command prompt (or both) Allows checking results easily (if long) Create a FileStream object (using FileWriter class) Use that to create a PrintWriter Object Allows print, println, and printf methods import java.io.*; FileStream fstream = new FileWriter( customers.txt ); PrintWriter outputfile = new PrintWriter(fstream); can use outputfile.println( joe ) to write an arbitrary string outputfile.println(82) outputfile.print(name + + idnumber) can use outputfile.close() for closing the file throws IOException Importing classes import declaration Helps the compiler locate a class that is used in this program. Rich set of predefined classes that you can reuse rather than reinventing the wheel. Classes are grouped into packages named groups of related classes and are collectively referred to as the Java class library, or the Java Application Programming Interface (Java API). You use import declarations to identify the predefined classes used in a Java program. 5

System is a class. Importing classes Part of package java.lang. Class System is not imported with an import declaration at the beginning of the program. By defauly, Java,lang is automatically imported into every java program. Usually, when your program accepts an input from command prompt, it is customary to prompt with appropriate details Packages Packages Set of predefined classes in Java Related classes are grouped into packages Group of all packages known as Java class library or Java applications programming interface (Java API) JOptionPane is in the javax.swing package This package has classes for using Graphical User Interfaces (GUIs) Packages are declared at the beginning of the file package edu.uta.carddeck; 2.7 Arithmetic (Cont.) Rules of operator precedence Multiplication, division and remainder operations are applied first. If an expression contains several such operations, they are applied from left to right. Multiplication, division and remainder operators have the same level of precedence. Addition and subtraction operations are applied next. If an expression contains several such operations, the operators are applied from left to right. Addition and subtraction operators have the same level of precedence. When we say that operators are applied from left to right, we are referring to their associativity. Some operators associate from right to left. Complete precedence chart is included in Appendix A. 6

2.8 Decision Making: Equality and Relational Operators Condition An expression that can be true or false. if selection statement Allows a program to make a decision based on a condition s value. Equality operators (== and!=) Relational operators (>, <, >= and <=) Both equality operators have the same level of precedence, which is lower than that of the relational operators. The equality operators associate from left to right. The relational operators all have the same level of precedence and also associate from left to right. Thank You! 28 7