MELJUN CORTES's - Java List of Source Code Application (FOURTH HAND-OUTS)

Embed Size (px)

Citation preview

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (FOURTH HAND-OUTS)

    1/19

    MELJclass EscapeSequences{ 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...");

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (FOURTH HAND-OUTS)

    2/19

    MELJ// use length to iterate the string, display every otherfor ( int index = 0; index < declaration.length(); index += 2 ){ // use charAt to display the character at the indexSystem.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);

    }

    }

    }

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (FOURTH HAND-OUTS)

    3/19

    MELJOUTPUT:

    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:

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (FOURTH HAND-OUTS)

    4/19

    MELJclass 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);

    }

    }**********************************************************

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (FOURTH HAND-OUTS)

    5/19

    MELJ

    MELJ

    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"));

    }

    }

    OUTPUT:

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (FOURTH HAND-OUTS)

    6/19

    MELJ

    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);

    System.out.println("\nTruncating...");

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (FOURTH HAND-OUTS)

    7/19

    MELJ

    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:

    import java.io.*;

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (FOURTH HAND-OUTS)

    8/19

    MELJ

    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 filewhile ( (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:

    import java.io.*;

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (FOURTH HAND-OUTS)

    9/19

    MELJ

    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 timeBufferedReader 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);

    }

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (FOURTH HAND-OUTS)

    10/19

    MELJ

    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);

    }

    }

    OUTPUT:

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (FOURTH HAND-OUTS)

    11/19

    MELJ

    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");

    }

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (FOURTH HAND-OUTS)

    12/19

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (FOURTH HAND-OUTS)

    13/19

    MELJ

    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();

    }

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (FOURTH HAND-OUTS)

    14/19

    MELJ

    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();

    }

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (FOURTH HAND-OUTS)

    15/19

    MELJ

    // 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:

    *********************************************************************

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (FOURTH HAND-OUTS)

    16/19

    MELJ

    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();

    }

    }

    OUTPUT:

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (FOURTH HAND-OUTS)

    17/19

    MELJimport java.lang.*;

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (FOURTH HAND-OUTS)

    18/19

    MELJ

    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);

    }

    }

    }

    OUTPUT:

  • 8/9/2019 MELJUN CORTES's - Java List of Source Code Application (FOURTH HAND-OUTS)

    19/19