Java Programing
Download
Report
Transcript Java Programing
Java Programing
PSC 120
Jeff Schank
Let’s Create a Java Program
1.
2.
3.
4.
Open Eclipse
Create a project: File -> New -> Java Project
Create a package: File -> New -> Package
Create a Class: File -> New -> Class
package talker;
public class Talkers {
public static void main(String[] args) {
}
}
}
How to say “Hello World!”
package talker;
public class Talkers {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
}
Let’s Add Some Numbers
package talker;
public class Talkers {
public static void main(String[] args) {
System.out.println(23 + 149 + 50291);
}
}
}
Let’s Format the Results
package talker;
public class Talkers {
public static void main(String[] args) {
System.out.println("23 + 149 + 50291 = " + (23 + 149 + 50291));
}
}
}
Classes
• Let’s create another class called “Agent”
• File -> New -> Class
package talker;
public class Agent {
}
Data
• Now, let’s add some data—in this case a
vocabulary
public class Agent {
public String[] vocabulary = new String[] {
"I'm fine!",
"I wish I had a different name.",
"I'm hungry",
"I ate too much pizza.",
"I think, therefore I exist.",
"I'm fine but i'll be better when class is over!"
};
}
Methods
• Now, let’s add a method
public class Agent {
public String[] vocabulary = new String[] {
"I'm fine!",
"I wish I had a different name.",
"I'm hungry",
"I ate too much pizza.",
"I think, therefore I exist.",
"I'm fine but i'll be better when class is over!"
};
public void saySomething(int x){
int size = vocabulary.length;
if(x>=0 && x < size){
System.out.println(vocabulary[x]);
}
else{
System.out.println("I'm not that smart!");
}
}
}
Let’s Say Something
package talkers;
public class Talkers {
public static void main(String[] args) {
Agent a = new Agent();
String s = a.saySomething(1);
System.out.println(s);
}
}
Let’s Say Something Randomly
package talkers;
public class Agent {
public String[] vocabulary = new String[]
{"I'm fine!",
"I wish I had a different name.",
"I'm hungry",
"I ate too much pizza.",
"I think, therefore I exist.",
"I'm fine but i'll be better when class is over!"
};
public String saySomething(int x){
if(x < vocabulary.length && x >= 0)
return vocabulary[x];
else
return "My vocabulary is small!";
}
public String saySomethingRandomly(){
int lengthOfVocabulary = vocabulary.length;
int randomInt = (int)(Math.random()*(double)lengthOfVocabulary);
return vocabulary[randomInt];
}
}
Variables and Their Types
• As we just saw, we define the objects that will interact in our
simulation by defining classes
• Once a class is completely defined, then it can be instantiated many
times
– For example, we could define a class called “Person” and then make
1000 persons that interact in our simulation.
• Classes have members that occupy fields in a class
• A class can have indefinitely many fields and a field is either
occupied by variables or methods
• When defining classes, I prefer to place the variables first and
methods second in a class, but Java does not care how they are
ordered
• Let’s look at some of the types of variables we can define in a class.
Example MyClass
package talkers;
public class MyClass {
int n; //a declared integer
int m = 1; //a declared integer with a value assigned to it
double x; //declared a double variable, for storing real numbers
double pi = Math.PI; //a double variable pi, with an approximation of
//pi assigned to it, 3.141592654
boolean b; //declaration of a boolean variable
boolean xyz = true; //declaration of a boolean variable assigned the value true
boolean there_is_a_Martian_in_this_room = false;
//it is often a good idea to make variable names that
//have meaning to you.
String s; //declaration of a string variable
String myName = "Jeff Schank"; //declaration of a string variable and
//assignment of a string.
//We can also define array variables that can contain values for the type of
//array.
int[] integerArray; //declaration of an integer array variable
int[] myNumbers = new int[100]; //declaration of an integer array with
//100 slots for integers. But, no integers have been specified for the array
int[] one_to_ten = {1,2,3,4,5,6,7,8,9,10}; // declaration of an integer array,
//creation of an array with 10 slots, with values 1 to 10 assigned to the slots.
}
Access Modifiers
• Variables (and methods) have specifications for
how they are accessed
• There are four types of access modifiers: no
explicit modifier, public, private, and protected.
– public modifier—the field is accessible from all
classes.
– private modifier—the field is accessible only within its
own class.
– protected modifier—the field is accessible within its
own class, package, and subclass.
– no explicit modifier—the field is accessible within its
own class and package
Methods
• Methods specify how objects do things (how they behave)
• Methods also specify how objects interact with other objects
• Methods have at least five features:
1.
2.
3.
4.
5.
Modifiers—such as public, private, and others listed above.
The return type—the data type of the value returned by the
method, or void if the method does not return a value.
The method name—the rules for field names apply to method
names as well, but the convention is a little different.
The parameter list in parenthesis—a comma-delimited list of input
parameters, preceded by their data types, enclosed by parentheses,
(). If there are no parameters, you must use empty parentheses.
The method body, enclosed between braces—the method’s code,
including the declaration of local variables, goes here.
Example Method
1.
Modifier
2. Return
Type
3. Method
Name
4. Parameter
List
5. Body
Example Method
1.
Modifier
2. Return
Type
3. Method
Name
4. Parameter
List
5. Body
Example Method
1.
Modifier
2. Return
Type
3. Method
Name
4. Parameter
List
5. Body
Logical Operators
1.
2.
3.
4.
5.
6.
7.
8.
9.
&&
||
==
!
!=
>
>=
<
<=
means roughly “and”
means roughly “or”
means roughly “equals”
means roughly “not”
means roughly “not equal to”
means “greater than”
means “greater than or equal to”
means "less than”
means "less than or equal to"
&& and ||
! and !=
Arithmetic Operators
1. +
2. –
3. *
4. /
Additive operator but it is also used for
String concatenation.
Subtraction operator
Multiplication operator
Division operator
Examples: +
If-then Statement
Conditions
Body
If-then Example
For Statements
• Probably, the next most commonly used control
statement is the for statement.
• For control statements are one of several control
statements that allow you to perform a number
of operations over and over again for a specified
number of steps (the others are while and dowhile).
• For statements typically have three statements as
arguments and then a body that is repeated
(there are variations on this theme).
A common form
Modifier
Arguments
Body
Example
Another Example
The maximum value for an integer is 2147483647
But, since it does not stop at this value, it would
generate an error.
Switch Statement
Scope of a Variable
• The scope of a variable is the region of a
program within which, a variable can be
referenced.
• In Java, the largest scope a variable can have is
at the level of the class.
• So, if variables are declared in a class field,
they can be referenced anywhere in the class
including inside methods.
Examples
Examples
pa c k a ge t al ker s;
publ i c c l a s s MyCl ass {
s t a t i c i nt x = 72;
publ i c s t a t i c v oi d myMet hod( i nt x) {
f or ( x = 0; x < 5; x++) {
Syst em. out . pr i nt l n( x) ;
}
}
publ i c s t a t i c v oi d mai n( St r i ng[ ] ar gs) {
myMet hod( 10) ;
Syst em. out . pr i nt l n( x ) ;
}
}
/ / What i s t he val ue pr i nt ed by myMet hod( 10) ?
/ / What i s t he val ue pr i nt ed by
Syst em. out . pr i nt l n( x) ?
This
publ i c c l a s s MyCl ass {
i nt x = 72;
publ i c v oi d myMet hod( i nt x) {
f or ( x = 0; x < 5; x++) {
t hi s . x ++;
x ++;
}
Syst em. out . pr i nt l n( x) ;
Syst em. out . pr i nt l n( t hi s . x ) ;
}
}
/ / What i s t he val ue pr i nt ed by myMet hod( 10) ?
/ / What i s t he val ue pr i nt ed by Syst em. out . pr i nt l n( t hi s. x) ?
Returning to Talkers
public static Agent[] population;
public static void makeAgents(int number){
population =new Agent[number];
for(int i = 0; i<number;i++){
population[i]=new Agent(i,population);
}
}
Adding to the Agent Class
public String name;
public Agent[] population;
public Agent(int number, Agent[] population){ //Constructor for Agent
name = "Agent"+number;
this.population = population;
}
Adding to the Agent Class
public void askAgent(){
int n = population.length;
int i = (int)(Math.random()*n);
Agent a = population[i];
System.out.println("\nBEGIN CONVERSATION");
System.out.println("What is your name? I'm "+ getName()+".");
System.out.println("My name is "+ a.getName());
System.out.println("How are you doing, "+ a.getName() + "?");
saySomethingRandom();
System.out.println("END CONVERSATION\n ");
}
Back to Talkers
public static void main(String[] args) {
int n = 100;
int steps = 10;
makeAgents(n);
for(int i=0;i<steps;i++){
Agent a = population[(int)(Math.random()*100)];
a.askAgent();
}
}