Java 211 – Lecture 3
Java 211
Strings, Reading Input, Else-If
Yosef Mendelsohn
I. Strings
The String data type is not one of the so-called “primitive” data types (e.g. int, char, double, etc) that we have been discussing over the last couple of lectures. Rather, they are what we call objects, a fact that will become increasingly relevant as you learn more about Java. For now, we will begin with some String fundamentals and then learn more about them as we learn about objects.
The best way to describe a string is to give some examples:
String s1 = "hello";
//a string of length=5
String s2 = "hello, Bob.. How are you? ";
String s3 = "h";
//a string of length=1
String s4 = "123456";
//a string of digits – it is NOT a number)
Notice that the data type String begins an upper case ‘S’.
However:
char c1 = 'h';
if (c1 == s3) //error!!! – type mismatch
int x = s4; //error – type mismatch
Some commonly used methods that can be invoked by a string object include:
- equals (returns a bool)
- length (returns an int)
- toLowerCase (returns a String)
The idea of an object invoking its own method may confuse you. We will return to this topic down the road. For now, we will concern ourselves with simply USING these methods. I will explain the reasoning behind them as we progress.
Important point #1: To compare two strings to determine if they are holding identical values, you can NOT use the == operator. The == operator works ONLY for primitive data types (eg to compare two variables of, say, type int or double). Recall that strings are not primitive data types. When comparing to objects, the == operator will give unexpected results. So we need another way to compare two strings. Here is the an example of some code to compare two strings:
String s1 = "hello";
String s2 = "goodbye";
To compare these two strings to see if they are identical, we would write:
if ( s1.equals(s2) )
{
System.out.println("The strings are identical");
}
Another example:
if ( s1.equals("hello") )
{
System.out.println("The string s1 holds the word hello. ");
}
This ‘equals’ method is very important. Be sure that you are comfortable with its usage.
If you wish to compare two Strings without regard for case, you can use the method
equalsIgnoreCase()
For example:
String word = "hElLo"
if ( word.equalsIgnoreCase("hello") )
{
System.out.println("The strings are identical.");
}
Another very useful String method is called length() . Here it is in use:
String s1 = "hello";
int length = s1.length();
System.out.println("The length of the string is: "
+ length );
Another example:
if ( s1.length() > 10 )
{
System.out.println("The string s1 is longer than 10
characters. ");
}
Notice the need for a pair of parentheses after the word length().
There are numerous other methods available to String objects that we will discuss in class. I will also show you how to look up others on your own.
Concatenation
We have seen the ‘+’ operator used to add two numbers together. However, this operator does something completely different when applied to Strings. It concatenates two or more strings together. That is, it takes two Strings and joins them to make a longer String. In fact, you can join as many strings as you like together using this operator.
This is why you can have two strings inside a println statement. By concatenating them together, they will be represented as a single string. The second string is appended on to the end of the first string.
- Also, strings can be concatenated with numbers
- If the two operators on both sides of a + are numbes, then addition is performed. Otherwise, concatenation is performed. You can also control behavior by using brackets.
Here are a couple of examples of concatenation in action. You will find yourself concatenating strings often, and in many different ways.
String s1, s2, s3;
s1 = "Hello";
s2 = "How are you?"
s3 = s1 + s2;
//what is wrong with the resulting output???
//Better:
s3 = s1 + ". " + s2;
As with numeric variables, a string can be ‘added’ (i.e. concatenated) to itself:
String s = "hello";
s = s+s;
//what is the current value of s?
Escape Sequences
Sometimes we want to output special characters such as quotation marks or \ signs or newlines, etc. in our strings. Because these characters can interfere with our source code, we need a way of indicating to the compiler that these are special characters and must not be treated in their usual way. The technique is to precede these characters by a ‘\’ character. A partial list of escape sequences can be found in an appendix or by googling.
Examples include:
• \n newline
• \t tab
• \’ single quote
• \" double quote
For example:
System.out.println("How are you?\nIam fine.");
//on two lines
System.out.println("How are you?\tIam fine.");
//tab in between
//putting several together:
System.out.println("Bob said \"How y\'all doin\'\"");
Since we have established that Strings are objects of a class called ‘String’, lets take a quick look at some of the methods of that class by checking out the String API. (Yet again, to be discussed later…)
II. The Scanner class
As mentioned in lecture, one of the great advantages of a powerful and widely used programming language such as Java is the possibility to extend the language to add features. One glaring hole in earlier versions of Java (prior to SDK v.14) was an easy way to read input from the user. Fortunately, this has been remedied by a new library that includes a class called ‘Scanner’.
Again, because we do not understand classes and objects very well (or at all!) yet, for now you will have to simply get comfortable with the code as I demonstrate it to you. Again, as we progress, some of the things that may seem mysterious now will become clear.
Here is an example of some code to take input in from the user via the keyboard:
Scanner console = new Scanner(System.in);
//this line is required to use the Scanner class
//it should be placed near the top of your method
int age;
double gpa;
String firstName;
System.out.println("How old are you?");
age = console.nextInt();
System.out.println("What is your GPA?");
gpa = console.nextDouble();
System.out.println("What is your name?");
firstName = console.next();
Notice how the method attached to the word ‘input’ changes depending on the type of data we want to read. For example, if you are expecting the user to enter a double, you should use nextDouble() . If you are expecting an int: nextInt(). A String: next() not ‘nextString() .
What would happen with the following:
System.out.println("How many miles did you run?");
miles = console.next();
Answer: The method ‘next()’ returns a String. If you put a string into a variable of type double you have a type mismatch.
One note: The word ‘console’ is simply an identifier. You could choose any identifier that you like such as:
Scanner keyboardInput = new Scanner(System.in);
However, the book uses ‘console’, so I’ll use it here as well.
As with Strings, the Scanner class is another class that we will be using throughout the course, so you should become familiar with it now.
There is one thing that you need to do to use the Scanner class: you need to “import” the package that holds it. We’ll talk more about this later, but for the moment, whenever you want to use the Scanner class, include the following line at the very top of your program (even before the class declaration):
import java.util.Scanner;
Here is a link to the complete program using the code we’ve just discussed.
III. if-else
Last lecture we talked about ‘if’ statements. If you have a lone ‘if’ statement, the program’s flow begins by evaluating the conditional. If the conditional evaluates to ‘true’, flow enters the body of the ‘if’ block. If the conditional evalutes to ‘false’, flow simply skips the ‘if’ block by jumping ahead to the closing brace ‘}’ .
However, there may be situations where you want to have your program do something even when the conditional is false. The easiest way to demonstrate this is by an (admittedly frivolous) example:
System.out.println("What is your GPA?");
gpa = console.nextDouble();
if ( gpa > 3.5 )
{
System.out.println("You're a good student!");
}
else
{
System.out.println("Better work harder!");
}
In other words, if the conditional turns out to be false, flow will jump directly to the ‘else’ block and execute it. If the conditional is true, flow will execute the ‘if’ block, and will then skip the ‘else’ block by jumping to its closing brace.
‘Else’ statements are optional. Whether or not you include one really depends on the logic of your program. Most of the time you will have no problem deciding whether or not your code needs to have an ‘else’ block.
If and else-if statements:
There will also be situations where you want your code to evaluate several different possibilities. Again, this is best explained by an example. Let’s write some code that prompts the user for their percentage score for the course. The code will then determine the appropriate letter grade.
int percentGrade;
System.out.println("What was your % for the course?");
percentGrade = console.nextInt();
if ( percentGrade >= 90 )
{
System.out.println("You receive an A.");
}
else if ( percentGrade >= 80 )
{
System.out.println("You receive a B.");
}
else if ( percentGrade >= 70 )
{
System.out.println("You receive a C. ");
}
else if ( percentGrade >= 60 )
{
System.out.println("You receive a D.");
}
else //user’s score is less than 60
{
System.out.println("You receive an F.");
}
The moment flow finds a conditional that is true, it will execute the corresponding block. It will then skip all the way to the end of the if / else-if statements – regardless of how many of them are present.
A common mistake: Many beginniners tend to write ‘if else’ instead of ‘else if’. The proper syntax is: else if ( conditional ) …
One other thing:
Notice how the last ‘else’ does not have to be an ‘else if’. The reason is that if flow makes it that far in the if / else-if statements, then the user MUST have scored less than 60. It would certainly be possible to write:
else if ( percentGrade < 90 )
for the last situation, but it isn’t necessary. Either version is fine.
What do you think? (An argument could be made that having a final else if is preferable since it makes the code a bit more clear).
................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related download
- computer science ii
- colorado state university
- internet programming with java course
- android part 1 java language topics
- james gosling s java
- rochester city school district
- computer science department index page
- 1 what is the output produced by the following line of code
- arrays ecology lab
- second java program
Related searches
- marketing management pdf lecture notes
- strategic management lecture notes pdf
- strategic management lecture notes
- philosophy 101 lecture notes
- philosophy lecture notes
- philosophy of education lecture notes
- financial management lecture notes
- financial management lecture notes pdf
- java plugin java 1 6 0 29 download
- 211 angel numbers
- 211 cmr 133
- ratio tables 211 lesson 3