Студопедия
Случайная страница | ТОМ-1 | ТОМ-2 | ТОМ-3
АрхитектураБиологияГеографияДругоеИностранные языки
ИнформатикаИсторияКультураЛитератураМатематика
МедицинаМеханикаОбразованиеОхрана трудаПедагогика
ПолитикаПравоПрограммированиеПсихологияРелигия
СоциологияСпортСтроительствоФизикаФилософия
ФинансыХимияЭкологияЭкономикаЭлектроника

Useful examples

Fundamentals of programming II | Write down and run this program on your computer | Write down and run this program on your computer | Introduction to objects | The first program | Types. Primitive types. | Types of variables. Declarations. | More on operators and expressions | Numeric promotions | Objects and references |


Читайте также:
  1. A useful skill for IELTS speaking AND writing
  2. ABBREVIATIONS USED IN INDEX TO THE ILLUSTRATIVE EXAMPLES
  3. Advertisers perform a useful service to the community
  4. And some useful expressions
  5. C Here are some useful nouns.
  6. Chapter 3. Examples of Materials Covered in the Course
  7. Chapter 7. Examples of the Unconscious in Modern Psychology


The following instruction:

String s = JOptionPane.showInputDialog("Message");

shows a dialog box with the message "Message" requesting input from the user. After clicking the "OK" button the entered text is stored in the variable s. By closing the dialog box (or by clicking the "Cancel" button) the null value is returned.

The instruction:

JOptionPane.showMessageDialog(null, "Message");

brings up an information-message dialog titled "Message".

To use these dialogs the statement import javax.swing.JOptionPane; must be put in the first line of a program.


Dialogs enable interaction with a user. The next program shows how to do it.

import javax.swing.JOptionPane; public class GreetMsg { public static void main(String[] args) { String name = JOptionPane.showInputDialog("Give your name"); if (name == null) name = ""; JOptionPane.showMessageDialog(null, "Hello " + name + "!"); System.exit(0); } }

It shows an input dialog requesting input from the user. If we cancel the dialog without giving a name, the result of the method invocation JOptionPane.showInputDialog(...) stored in the variable name will be null. In such cases we assign to it a reference to an empty string ("").


The next call JOptionPane.showMessageDialog(..) shows a message dialog with the given name.

 

Second example concatenates a number of strings given by a user in a dialog box. Then it displays all of them (one per single line) in a message dialog.
Closing the dialog box terminates gathering of input data (strings) from the user. The program does not accept an empty string. Clicking the "OK" button with no string given as input results in displaying the message dialog with request for correct input (or for canceling the operation by clicking "Cancel"). The figure shows the result of running the program with names of some animals given as input.

import javax.swing.JOptionPane; public class ShowStrings { public static void main(String[] args) { String out = ""; String inp = null; while ((inp = JOptionPane.showInputDialog("Type in something"))!= null) { if (inp.equals("")) JOptionPane.showMessageDialog(null, "Input some text or close the dialog"); else out = out + '\n' + inp; } if (out.equals("")) out = "No text was given"; JOptionPane.showMessageDialog(null, out); System.exit(0); } }

Note that:


Both programs use invocation of System.exit(0) which terminates the execution of the program.

Usually a program terminates after all instructions in the method main have been executed. However, it is not true for programs with graphical user interfaces (more on this later). The dialog boxes are elements of the graphical user interface, so programs using them require explicit termination with call to System.exit(...).


How can a user introduce numbers into a program (using dialogs)?
If we write a number in a text field of a dialog it is treated as text and in this form it is available in the program. Of course, we cannot carry out arithmetical operations on strings representing numbers. We must convert them to the form in which numbers are represented in the computer.

A string representing a number may be converted to a number with the following method invocation:

aNumber = Integer.parseInt(aString);

where:
aNumber - a variable of the type int
aString - an expression of type String

 


As an example, consider the following program which adds two numbers given by the user:

import javax.swing.*; public class ParseInt { public static void main(String[] args) { String s1 = JOptionPane.showInputDialog("Give the first number"); String s2 = null; if (s1!= null) { s2 = JOptionPane.showInputDialog("Give the second number"); if (s2!= null) { int l1 = Integer.parseInt(s1); int l2 = Integer.parseInt(s2); JOptionPane.showMessageDialog(null, "Sum: " + (l1 + l2)); } } System.exit(1); } }


Run this program with various input strings. Try out strings which do not represent numbers (or even an empty string).

Summary

The lecture has presented:

Detailed treatment of the notion of reference is very important for understanding Java programs.
Although we do not know yet how to create classes, we know how to use objects.
In particular we can operate on strings (creating them, concatenate them, appending data of other types). We know how to prepare interactive (to some degree) programs too: programs which ask user for some data and display results of calculations using dialogs.

Exercises

  1. Write a program calculating a computer price. Use dialogs to gather information about prices of components.
  2. Write a program converting temperatures: Fahrenheit -> Celsius using dialogs.
  3. Similarly improve the "shopping" program from the previous lecture.

 


Lecture 7

Classes I

This lecture introduces classes. It is a fundamental concept for object-oriented programming. A class defines properties of objects; it is a kind of template used for creating objects.

7.1. What are classes used for?

In object-oriented programming we use objects.
As we already know (see 4.2), objects are characterized by:

Objects in a program reflect real world objects which might be concrete (physically existing) or abstract.

For example, in a program simulating motor traffic we should represent cars.
A car (as an object in our program) has some properties (attributes):

It can satisfy certain requests too:

Two cars can be represented by two objects in the program, each specified by values of its properties.

Car A (denoted by carA in the program) Car B (denoted by carB in the program)
weight = 1000 height = 1.5 current velocity = 0 weight = 1000 height = 1.5 current velocity = 60

 

Messages are sent to objects using the dot operator.

Each of them understands the following messages:

carA.start();

carB.stop();

How do we know what attributes cars-objects have? How do we know what messages they understand?

All these are specified in the definition of the class of cars. Our program must supply it or import it from somewhere.

A class is a description of invariable properties of a group of similar objects.

So we may write symbolically:

Class Car

attributes:

weight
height
current velocity

requests (operations, messages):

start
stop
increase_velocity
turn_left

 

Now we know what properties characterize an object-car and how it can be used in our program.


Thus,

the definition of a class specifies:

 

 

In most object-oriented languages (including Java):

Therefore, a class definition supplies the definitions of:

A class is a template describing creation of objects (constructors), their attributes (fields) and the manner of communicating with objects (methods).

 


In java the keyword class is used to define classes. The definition is placed between the braces that follow it. The code that defines it is called class body.


[ public ] class AClassName {

// field definitions
// constructor definitions
// method definitions
}

where:

 

Examples of class definitions:

public class Pair { // definition of the class representing pairs of integers

// class body

}

public class Car {
// class body
}


class TestPair {
// class body
}

Fields and methods of a class are called members.

Members of a class = fields + methods

 


Дата добавления: 2015-11-16; просмотров: 81 | Нарушение авторских прав


<== предыдущая страница | следующая страница ==>
The class String| Defining attributes of objects

mybiblioteka.su - 2015-2024 год. (0.011 сек.)