Sie sind auf Seite 1von 19

class EscapeSequences

MELJU
{
public static void main(String[] args)
{
String demo = "Here are two tabs:\t\tAnd this is a newline:\n";
demo += "And two more tabs:\t\tAnd some more words.";
System.out.println(demo);

demo = "\nI put \"double quotes\" in double quotes,";


System.out.println(demo);

demo = "I put \'single quotes\' in single quotes";


System.out.println(demo);

demo = "If you want to use a backslash (\\) you must put two,\n";
demo += "to escape the second one";
System.out.println(demo);

demo = "\nUnicode 68 is \u0068, which is a fun way to put\n";


demo += "characters in your code.";
System.out.println(demo);

}
}

OUTPUT:

class StringExamine
{
public static void main(String[] args)
{
String declaration =
"We hold these truths to be self-evident that all men are created equal.";

System.out.println("Examining the string:\n" + declaration);

// use length to find the number of characters


System.out.println("\nThere are " + declaration.length() +
" characters in the string. Here is every other character...");
MELJU
// use length to iterate the string, display every other
for ( int index = 0; index < declaration.length(); index += 2 )
{
// use charAt to display the character at the index
System.out.print(declaration.charAt(index));
}
System.out.println("");
}
}

OUTPUT:

class StringExamine2
{
public static void main(String[] args)
{
String declaration =
"We hold these truths to be self-evident that all men are created
equal.";

System.out.println("Examining the string:\n" + declaration);

// find the first o


int position = declaration.indexOf("o");
System.out.println("the first o is at position: " + position);
// find the next o
position = declaration.indexOf("o", position + 1);
System.out.println("the next o is at position: " + position);
// find every e
position = declaration.indexOf("e");
while ( position > -1 )
{
System.out.println("There is an e at position: " + position);
position = declaration.indexOf("e", position + 1);
}
}
}
MELJU
OUTPUT:

class StringExamine3
{
public static void main(String[] args)
{
String declaration =
"We hold these truths to be self-evident that all men are created
equal.";

System.out.println("Examining the string:\n" + declaration);

int position = declaration.indexOf("th");


while ( position > -1 )
{
System.out.println(
"There is an example of th at position: " + position);
position = declaration.indexOf("th", position + 1);
}
}
}
OUTPUT:
MELJU
class StringExamine4
{
public static void main(String[] args)
{
String declaration =
"We hold these truths to be self-evident that all men are created
equal.";

System.out.println("Examining the string:\n" + declaration);

int position = declaration.lastIndexOf("l");


System.out.println("The last position of the letter l is: " + position);
}
}

OUTPUT:

class Substring
{
public static void main(String[] args)
{
String declaration =
"We hold these truths to be self-evident that all men are created
equal.";

int position = declaration.indexOf("be "); // find the word be

// get substring starting with be


String restOfString = declaration.substring(position);
System.out.println("Here is the end of the string...");
System.out.println(restOfString);
// get fifteen characters starting with be
restOfString = declaration.substring(position, position + 15);
System.out.println("Here is the middle of the string...");
System.out.println(restOfString);
}
}
**********************************************************
MELJU
OUTPUT:

class CompareStrings
{
public static void main(String[] args)
{
String stringA =
"We hold these truths to be self-evident that all men are created equal";

String stringB = "We hold no truth to be self-evident";


String stringC = "We hold no truth to be SELF-EVIDENT";

// display the strings


System.out.println("stringA:");
System.out.println(stringA);
System.out.println("\nstringB:");
System.out.println(stringB);
System.out.println("\nstringC:");
System.out.println(stringC);

// test for equality


System.out.println("\nstringA == stringB: " + stringA.equals(stringB));
System.out.println("stringB == stringC: " + stringB.equals(stringC));
System.out.println("stringB == stringC ignore case: " +
stringB.equalsIgnoreCase(stringC));

// test for ends with or begins with


System.out.println("\nstringA ends with equality: " +
stringA.endsWith("equality"));

System.out.println("stringA ends with equal: " +


stringA.endsWith("equal"));

System.out.println("\nstringA starts with Wehold: " +


stringA.startsWith("Wehold"));

System.out.println("stringA starts with We hold: " +


stringA.startsWith("We hold"));

}
}

MELJU
OUTPUT:
class StringBufferDemo
{
public static void main(String[] args)
{
StringBuffer mutableString = new StringBuffer("We hold these truths ");
System.out.println(mutableString);

System.out.println("The fifth character is " + mutableString.charAt(4));

System.out.println("\nSetting the fifth character to x ...");


mutableString.setCharAt(4,'x');
System.out.println(mutableString);

System.out.println("\nAdding a phrase to the string...");


mutableString.append("to be self-evident...");
System.out.println(mutableString);

System.out.println("\nInserting characters...");
mutableString.insert(21, "not ");
System.out.println(mutableString);

System.out.println("\nDeleting...");
mutableString.delete(21,25);
System.out.println(mutableString);

System.out.println("\nReplacing...");
mutableString.replace(3,7,"hold");
System.out.println(mutableString);

MELJU
System.out.println("\nTruncating...");
mutableString.setLength(21);
System.out.println(mutableString);

System.out.println("\nReversing...");
mutableString.reverse();
System.out.println(mutableString);

System.out.println("\nCreating a String...");
mutableString.reverse(); // back to normal
String fixedString = mutableString.toString();
System.out.println(mutableString);
System.out.println(fixedString);

}
}

OUTPUT:

MELJU
import java.io.*;
import java.util.*;

class LineCount
{

public void run()


{
int lineCount = 0;
try
{
InputStreamReader isr = new InputStreamReader(System.in);

// a BufferedReader has a readLine method that returns null at EOF


BufferedReader reader = new BufferedReader(isr);

String line = null;

// do this once for each line in the file


while ( (line = reader.readLine()) != null )
{
lineCount++;
}
}
catch (IOException e)
{
System.err.println("IOException caught!");
}

System.out.println("Line Count = " + lineCount);

public static void main(String[] args)


{
LineCount lc = new LineCount();
lc.run();
}
}

OUTPUT:

MELJU
import java.io.*;
import java.util.*;

class FileCopy
{

public void run(String inFileName, String outFileName)


{
int lineCount = 0;
try
{

// open a stream on a file (bytes)


FileInputStream inFile = new FileInputStream(inFileName);

// character based reading


InputStreamReader isr = new InputStreamReader(inFile);

// read a line at a time


BufferedReader reader = new BufferedReader(isr);

// write out to the file


FileWriter outFile = new FileWriter(outFileName);

String line = null;

// do this once for each line in the file


while ( (line = reader.readLine()) != null )
{
lineCount++;

// Write the line to the output file


outFile.write(line + "\n");
}

// close the output file object


outFile.close();

}
catch (IOException e)
{
System.err.println("IOException caught!");
}

System.out.println("Copied " + lineCount


+ " lines from " + inFileName +
" to " + outFileName);

MELJU
public static void main(String[] args)
{

String inputFileName = "";


String outputFileName = "";

// if the user does not supply both an input and an output file name
if ( args.length < 2 )
{
// if no filename was given, complain
// System.out.println("Usage: FileCopy inFileName outFileName");
// System.exit(1);

// Why grouse? Just ask for the file names...


try
{

InputStreamReader isr = new InputStreamReader(System.in);


BufferedReader reader = new BufferedReader(isr);

// neither was supplied, ask for the input first


if ( args.length < 1 )
{
System.out.print("Please provide an input file name: ");
inputFileName = reader.readLine();
}

// ask for the output file name


System.out.print("Please provide an output file name: ");
outputFileName = reader.readLine();
}

catch (IOException e)
{
System.out.println("Could not read.");
return;
}

}
else // the names were supplied on the command line
{
inputFileName = args[0];
outputFileName = args[1];
}

// instantiate FileCopy and pass in the file names


FileCopy fc = new FileCopy();
fc.run(inputFileName, outputFileName);
}
}

MELJU
OUTPUT:
import java.io.*;
import java.util.*;

class FileCopyWithWordCount
{
public void run(String inFileName, String outFileName)
{
int lineCount = 0;
int wordCount = 0;
try
{
FileInputStream inFile = new FileInputStream(inFileName);

InputStreamReader isr = new InputStreamReader(inFile);

BufferedReader reader = new BufferedReader(isr);

FileWriter outFile = new FileWriter(outFileName);

String line = null;

while ( (line = reader.readLine()) != null )


{
lineCount++;

// create a StringTokenizer to read the line


StringTokenizer st = new StringTokenizer(line);

// iterate through the line, counting words


while ( st.hasMoreTokens() )
{
++wordCount;
st.nextToken();
}

outFile.write(line + "\n");
}

MELJU
outFile.close();
}
catch (IOException e)
{
System.err.println("IOException caught!");
}
System.out.println("Copied " + lineCount
+ " lines (" + wordCount + " words) from " + inFileName +
" to " + outFileName);
}
public static void main(String[] args)
{
String inputFileName = "";
String outputFileName = "";

if ( args.length < 2 )
{
try
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(isr);

if ( args.length < 1 )
{
System.out.print("Please provide an input file name: ");
inputFileName = reader.readLine();
}
else { inputFileName = args[0]; }

System.out.print("Please provide an output file name: ");


outputFileName = reader.readLine();
}
catch (IOException e)
{
System.out.println("Could not read.");
return;
}
}
else // the names were supplied on the command line
{
inputFileName = args[0];
outputFileName = args[1];
}
FileCopyWithWordCount fc = new FileCopyWithWordCount();
fc.run(inputFileName, outputFileName);
}
}

MELJU
OUTPUT:

import java.io.*;
import java.util.*;

class WordCounter
{
public static void wordCount(String inFileName, String outFileName)
{
int wordcount = 0;
TreeSet uniqueWords = new TreeSet();

System.out.print(inFileName + ": ");


try
{
FileInputStream inFile = new FileInputStream(inFileName);

// a BufferedReader has a readLine method that returns null at EOF


BufferedReader reader = new BufferedReader(new
InputStreamReader(inFile));
// We use a StreamTokenizer to
// chop the line up into words and ignore anything that is not
// made up of characters or digits.
StreamTokenizer st = new StreamTokenizer(reader);
st.resetSyntax();
st.wordChars('a', 'z');
st.wordChars('A', 'Z');
st.wordChars('0', '9');

int token;
while ( (token = st.nextToken()) != StreamTokenizer.TT_EOF )
{
if ( token == StreamTokenizer.TT_WORD )
{
++wordcount;
uniqueWords.add(st.sval);
}
}
inFile.close();
}

MELJU
catch (IOException e)
{
System.out.println("Could not read.");
return;
}

// display the number of unque words


System.out.println("word count = " + wordcount + ", unique = " +
uniqueWords.size());

// write all the unique words to a file


try
{
FileWriter outFile = new FileWriter(outFileName);

// iterate over the set, writing each word to the output file
for ( Iterator it = uniqueWords.iterator(); it.hasNext(); )
{
outFile.write(it.next() + "\n"); // write one word per line
}
outFile.close();

}
catch (IOException e)
{
System.out.println("Could not write to '" + outFileName + "'.");
return;
}
}

public static void main(String[] args)


{
String inputFileName = "";
String outputFileName = "";

// if the user does not supply both an input and an output file name
if ( args.length < 2 )
{
try
{

InputStreamReader isr = new InputStreamReader(System.in);


BufferedReader reader = new BufferedReader(isr);

// neither was supplied, ask for the input first


if ( args.length < 1 )
{
System.out.print("Please provide an input file name: ");
inputFileName = reader.readLine();
}

MELJU
// ask for the output file name
System.out.print("Please provide an output file name: ");
outputFileName = reader.readLine();
}

catch (IOException e)
{
System.out.println("Could not read.");
return;
}

}
else // the names were supplied on the command line
{
inputFileName = args[0];
outputFileName = args[1];
}

wordCount(inputFileName, outputFileName);
}
}

OUTPUT:

MELJU
*********************************************************************
import javax.swing.JOptionPane;

class Factorial
{
private int doFactorial(int N)
{
int result;
if ( N == 0 )
{
result = 1;
}
else
{
result = N * doFactorial(N - 1);
}

System.out.println(N + "!) = " + result);


return result;
}

public void run()


{
int nValue;

for ( ;; )
{
String userChoice =
JOptionPane.showInputDialog("What value? (-1 to quit)");
nValue = Integer.parseInt(userChoice);

if ( nValue == -1 )
{
break;
}

int result = doFactorial(nValue);


System.out.println(nValue + "! = " + result);

} // end for

System.exit(0);
} // end run

public static void main(String[] args)


{
Factorial f = new Factorial();
f.run();
}
}

MELJU
OUTPUT:
MELJU
import java.lang.*;
import java.util.*;

class Hanoi
{

static int nRings = 3;

public static void main(String[] args)


{

if ( args.length > 0 )
{
nRings = Integer.parseInt(args[0]);
}
Hanoi h = new Hanoi();
h.run();
}

public void run()


{
System.out.println("Tower of Hanoi");

// start with nRings


moveNRings(nRings, 0, 1, 2);
}

// display the move as an instruction


private void moveOneRing(int sourceTower, int destTower)
{
System.out.println("Move from " + sourceTower + " to " + destTower);
}

private void moveNRings(


int n, int sourceTower, int destTower, int storageTower)
{
// if only one ring, move it
if ( n == 1 )
{
moveOneRing(sourceTower, destTower);
}
else // otherwise move others out of the way
{
moveNRings(n - 1, sourceTower, storageTower, destTower);
moveOneRing(sourceTower, destTower);
moveNRings (n - 1, storageTower, destTower, sourceTower);
}
}
}

MELJU
OUTPUT: