import java.util.Scanner;import java.util.Scanner;
import java.text.DecimalFormat;

// Simple string program in Java

public class SimpleString {

    public static void main(String[] args) {

        // Keyboard input example
        String string1;
        Scanner keyboard = new Scanner(System.in);
        System.out.print("String: ");
        string1 = keyboard.nextLine();
        System.out.println(string1);
        System.out.print("Double: ");
        double x = keyboard.nextDouble();
        
        //Formatting example
        DecimalFormat  fmt = new DecimalFormat( "#.##" );
        System.out.println (fmt.format(x) + "\n");
        
        // Using String methods: charAt, indexOf, length, substring
        String string2 = "Here is a test string";
        System.out.println(string2.charAt(2));       // prints "r"
        System.out.println(string2.indexOf("s"));    // prints 6
        System.out.println(string2.indexOf("x"));    // prints -1
        System.out.println(string2.length());        // prints 21
        System.out.println(string2.substring(8,14)); // prints "a test"
        
        // String concatenation
        String string3 = "Here is a ";
        String string4 = "test string";
        String string5 = string3.concat(string4);
        System.out.println ("\n" + string5);
        
        // Example to show you must use .equals with Strings (not ==)
        if (string2 == string5)
            System.out.println  ("== worked");
        else
            System.out.println ("== did not work");
        if (string2.equals(string5))
            System.out.println (".equals worked");
        else
            System.out.println (".equals did not work");
    }
}

© 2012 CS160 Colorado State University. All Rights Reserved.