Introduction to Strings and Reading Input in Java
Learn about strings in Java, including creating, concatenating, and extracting parts of strings. Also, explore reading input from the keyboard using the Scanner class.
Introduction to Strings and Reading Input in Java
E N D
Presentation Transcript
Week 6 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham
Week 6 Topics 6.1.1 Strings 6.1.2 Reading Input
6.1.1 Strings • A string is a series of characters such as “Hello, World!” • Strings are delimited by (enclosed within) quotation marks • Creating a string object does not require the new operator: String msg = “Hello, World!”; • The length of the example string above is 13 and can be determined via a call to the length method: System.out.println(msg.length());
6.1.1 Strings • The + operator is used to concatenate strings (put them together): String a = “Agent”; int n = 7; String bond = a + n; • Note that the integer value n is converted to a string • Use concatenation to simplify expressions: System.out.println(“Total is ” + total);
6.1.1 Strings • If a string contains digits of a number, you can use the Integer.parseInt or the Double.parseDouble method to obtain the number value • int count = Integer.parseInt(input); • double price = Double.parseDouble(input);
6.1.1 Strings • Use the substring method to extract a part of a string: s.substring(start, pastEnd) • You specify the position you want to start at, and the position one past the position you want to end at • String msg = “Hello, World!”; • String sub = msg.substring(0, 5); • // sub is “Hello”
6.1.1 Strings • String msg = “Hello, World!”; • String sub = msg.substring(7, 12); • // sub is “World” • String sub = msg.substring(7); // World! • Above copies from start pos to end
6.1.2 Reading Input • In Java version 5.0, a Scanner class was added that lets you read keyboard input in a convenient manner • To construct a Scanner object, simply pass the System.in object to the Scanner constructor: Scanner in = new Scanner(System.in); • Once you have a scanner, use nextInt or nextDouble method to read a whole number or a floating point number.
6.1.2 Reading Input • Scanner in = new Scanner(System.in); • System.out.print(“Enter Quantity: ”); • int quantity = in.nextInt(); • System.out.print(“Enter Price: ”); • double price = in.nextDouble();
6.1.2 Reading Input • nextLine() gets all text including spaces, next() gets a word (token) as soon as it comes to a white space (space, end of line, tab) • System.out.print(“Enter City: ”); • String city = in.nextLine(); • System.out.print(“Enter state code: ”); • String state = in.next();
Reference: Big Java 2nd Edition by Cay Horstmann 6.1.1 Strings (section 4.6 in Big Java) 6.1.2 Reading Input (section 4.7 in Big Java)