M1.1 - Review v1
M1.1 - Review v1
Review of 1301/1321
Common data types
• byte, short, int, long, double, float, char,
• C#: bool, string / String
• Java: boolean, String
To declare a variable
<type> <name>;
Example:
int myNum;
ReadLine() returns a string, so if you want to get something else from the user
(and int for example), you have to convert it.
This takes in input from the user (as a string) and then passes this string to the
Parse method of the Int32 class; this Parse method returns an int, so this is a
valid assignment since now the left and the right side of the assignment (=)
operator are of the same type.
Recall that with using scanner, if you mix the use of nextLine() and
nextInt(), etc., you may have to flush the stream.
Java Converting type
• When you read from the console, typically you’ll use:
String word=scan.nextLine();
int num=Integer.parseInt(word);
double num=Double.parseDouble(word);
• Or perhaps…
word.toChar()
Boolean.parseBoolean(word)
Data validity
• You should generally assume the user is going to give
you bad input.
• If you prompt them for a number, what if they enter a
character, string or nothing at all?
• You should think about this while writing code, and
begin to code around it.
• Later in the class we’ll explain how exception handling
works, but for now you can use if statements.
C# User interaction
You should generally add the {}s. It makes your code more clear.
Declaring Methods
You declare a method in Java and C# using the following pattern:
int sum = 0;
for (int i=0; i < 100; i += 2)
{
sum+= i;
}
PRINT ("The sum is "+sum);
do while loop
do {
<body/work>
} while (<conditional>);
int i = 10;
int total=0;
do {
total+=i;
i--;
} while (i > 0);
PRINT("Total" + total);
while loop
while (<conditional>)
{
<body/work>
}
int i = 0;
while (i != 0)
{
i -= 1;
}
PRINT("the result is "+i);
Method examples - A menu – Java/C#
void PrintMenu() {
PRINT("1. Display result");
PRINT("2. Add a number");
PRINT("3. Delete a number");
PRINT("4. QUIT");
}
Method examples 2 choice – Java and C#
int GetChoice() {
int choice;
do {
PRINT("Enter your choice (1-4) : ");
choice = READ();
} while ((choice < 1) || (choice > 4));
return choice;
}
Array Of Integers
int[] myIntArray;
myIntArray = new int[10];
or
or
foreach(Trophy t in data_storage)
{ do something as long as it doesn't add or
remove members of the array
}
Traversing an array – Java