import java.util.Scanner; public class Ch4 { public void workWithStrings() { // concatenation: String name = "Dave"; String msg = "Hello, " + name; String a = "Agent"; int n = 7; String bond = a + n; // convert a String to an integer: String num = "3"; int num2 = Integer.parseInt(num); //convert a String to a double: String num5 = "3.14159"; double num6 = Double.parseDouble(num5); // convert an int to a String: int num3 = 3; String num4 = String.valueOf(num3); // substrings name = "Aanya Tripathi"; // gets characters from position 0 to 5: String name2 = name.substring(0,6); System.out.println("name2: " + name2); // another substring example: // gets characters from position 6 // to the end of the String: String name3 = name.substring(6); System.out.println("name3: " + name3); } public void readInput() { // uses Scanner class Scanner in = new Scanner(System.in); System.out.print("Integer: >"); int a2 = in.nextInt(); System.out.print("Double: >"); double b2 = in.nextDouble(); System.out.print("Enter state code: >"); String state = in.next(); } public void doMath() { // use parentheses when needed: int a = 7; int b = 9; int avg = (a + b) / 2; int items = 5; // increment: items++; // decrement: items--; // integer division // the result of dividing 2 int's is an int int x = 7/5; System.out.println("result: " + x); double y = 7./5; System.out.println("result: " + y); // modular division (keep the remainder) int z = 7 % 5; System.out.println("result: " + z); // square root: double bb = Math.sqrt(100); System.out.println("result: " + bb); // raising a number to a power: double cc = Math.pow(4, 3); int ee = (int) cc; System.out.println("result: " + ee); System.out.println("result: " + cc); // floor and ceil: double dd = 3.9; System.out.println("result: " + Math.floor(dd)); System.out.println("result: " + Math.ceil(dd)); double zz = 3.5; // can't assign a double to an int: // int yy = zz; // one possibility, use an int cast: int yy = (int)zz; System.out.println("yy: " + yy); // or round to a "long": long xx = Math.round(zz); System.out.println("xx: " + xx); // integer division: int pp = 5/2; System.out.println("pp: " + pp); // avoiding integer division: double rr = 5./2; System.out.println("rr: " + rr); rr = (double)5/2; System.out.println("rr: " + rr); } public static void main(String[] args) { // numbers have ranges in which they're valid int n = 1000000; //System.out.println(n * n); // roundoff error can occur with doubles double f = 4.35; //System.out.println(f * 100); // declaring constants final int DAYS_IN_WEEK = 7; // error: //DAYS_IN_WEEK = 8; //System.out.println("DAYS_IN_WEEK: " + DAYS_IN_WEEK); //System.out.println("Java's value for Pi: (a constant) " + Math.PI); Ch4 c = new Ch4(); //c.doMath(); //c.workWithStrings(); c.readInput(); } }