|
Learn to Program JAVA. Learn the Basics.
by: Rodelio P. Barcenas
This program is supposed to display
the characters of string "Jack Frost". Each character
of the word will be displayed every line. The variable "name"
is an object and ".charAt(x) is a method of the object. ".charAt(x)"
returns the character pointed by the value of x. Create a file
named "getchars.java" and encode the lines below.
public class
getchars {
public
static void main(String arg[]) {
String
name; // contains the string value
name = "Jack Frost";
//
string "Jack Frost" was assigned
int
lname = name.length();
// get the length of string
char c;
for(int
x=0;x<lname;x=x+1) { // start of loop
c = name.charAt(x);
// get the char pointed by x
System.out.println(c);
//
display char w/ line-feed
} // end for loop
} // end main
} //
end class getchars
The next program
will display the characters of the name "Jack Frost"
backwards starting with "t" going to "J".
Each character is displayed in every line The variable "name"
is an object and ".charAt(x) is a method of the object. ".charAt(x)"
returns the character pointed by the value of x.
public class
reverse {
public
static void main(String arg[]) {
String
name; // contains the string value
name = "Jack Frost";
int
lname = name.length(); // get the length
of string
char c;
for(int
x=lname-1; x>=0; x--) { // start of loop
c = name.charAt(x);
// get character pointed by x
System.out.println(c);
// display char w/ linefeed
} // end for loop
}
// end main
}//
end class reverse
This program
is written to produce a pattern below
if n = 3;
XXX
X
XXX
if n = 4;
XXXX
X
X
XXXX
Solution;
by looking at the pattern, you can see that
a row is printed multiple X during n = 1 and
n = maximum.
else just simply
print a single X
public class
pattern2 {
public
static void main(String arg[]) {
int
n;
n=10;
for(int
cnt = 1; cnt <=n; cnt = cnt +1) {
if (cnt==1 || cnt ==n)
{ // if n = 1 or max
for(int
x=1; x<=n; x=x+1){
// then print multiple X
System.out.print("X");
}
System.out.println();
// print a line feed
}
else
System.out.println("X"); // else
just print X
}
// end for loop
}
// end void main
} //
end class
This program is written to provide an output pattern
if limit = 4;
1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7
if limit = 5;
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9
public class pattern1 {
public
static void main(String arg[]) {
int row,col,limit;
limit = 5;
for(row=1;row<=limit;row=row+1)
{
for(col=row;col<=limit+row-1;col=col+1)
{
System.out.print(col+"
");
}
System.out.println();
}
}
// end void main
} //
end class
|