Download Week7

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Introduction to Programming w/ Java – Week 7
Week 7 Agenda:
Importing other packages and using their pre-defined classes.
Getting user input!
Converting Strings to Integers
Today we will learn how to interact with users – asking them for input and then using that input.
First we will click on File and choose New Project and Java Application.
For our project name we will type “Week7”, and we will allow Java to create a Main method for us.
Feel free to delete all the standard comments that come up, and then type the program that follows.
But first, notice that this program takes advantage of a pre-defined class named “Scanner” that is contained
in a package “java.util” (i.e. the java utilities package). There are many standard pre-written classes which
you, as a programmer, can access. In order to not overload a system’s memory, and to make your programs
load in a timely manner (i.e. not take too long), many of these standard packages can be imported if (and
only if) you need to use them.
Example: We could import this entire package by using the statement import java.util*, but that would
make our program take longer to load and run (and take up more memory). So we’ll just import the actual
class that we need – “import java.util.Scanner”.
Step 1 -Getting user input:
----------------package week7;
import java.util.Scanner;
public class Week7 {
public static void main(String[] args) {
Scanner readInput;
readInput = new Scanner(System.in);
String firstName;
System.out.println("Enter your first name please.");
firstName = readInput.next();
System.out.println("Your first name is "+firstName+".\n");
}
}
-----------------------As you can see, this program instantiates an object named “readInput” which is an object of the class
“Scanner”. When using the Scanner class, we need to tell it where to look for the input, and this is done by
using the “System.in” command when instantiating “readInput”. Next we create a String named
“firstName”. Finally, we ask the user for the input, save it, and then display it back.
Next, try asking the user for their first and last name and displaying both back, as below:
----------------package week7;
import java.util.Scanner;
public class Week7 {
public static void main(String[] args) {
Scanner readInput;
readInput = new Scanner(System.in);
String firstName, lastName;
System.out.println("Enter your first name please.");
firstName = readInput.next();
System.out.println("Enter your last name please.");
lastName = readInput.next();
System.out.println("Your full name is Bubba.");
System.out.println("Just kidding, your full name is "+firstName+" "+lastName+".\n");
}
}
-----------------------Step 2 – Let’s make a simple game!
In this lesson, we will learn about converting String input to integers to be used for calculations
Here the user types input (which is a String), and then we convert it to an integer – a variable type on which
we can perform mathematical operations (addition, subtraction, comparison, etc.)
This program imports three predefined classes:
- java.util.Scanner – we know about this one from above
- java.util.Random – this one allows us to generate a random integer. Note that the integer will be between
0 and max, where max is the number of integers to pick from. So, if max is 10, then Java selects at random
between 0 and 9. If max is 16, then Java selects between 0 and 15.
- java.lang.Integer - the “Integer” class which allows us to use the parseInt method, which takes a String
and picks out the integer. So we can type in “9”, but we could not type in “nine”. Does that make sense?
Before we jump in and program the entire game, I would always suggest you start small, and make good
use of comments to outline the flow of your program. Planning a program is the hard part, typing in the
code is the easy part. So I’d suggest you start like this:
----------------------public class GuessNumber {
public static void main(String args[]) {
//Define some variables – the total number of guesses and the user’s guess
//Generate a Random integer
//While the User’s guess does not equal the Random Integer, do the following LOOP:
//Get the User’s guess
//Compare the users’s guess to the Random integer, display the results (i.e. too high, too low, or correct)
//increment the total guess counter
//Congratulate the user, show the total number of guesses
}
--------------------Once we have this mapped out, we can start coding. As always, we suggest you code one section at a time,
then compile and test, then continue on…. This leads to many fewer errors and much less frustration!
Here is the final program…..
----------------package week7;
import java.util.Scanner;
import java.lang.Integer;
import java.util.Random;
public class GuessNumber {
public static int getUserGuess() {
String userInput;
System.out.println("What number am I thinking of? (It is between 1 and 10)");
Scanner readText = new Scanner(System.in);
userInput = readText.next();
return Integer.parseInt(userInput);
}
public static void compareAndDisplay (int userGuess, int randomInt) {
if (userGuess < randomInt) {
System.out.println("Too low, try again.");
} else if (userGuess > randomInt) {
System.out.println("Too high, try again.");
} else {
System.out.println("Perfect!");
}
}
public static void main(String[] args) {
//Pick a random number between 1 and 10
int randomInt;
Random randomGenerator = new Random();
randomInt = randomGenerator.nextInt(10) + 1;
//while User Guess != random number let them keep guessing
int userGuess = -1;
int numberGuesses = 0;
while (userGuess != randomInt) {
userGuess = getUserGuess();
compareAndDisplay(userGuess, randomInt);
numberGuesses++;
}
System.out.println("Congratulations - you guess correctly in "+numberGuesses+" guesses.");
}
}
-----------------------Step 3 – Challenge
Now try getting user input for your own interest – feel free to ask anything, save it, and then display it
back! Alternatively, try remaking the Celcius to Farenheit converter, this time asking the user for the input.
Here is a sample – remember to comment out all main methods in the same package except the one you
want to run…
----------------------------package week7;
import java.util.Scanner;
import java.lang.Integer;
public class celciusConverter {
public static void main(String[] args) {
String tempCelciusString;
int tempCelcius;
double tempFarenheit;
Scanner readText;
readText = new Scanner(System.in);
System.out.println("Enter the temperature in Celcius: ");
tempCelciusString = readText.next();
System.out.println("You entered a Celcius temperature of "+tempCelciusString+".");
System.out.println("I will now convert this String to an integer.");
tempCelcius = Integer.parseInt(tempCelciusString);
System.out.println("The Celcius temperature is "+tempCelcius+ "C.");
System.out.println("I will now convert the Celcius Temperature to Farenheit.");
tempFarenheit = 1.8*(tempCelcius)+32.0;
System.out.println("The Farenheit temperature is "+tempFarenheit+ "F.");
}
}