Download Lecture 7

Document related concepts
no text concepts found
Transcript
String Class
• String Class in package java.lang
• String is a class not a primitive data type
• String constants can be created using a traditional
shorthand notation
– String str = “This is my string”
• An empty string is not the same as an uninitialised
string
– String str;
– String str=“”;
// uninitialised  = null
// empty
String Class
• Strings unlike other objects have an operator
defined for them: + for string concatenation
– str = str1 + str2 + “another string”;
• String concatenation
– Using the + operator with two Strings concatenates
them into a new String
– Using the + operator with a String and a value of
another data type concatenates the String with a
String representation of the other value
• When the other value is an object, its toString method is
called to generate its String representation
String Class
• Strings unlike other objects have an operator defined
for them: + for string concatenation
– str = str1 + str2 + “another string”;
• Once created the contents of a String cannot be
changed
– to alter the contents of strings use another class
StringBuffer
• String class has a comprehensive list of constructors
and methods available
Concat and +
concat() - Concatenates the specified string to the end of this
string.
If the length of the argument string is 0, then this String object
is returned.
Otherwise, a new String object is created, containing the
invoking string with the contents of the str appended to it.
public String concat(String str)
"to".concat("get").concat("her") returns "together"
Note
• The following program uses the following
toUpperCase method
String Operations
• toLowerCase(): Converts all of the characters in a String to
lower case.
• toUpperCase(): Converts all of the characters in this String to
upper case.
public String toLowerCase()
public String toUpperCase()
Eg: “HELLO THERE”.toLowerCase();
“hello there”.toUpperCase();
Uppercase Program
• import javax.swing.JOptionPane;
• import java.lang.*;
• public class Capstring1 {
•
public static void main(String args []){
•
String firststr1,s2;
•
firststr1 = JOptionPane.showInputDialog("Enter
String");
•
•
s2 = firststr1.toUpperCase();
JOptionPane.showMessageDialog(null,
"Result is "+ s2,"outcome",
JOptionPane.PLAIN_MESSAGE);
}}
Example Input
Example Output
Notes
• In this program we could not change
• The string firststr1
• In order to effect the change to all Capital
letters we had to use another string variable
s2.
Strings
• Java string is a sequence of characters. They are objects of
type String.
• Once a String object is created it cannot be changed. Stings
are Immutable.
• To get changeable strings use the class called StringBuffer.
• String and StringBuffer classes are declared final, so there
cannot be subclasses of these classes.
• The default constructor creates an empty string.
String s = new String();
Creating Strings
• String str = "abc"; is equivalent to:
char data[] = {'a', 'b', 'c'};
String str = new String(data);
• If data array in the above example is modified after the string
object str is created, then str remains unchanged.
• Construct a string object by passing another string object.
String str2 = new String(str);
String Class
• The String class example of some of the methods
– General – length(),
• charAt(), getchars()
– Comparing Strings –
• compareTo() startsWith(), endsWith()
– Locating Characters
• indexOf(), lastIndexOf()
– Extracting substrings
• subString()
String Operations
• The length() method returns the length of the string.
Eg: System.out.println(“Hello”.length()); // prints 5
• The + operator is used to concatenate two or more strings.
Eg: String myname = “Harry”
String str = “My name is” + myname+ “.”;
• For string concatenation the Java compiler converts an
operand to a String whenever the other operand of the + is a
String object.
Example
import javax.swing.JOptionPane;
import java.lang.*;
public class Lengthstring1 {
public static void main(String args []){
String firststr1,s2;
firststr1 = JOptionPane.showInputDialog("Enter String");
int l = firststr1.length
//StringBuffer sb = new StringBuffer(firstnum1);
//sb = sb.reverse();
JOptionPane.showMessageDialog(null, "Length is "+ l ,"outcome",
JOptionPane.PLAIN_MESSAGE);
}}
Notes
• The variable l is an integer but the expression
• “length is” + l is a string and is output as:
• For example if input is Manchester United
Exercises
• 1: Enter 2 strings and output the longest.
• 2: Print Out an error message if a string is
input which is longer than 15 characters.
String Operations
• equals() - Compares the invoking string to the specified object. The result
is true if and only if the argument is not null and is a String object that
represents the same sequence of characters as the invoking object.
public boolean equals(Object anObject)
• equalsIgnoreCase()- Compares this String to another String, ignoring case
considerations. Two strings are considered equal ignoring case if they are
of the same length, and corresponding characters in the two strings are
equal ignoring case.
public boolean equalsIgnoreCase(String
anotherString)
Exercise
• Write a program which asks the following
question and tests if the users answers is
correct or not.
• Question
• What is the Capital City of Ireland
• Answer
• Dublin
String Operations
• compareTo() - Compares two strings lexicographically.
– The result is a negative integer if this String object lexicographically
precedes the argument string.
– The result is a positive integer if this String object lexicographically
follows the argument string.
– The result is zero if the strings are equal.
– compareTo returns 0 exactly when the equals(Object) method would
return true.
public int compareTo(String anotherString)
public int compareToIgnoreCase(String str)
Example Program
import javax.swing.JOptionPane;
import java.lang.*;
public class Compstring1 {
public static void main(String args []){
String firststr1,s2;
firststr1 = JOptionPane.showInputDialog("Enter String");
s2 = JOptionPane.showInputDialog("Enter another String");
if (firststr1.compareTo(s2) < 0)
JOptionPane.showMessageDialog(null, firststr1 + "precedes "+
s2,"outcome", JOptionPane.PLAIN_MESSAGE);
else
JOptionPane.showMessageDialog(null, s2 + "precedes "+ firststr1,"outcome",
JOptionPane.PLAIN_MESSAGE);
}}
For inputs
• Cat
• Dog
• We get output:
String Operations
• replace()- Returns a new string resulting from replacing all
occurrences of oldChar in this string with newChar.
public String replace(char oldChar, char newChar)
"mesquite in your cellar".replace('e', 'o') returns
"mosquito in your collar"
Example with replace
import javax.swing.JOptionPane;
import java.lang.*;
public class Replacestring1 {
public static void main(String args []){
String firstnum1,s2;
firstnum1 = JOptionPane.showInputDialog("Enter String");
s2 = firstnum1.replace('a','o');
//StringBuffer sb = new StringBuffer(firstnum1);
//sb = sb.reverse();
JOptionPane.showMessageDialog(null, "Result is "+ s2,"outcome",
JOptionPane.PLAIN_MESSAGE);
}}
For Input “hat”
• We get output
Exercise
• Write a program to
• Replace all vowels in a word with *’s
Other string operations
• We will see some of these again when we look
at a changeable string class String Buffer
String Operations
indexOf – Searches for the first occurrence of a character or substring.
Returns -1 if the character does not occur.
public int indexOf(int ch)- Returns the index within this
string of the first occurrence of the specified character.
public int indexOf(String str) - Returns the index within
this string of the first occurrence of the specified substring.
String str = “How was your day today?”;
str.indexof(‘t’);
str(“was”);
String Operations
public int indexOf(int ch, int fromIndex)- Returns the
index within this string of the first occurrence of the specified character,
starting the search at the specified index.
public int indexOf(String str, int fromIndex) - Returns
the index within this string of the first occurrence of the specified
substring, starting at the specified index.
String str = “How was your day today?”;
str.indexof(‘a’, 6);
str(“was”, 2);
String Operations
lastIndexOf() –Searches for the last occurrence of a character or
substring. The methods are similar to indexOf().
substring() - Returns a new string that is a substring of this
string. The substring begins with the character at the specified
index and extends to the end of this string.
public String substring(int beginIndex)
Eg: "unhappy".substring(2) returns "happy"
String Operations
• public String
substring(int beginIndex,
int endIndex)
Eg: "smiles".substring(1, 5) returns
"mile“
String Operations
• Characters in a string can be extracted in a number of ways.
public char charAt(int index)
– Returns the character at the specified index. An index
ranges from 0 to length() - 1. The first character of the
sequence is at index 0, the next at index 1, and so on, as
for array indexing.
char ch;
ch = “abc”.charAt(1); // ch = “b”
String Operations
• trim() - Returns a copy of the string, with leading and trailing
whitespace omitted.
public String trim()
String s = “ Hi Mom!
S = “Hi Mom!”
“.trim();
• valueOf() – Returns the string representation of the char array
argument.
public static String valueOf(char[] data)
String Operations
• The contents of the character array are copied; subsequent
modification of the character array does not affect the newly
created string.
Other forms are:
public static
public static
public static
public static
public static
public static
String
String
String
String
String
String
valueOf(char c)
valueOf(boolean b)
valueOf(int i)
valueOf(long l)
valueOf(float f)
valueOf(double d)
String Operations
• getChars() - Copies characters from this string into the
destination character array.
public void getChars(int srcBegin, int srcEnd,
char[] dst, int dstBegin)
–
–
–
–
srcBegin - index of the first character in the string to copy.
srcEnd - index after the last character in the string to copy.
dst - the destination array.
dstBegin - the start offset in the destination array.
String Operations
• startsWith() – Tests if this string starts with the specified
prefix.
public boolean startsWith(String prefix)
“Figure”.startsWith(“Fig”); // true
• endsWith() - Tests if this string ends with the specified suffix.
public boolean endsWith(String suffix)
“Figure”.endsWith(“re”); // true
String Operations
• startsWith() -Tests if this string starts with the specified prefix
beginning at a specified index.
public boolean startsWith(String prefix,
int toffset)
prefix - the prefix.
toffset - where to begin looking in the
string.
“figure”.startsWith(“gure”, 2); // true
StringBuffer
• A StringBuffer is like a String, but can be modified.
• The length and content of the StringBuffer sequence can be
changed through certain method calls.
• StringBuffer defines three constructors:
– StringBuffer()
– StringBuffer(int size)
– StringBuffer(String str)
StringBuffer Class
• A StringBuffer is like a String but it can be modified
• The principle operations on a StringBuffer are
append() and insert()
String s = "a" + "b“ + 4 ;
System.out.println(s);
StringBuffer sb = new StringBuffer();
sb.append("a");
sb.append(4);
sb.insert(1,"b");
System.out.println (sb);
StringBuffer Operations
• The principal operations on a StringBuffer are the append and
insert methods, which are overloaded so as to accept data of
any type.
Here are few append methods:
StringBuffer append(String str)
StringBuffer append(int num)
• The append method always adds these characters at the end
of the buffer.
StringBuffer Operations
• The insert method adds the characters at a specified point.
Here are few insert methods:
StringBuffer insert(int index, String str)
StringBuffer append(int index, char ch)
Index specifies at which point the string will be inserted into the
invoking StringBuffer object.
Example program
• Note this uses the charAT method
String Operations
• Characters in a string can be extracted in a number of ways.
public char charAt(int index)
– Returns the character at the specified index. An index
ranges from 0 to length() - 1. The first character of the
sequence is at index 0, the next at index 1, and so on, as
for array indexing.
char ch;
ch = “abc”.charAt(1); // ch = “b”
This program take a string as input
• And duplicates every character in it
import javax.swing.JOptionPane;
import java.lang.*;
public class Changestring1 {
public static void main(String args []){
String firststr1;
firststr1 = JOptionPane.showInputDialog("Enter
String");
StringBuffer sb = new StringBuffer(firststr1);
int l = sb.length();
for (int i = 0; i < 2*l;i++) {
char k = sb.charAt(i);
sb = sb.insert(i,k);
i++;
}
JOptionPane.showMessageDialog(null, "Result is "+
sb,"outcome", JOptionPane.PLAIN_MESSAGE);
}}
Input
Output is
Notes about the program
• It passes the entered string into the String
Buffer constructor in order to get an
equivalent
• It retrieves each character using charAt
• It uses the insert method to insert in a copy of
that character
StringBuffer Operations
• replace() - Replaces the characters in a substring of this
StringBuffer with characters in the specified String.
public StringBuffer replace(int start, int end,
String str)
• substring() - Returns a new String that contains a
subsequence of characters currently contained in this
StringBuffer. The substring begins at the specified index and
extends to the end of the StringBuffer.
public String substring(int start)
StringBuffer Operations
• reverse() - The character sequence contained in this string
buffer is replaced by the reverse of the sequence.
public StringBuffer reverse()
• length() - Returns the length of this string buffer.
public int length()
StringBuffer Operations
• capacity() - Returns the current capacity of the String buffer.
The capacity is the amount of storage available for newly
inserted characters.
public int capacity()
•
charAt() - The specified character of the sequence currently
represented by the string buffer, as indicated by the index
argument, is returned.
public char charAt(int index)
StringBuffer Operations
• getChars() - Characters are copied from this string buffer into
the destination character array dst. The first character to be
copied is at index srcBegin; the last character to be copied is
at index srcEnd-1.
public void getChars(int srcBegin, int srcEnd,
char[] dst, int dstBegin)
•
setLength()
- Sets the length of the StringBuffer.
public void setLength(int newLength)
StringBuffer Operations
• delete() - Removes the characters in a substring of this
StringBuffer. The substring begins at the specified start and
extends to the character at index end - 1 or to the end of the
StringBuffer if no such character exists. If start is equal to end,
no changes are made.
public StringBuffer delete(int start, int end)
Examples: StringBuffer
StringBuffer sb = new StringBuffer(“Hello”);
sb.length(); // 5
sb.capacity(); // 21 (16 characters room is
added if no size is specified)
sb.charAt(1); // e
sb.setCharAt(1,’i’); // Hillo
sb.setLength(2); // Hi
sb.append(“l”).append(“l”); // Hill
sb.insert(0, “Big “); // Big Hill
Examples: StringBuffer
sb.replace(3, 11, “”); // Big
sb.reverse(); // gib
Example Program
•
•
•
•
•
•
Purpose accept as input a string of the form
Part1-part2
And to split it into two separate parts e.g.
“a-b”
First element is a
Second element is b
import javax.swing.JOptionPane;
import java.lang.*;
public class Parsestring1 {
public static void main(String args []){
String firstnum1;
firstnum1 = JOptionPane.showInputDialog("Enter Code");
StringBuffer sb = new StringBuffer(firstnum1);
int l = sb.length();
StringBuffer sb1 = new StringBuffer();
StringBuffer sb2 = new StringBuffer();
int k = sb.indexOf("-");
sb1 = sb1.append(sb.substring(0,k));
sb2 = sb2.append(sb.substring(k+1,l));
JOptionPane.showMessageDialog(null, "First part is "+
sb1,"outcome", JOptionPane.PLAIN_MESSAGE);
JOptionPane.showMessageDialog(null, "Second part is "+
sb2,"outcome", JOptionPane.PLAIN_MESSAGE);
}}
Input
Output1
Output 2
Exercise
• Write a program which accepts as input a
string of the form “3+5” and which calculates
the result
Exercises
• Show two ways to concatenate the following two strings
together to get the string "Hi, mom.": String hi = "Hi, "; String
mom = "mom.";
• Write a program that computes your initials from your full
name and displays them.
• An anagram is a word or a phrase made by transposing the
letters of another word or phrase; for example, "parliament"
is an anagram of "partial men," and "software" is an anagram
of "swear oft." Write a program that figures out whether one
string is an anagram of another string. The program should
ignore white space and punctuation.
• Exercise 1: Show two ways to concatenate the following two
strings together to get the string "Hi, mom.":
• String hi = "Hi, ";
• String mom = "mom.";
• Answer 1: hi.concat(mom) and hi + mom.
•
Exercise 2: Write a program that computes your
initials from your full name and displays them.
Answer 2: ComputeInitials
• public class ComputeInitials {
•
public static void main(String[] args) {
•
String myName = "Fred F. Flintstone";
•
StringBuffer myInitials = new
StringBuffer();
•
• int length = myName.length();
•
•
for (int i = 0; i < length; i++) {
if
(Character.isUpperCase(myName.charAt(i))) {
•
•
•
•
•
•
myInitials.append(myName.charAt(i));
}
}
System.out.println("My initials are: " +
myInitials);
}
}
A Quick Java
Swing Tutorial
72
Introduction
• Swing – A set of GUI classes
– Part of the Java's standard library
– Much better than the previous library: AWT
• Abstract Window Toolkit
• Highlights
– A rich set of widgets
• Widget: Any GUI element (also called: components)
– Contents and shape are separated (MVC support)
– Fine-grained control over the behavior and look and feel
– Platform independent
• Isolates the programmer from the operating system's GUI
73
Swing Components
• Containers
– Contain and manage other components.
– Top Level/Internal
– Examples: JFrame (Top Level), JScrollPane, JPanel.
• Basic controls
– Atomic components
– Used for showing ouput and/or getting some input
– Inherits JComponent
– Examples: JButton, JLabel, JTextArea, JTable,
Jlist
• Usually every Swing class extends the corresponding AWT class
– For backward-compatibility reasons
74
My First Swing Program
import javax.swing.*;
import java.awt.BorderLayout;
public class First {
public static void main(String[] args) {
JFrame frame = new JFrame("My First Frame");
// operation to do when the window is closed.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(new JLabel("I Love Swing"),
BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
75
Top Level Containers: JFrame
• javax.swing.JFrame:
– Top-level window with a title and a border.
– Usually used as a program's main window
76
More on JFrame
• Made of several layers
• Widgets are added to the Content Pane layer.
– Use getContentPane() to obtain it
• Other layers are used for customizing the window's
appearence
77
Top Level Containers: JDialog
• javax.swing.JDialog:
–
–
–
–
More simple and limited than frames
Typically used for showing a short message on the screen
Also has a border and a title bar
May have an owner
• If the owner is invisible the dialog will also be invisible
– Use the static method of JoptionPane to show standard dialog boxes:
JOptionPane.showMessageDialog(null, "4+2=6");
78
Internal Containers
• Not Top level containers
• Can contain other non-top level components
• Examples:
– JScrollPane: Provides a scrollable view of its
components
– JSplitPane: Separates two components
– JTabbedPane: User chooses which
component to see
79
Containers - Layout
• Each container has a layout manager
– Determines the size, location of contained widgets.
• Setting the current layout of a container:
void setLayout(LayoutManager lm)
• LayoutManager implementing
– BorderLayout
– BoxLayout
– FlowLayout
– GridLayout
80
classes:
Containers - Layout
81
Swing Components
82
Swing Components
83
First Swing Program Revisited
import javax.swing.*;
import java.awt.BorderLayout;
Create a frame
public class First {
public static void main(String[] args) {
JFrame frame = new JFrame("My First Frame");Choose the border
layout
// operation to do when the window is closed.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(new JLabel("I Love Swing"),
BorderLayout.CENTER);
frame.pack();
Create a text
frame.setVisible(true);
label
}
Add the label to
Specify
CENTER
}
the content pane
as the layout
position
84
Input
• So we now know how to present widgets on the screen
• A program also needs to react to the user's actions
• Examples:
– When the user presses a button we want to save a file
– When the user closes the program we want to ask “are you sure?”
– ...
• Swing mechanism: Events and Listeners
85
Events, Listeners
• Swing defines all sorts of Listener interfaces
– E.g.: ActionListener, MouseMotionListener,
WindowListener, ...
public interface ActionListener extends EventListener {
public void actionPerformed(ActionEvent e);
}
public interface MouseMotionListener extends EventListener {
public void mouseDragged(MouseEvent e);
public void mouseMoved(MouseEvent e);
}
• There are default (empty) implementations for many of the listeners
– E.g.: MouseMotionAdapter, WindowAdapter
86
Events, Listeners (cont.)
• A listener is an object that implements a listener interface
• If we need to react to an event (on a certain widget) we register a listener
object with that widget
• E.g.: addActionListener() registers an action listener with its receiver:
JButton button = new JButton();
ActionListener listener = ...;
button.addActionListener(listener);
• When an event occurs, all registered listeners are notified
– The appropriate listener method (e.g: actionPerformed()) is invoked
– An object describing the event is passed as a parameter
87
Event Handling Demo: GUI
88
Event Handling Demo: Code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Events implements ActionListener {
public Events() {
JFrame frame = new JFrame("Events");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new FlowLayout());
JButton b = new JButton("Click me!");
b.addActionListener(this);
frame.getContentPane().add(b);
frame.pack();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Thank you");
}
public static void main(String[] args) { new Events(); }
}
89
Example of using RadioButtons
• From Roseindia.net
•
•
•
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
•
•
public class SelectRadioButton{
JLabel label;
•
•
•
•
•
•
•
•
public SelectRadioButton(){
JFrame frame = new JFrame("Radio button selection");
JRadioButton first = new JRadioButton("First");
JRadioButton second = new JRadioButton("Second");
JRadioButton third = new JRadioButton("Third");
JRadioButton fourth = new JRadioButton("Fourth");
JRadioButton fifth = new JRadioButton("Fifth");
• JPanel panel = new JPanel();
•
panel.add(first);
•
panel.add(second);
•
panel.add(third);
•
panel.add(fourth);
•
panel.add(fifth);
•
ButtonGroup bg = new ButtonGroup();
•
bg.add(first);
•
bg.add(second);
•
bg.add(third);
•
bg.add(fourth);
•
bg.add(fifth);
•
•
•
•
•
•
•
•
•
•
•
•
•
first.addActionListener(new MyAction());
second.addActionListener(new MyAction());
third.addActionListener(new MyAction());
fourth.addActionListener(new MyAction());
fifth.addActionListener(new MyAction());
label = new JLabel("Roseindia.net");
frame.add(panel, BorderLayout.NORTH);
frame.add(label, BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
• public class MyAction implements ActionListener{
•
public void actionPerformed(ActionEvent e){
•
label.setText(e.getActionCommand());
•
JOptionPane.showMessageDialog(null,"This is the " +
e.getActionCommand() +
• " radio button.");
•
}
• }
• public static void main(String[] args){
•
SelectRadioButton sr = new SelectRadioButton();
• }
• }
Notes
• Label.SetText assigns text to the label.
• e.getActionCommand(); gets the
text(command) from the control
• label.setText(e.getActionCommand());
• Assigns the label text the value from
e.getActionCommand which is the text
associaited with the control.
Notes 2
• ActionListener etc are examples of Java
Interfaces
• These are class definitions with blank method
declarations.
• This allows the user to define their own
methods
• We will see these next week.