概述
2020.7.7
第一天,加拿大卡尔顿大学cs网课。
今天学:
- basic property
- input and output operations
- Create simple programs in Java using the imperative/procedural paradigm
notes from lecture 1
- understand the syntax is important
- 用编译语言Compiled language写成的程序,在运行期的运行速度,通常比用解释型语言写的程序快。因为程序在编译期,已经被预先编译成机器代码,可以直接运行,不用像解释型语言interpreted language一样,还要多一道直译程序。
- Java is a compiled language
- Every variable in Java has a defined type that cannot change
- Common Java Primitive Variable Types:boolean – true or false char – a single character int – an integer number float – a decimal number double – a more precise decimal number
- The definition of objects are specified in classes
- “void” is a special return type, representing no value
第一个程序:
Hello World //Class declaration
public class HelloWorld{ //MethodDeclaration
public static void main(String[] args){ //Method body
System.out.println("Hello World!");
} //everything you want to execut in the 'main' method
} //This template can be used to basic Java code – add
网上知识:
1.public static void main(String[] args) 是什么意思?
这是 Java 程序的入口地址,Java 虚拟机运行程序的时候首先找的就是 main 方法。跟 C 语言里面的 main() 函数的作用是一样的。只有有 main() 方法的 Java 程序才能够被 Java 虚拟机运行,可理解为规定的格式。
对于里面的参数及修饰符:
- public:表示的这个程序的访问权限,表示的是任何的场合可以被引用,这样 Java 虚拟机就可以找到 main() 方法,从而来运行 javac 程序。
- static: 表明方法是静态的,不依赖类的对象的,是属于类的,在类加载的时候 main() 方法也随着加载到内存中去。
- void:main():方法是不需要返回值的。
- main:约定俗成,规定的。
String[] args:从控制台接收参数。
2.Java User Input
The Scanner
class is used to get user input, and it is found in the java.util
package.
To use the Scanner
class, create an object of the class and use any of the available methods found in the Scanner
class documentation. In our example, we will use the nextLine()
method, which is used to read Strings:
Java Scanner 类
java.util.Scanner 是 Java5 的新特征,我们可以通过 Scanner 类来获取用户的输入。
下面是创建 Scanner 对象的基本语法:
Scanner s = new Scanner(System.in);
Method | Description |
---|---|
nextBoolean() | Reads a boolean value from the user |
nextByte() | Reads a byte value from the user |
nextDouble() | Reads a double value from the user |
nextFloat() | Reads a float value from the user |
nextInt() | Reads a int value from the user |
nextLine() | Reads a String value from the user |
nextLong() | Reads a long value from the user |
nextShort() | Reads a short value from the user |
3.java中double与float的区别:(推荐:java视频教程)
单精度浮点数(float)与双精度浮点数(double)的区别如下:
(1)在内存中占有的字节数不同
单精度浮点数在机内占4个字节
双精度浮点数在机内占8个字节
(2)有效数字位数不同
单精度浮点数有效数字8位
双精度浮点数有效数字16位
(3)所能表示数的范围不同
单精度浮点的表示范围:-3.40E+38 ~ +3.40E+38
双精度浮点的表示范围:-1.79E+308 ~ +1.79E+308
5.static
所谓静态就是指在编译后所分配的内存会一直存在,直到程序退出内存才会释放这个空间,也就是只要程序在运行,那么这块内存就会一直存
6..String[ ] args :
String 类型的数组,名为args,这个名字是可以变化的,但是一般使用args。
7.分号
individual Java statements and expressions are terminated with a semicolon.
8.next() 与 nextLine() 区别
next():
- 1、一定要读取到有效字符后才可以结束输入。
- 2、对输入有效字符之前遇到的空白,next() 方法会自动将其去掉。
- 3、只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符。
- next() 不能得到带有空格的字符串。
nextLine():
- 1、以Enter为结束符,也就是说 nextLine()方法返回的是输入回车之前的所有字符。
- 2、可以获得空白。
next() 与 nextLine() 区别
next():
- 1、一定要读取到有效字符后才可以结束输入。
- 2、对输入有效字符之前遇到的空白,next() 方法会自动将其去掉。
- 3、只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符。
- next() 不能得到带有空格的字符串。
nextLine():
- 1、以Enter为结束符,也就是说 nextLine()方法返回的是输入回车之前的所有字符。
- 2、可以获得空白。
知识点:
1.Calculations and Arithmetic
+ addition
- Subtraction
* multiplication
/ division
% modulus
2.Branching
if(boolean_expression1){
//code }
else if(boolean_expression2){
//code
}else {
//code
}
3.Java User Input
The Scanner
class is used to get user input, and it is found in the java.util
package.
To use the Scanner
class, create an object of the class and use any of the available methods found in the Scanner
class documentation. In our example, we will use the nextLine()
method, which is used to read Strings:
import java.util.Scanner;
// Import the Scanner class
class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
// Create a Scanner object
System.out.println("Enter username");
String userName = myObj.nextLine();
// Read user input
System.out.println("Username is: " + userName);
// Output user input
}
}
4.Java uses symbols:
&&, ||, !
逻辑运算符
下表列出了逻辑运算符的基本运算,假设布尔变量A为真,变量B为假
操作符 | 描述 | 例子 |
---|---|---|
&& | 称为逻辑与运算符。当且仅当两个操作数都为真,条件才为真。 | (A && B)为假。 |
| | | 称为逻辑或操作符。如果任何两个操作数任何一个为真,条件为真。 | (A | | B)为真。 |
! | 称为逻辑非运算符。用来反转操作数的逻辑状态。如果条件为true,则逻辑非运算符将得到false。 | !(A && B)为真。 |
5.Looping with For/While
Java while(boolean_expression){ #code
}
6.Looping with For/While
Java while(boolean_expression){ #code
}
7.Java – For Loop
for(int i = 0; i < 10; i++){ //code
}
8.Arrays
Java arrays are similar to Python lists Array have a fixed length in Java (i.e., are not dynamically sized)
int[] numbers = {0, 1, 2, 3, 4};
int[] ages = new int[15];
The length property of an array arr can be accessed using arr.length This allows you to iterate over the indices of the array:
for(int i = 0; i < arr.length; i++)
We can also iterate over items in an array using a ‘for each’ loop
Java for(int item: arr){ #assuming arr stores integers
}
9.Java ArrayLists
Java also provides the ArrayList class that grows dynamically
ArrayList words = new ArrayList();
Create a new list that stores String values Java ArrayLists
.add(element) - adds element to end of list
.clear() - clears list
.get(index) - gets item at specific index
.remove(index) - removes item at specific index
.remove(element) - removes element
.size() - returns size of list (# of elements)
10.HashMaps
HashMap is similar to Python’s dictionary Associates values with unique keys Again,
types must be specified and the class must be imported
Create a HashMap with integer keys and string values: HashMap students = new HashMap();
Useful HashMap Methods
.put(key, value) - adds key/value pair to map
.get(key) - returns value associated with key
.remove(key) - removes key/value pair from map
.size() - returns number of key/value pairs
.keySet() - returns set of keys for iteration (i.e., for…)
.containsKey(key) – returns true if key exists, otherwise returns false
Programming Example #1
Create a simple conversion program that request an amount of one unit (e.g., kilometers) and converts that amount to another unit (e.g., miles).创建一个简单的转换程序,该程序需要一个单位(例如,公里)的数量并将该数量转换为另一个单位(例如,英里)。
import java.util.Scanner;//java.util.Scanner 是 Java5 的新特征,我们可以通过 Scanner 类来获取用户的输入。
public class Ex1_Convension {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Enter a number for miles:");
int miles = in.nextInt(); //Reads a int value from the user
double kms = miles * 1.6f;
System.out.println(miles + "equal to " + kms + " kilometers.");
} //println() 是一个方法,System 是系统类,out 是标准输出对象。。
//这句话的用法是调用系统类 System 中的标准输出对象 out 中的方法 println()。
}
Programming Example #2
Write Java code that asks the user to enter two numbers and prints out the largest of the two numbers.
import java.util.Scanner;
public class Ex2_LargestOfTwo {
public static void main(String[] args) {
int num1,num2;
Scanner in = new Scanner(System.in);
System.out.println("Enter the first number: ");
num1 = in.nextInt();
System.out.println("Enter the second number: ");
num2 = in.nextInt();
if (num1 > num2){
System.out.println("the first number is greater.");
}else if (num2 > num1){
System.out.println("the second number is greater.");
}else
System.out.println("numbers are equal.");
}
}
Programming Example #3
Write Java code that reads three numbers from the user and prints out the largest of the three numbers Programming
import java.util.Scanner;
public class Ex3_LargestOfThree {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int num1,num2,num3;
System.out.println("Enter the first number: ");
num1 = in.nextInt();
System.out.println("Enter the second number: ");
num2 = in.nextInt();
System.out.println("Enter third number: ");
num3 = in.nextInt();
if (num1 > num2 &&
num1 > num3) {
System.out.println("The first number is greater ");
}else if (num2>num1 && num2 > num3){
System.out.println("The second number is greater ");
}
}else{
System.out.println("The third number is greater ");
}
}
Programming Example Example #4
Write Java code that asks the user to enter a username and password. The code should then print out "Welcome" if the username is "user" and the password is "12345". Note: comparing strings with == in Java does not work as you may expect, this is because String is an object in Java, not a primitive type
import java.util.Scanner;
public class Ex4_UsernameNPassword {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String name,password;
System.out.println("Enter a user name: ");
name = in.next();
System.out.println("Enter your password: ");
password = in.next();
if(name.equals("keqi") && password.equals("990216")){
System.out.println("Welcome " + name + "!");
}else{
System.out.println("Sorry!Incorrect username or password");
}
}
}
Programming Example #5
Write Java code that will repeatedly read numbers from the user until a negative number is entered. When a negative number is entered, the code should print out the total and average of all non-negative values entered by the user and then stop
import java.util.Scanner;
public class Ex5_PosTotalAvg {
public static void main(String [] args) {
Scanner in = new Scanner(System.in);
double number;
double sum = 0;
int count = 0;
while(true){
System.out.println("Enter a positive number:");
number = in.nextDouble();
if(number > 0) {
count += 1;
sum += number;
}else{
break;
}
System.out.println("The sum of all positive numbers is: " + sum);
System.out.println("The average of all positive number is : " + sum/count);
}
}
}
Programming Example #6
Write Java code that prints out the integer numbers from 1 to 10
public class Ex6_ForLoop {
public static void main(String[] args) {
for (int i = 0; i <= 10; i++) {
System.out.println(i);
}
}
}
Programming Example #7
Write Java code that asks the user to enter an integer and prints out whether that integer is a prime number or not
import java.util.Scanner;
public class Ex7_PrimeOrNot {
public static void main(String[] args){
Scanner in= new Scanner(System.in);
System.out.println("Enter a number: ");
int number = in.nextInt();
boolean isPrime = true;
for(int i = 2; i < number; i++){
if(number % i == 0){
isPrime = false;
break;
}
}
if(isPrime) {
System.out.println(number + " is prime");
}else{
System.out.println(number + " is not prime");
}
}
}
Programming Example - 8
Write Java code that allows a user to repeatedly enter numbers. Each time the user enters a number, the program should print out the average of the last 3 numbers (or all numbers if 3 or less have been entered).
import java.util.Scanner;
public class Ex8_AvgLast3Numbers {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int size =3;
int index = 0;
int number;
int totalAdded = 0;
double sum = 0;
int[] array = new int[size];
while(true){
System.out.println("Enter a number: ");
number = in.nextInt();
totalAdded ++;
if(totalAdded > size){
totalAdded = size;
}
sum -= array[index];
sum += number;
array[index] = number;
index++;
if(index == size){
index = 0;
}
System.out.println("The average is: " + sum/totalAdded);
}
}
}
Programming Example - 9
Write Java code that will ask the user to enter a nonnegative integer, x. The code should then generate an array of size x filled with randomly generated integers between 0-100 and print out the average of all of these numbers. Use the Random class that is included in Java编写Java代码,要求用户输入非负整数x。然后,代码应生成一个大小为x的数组,其中填充了0到100之间的随机生成的整数,并打印出所有这些数字的平均值。使用Java中包含的Random类
import java.util.Scanner;
import java.util.Random;
public class Ex9_RandomArrays {
public static void main(String[] args) {
Scanner in = new Scanner( System.in);
System.out.println("Enter the size of array: ");
int size = in.nextInt();
int[] numbers = new int[size];
Random rand = new Random();
int sum = 0;
int number;
for(int i = 0; i < size; i ++){
numbers[i] = rand.nextInt(101);
System.out.println(numbers[i]);
}
for(int num: numbers){
sum += num;
}
System.out.println("The number is " + (double)sum/size);
}
}
Programming Example - 10
Create a method that accepts an integer value as an argument and returns a Boolean value. The method should return true if the argument is a prime number and false otherwise.创建一个接受整数值作为参数并返回布尔值的方法。如果参数是素数,则该方法应返回true,否则返回false。
import java.util.Scanner;
public class Ex10_MethodForPrime {
public static boolean isPrime(int number){
for(int i = 2; i < number; i++){
if(number % i == 0){
return false;
}
}
return true;
}
public static
void main(String[] args){
Scanner in= new Scanner(System.in);
System.out.println("Enter a number: ");
int num = in.nextInt();
System.out.println(isPrime(num));
}
}
Programming Example - 11
Write a method that takes an array of integers as an argument and returns the largest of those integers.编写一个将整数数组作为参数并返回这些整数中最大的一个的方法。
import java.util.Random;
//Write a method that takes an array of integers as an
// argument and returns the largest of those integers.
public class Ex11_LargestInArray {
public static int largest(int[] array){
if(array.length == 0) return 0;
int largest = array[0];
for(int i=1; i< array.length; i++){
if(array[i] > largest){
largest = array[i];
}
}
return largest;
}
public static void main(String[] args){
Random rand = new Random();
int size = 10;
int[] array = new int[size];
for(int i =0; i< size; i++){
array[i] = rand.nextInt(100);
}
for(int number: array){
System.out.println(number);
}
System.out.println("The largest number is: " + largest(array));
}
}
Programming Example - 12
Write Java code that asks the user to enter a subtotal amount and a tip percentage. The code should then calculate the total bill and print out the total with proper formatting (e.g., $xx.yy)
import java.util.Scanner;
//Write Java code that asks the user to enter a subtotal
// amount and a tip percentage. The code should then
calculate
// the total bill and print out the total with
proper formatting (e.g., $xx.yy).
public class Ex12_FormatOutput {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
float amount = in.nextFloat();
float tip = in.nextFloat();
float balance = amount + amount * tip;
System.out.println(balance);
System.out.println("The final balance is $" + String.format("%.3f", balance));
}
}
Programming Example #13
Write a method that accepts an array list of double values as an argument. The method should return the median value of the list.
import java.util.ArrayList;
import java.util.Collections;
//Write a method that accepts an array list of double values as an
// argument. The method should return the median value of the list.
public class Ex13_MedianOfArrayList {
public static double getMedian(ArrayList<Double> aList){
Collections.sort(aList); //sort aList
/*for(double element: aList)
System.out.println(element);
*/
while(aList.size() > 2){
aList.remove(0);
aList.remove(aList.size() -1);
}
if(aList.size() == 2){
return (aList.get(0) + aList.get(1))/2;
}
else
return aList.get(0);
}
public static void main(String[] args) {
ArrayList<Double> aList = new ArrayList<Double>();
aList.add(20.0);
aList.add(10.5);
aList.add(2.6);
//aList.add(200.1);
aList.add(50.5);
aList.add(22.5);
aList.add(35.0);
System.out.println(getMedian(aList));
}
}
Programming Example #14
Write Java code that reads pairs of employee IDs (keys) and names (values) from the user and stores them in a HashMap. It should not be possible to add the same ID twice. When the user enters an ID of 0, the code should print out all of the ID/name pairs.编写Java代码,以从用户读取成对的员工ID(键)和名称(值),并将它们存储在HashMap中。不能两次添加相同的ID。当用户输入ID为0时,代码应打印出所有ID /名称对。
import java.util.HashMap;
import java.util.Scanner;
public class Ex14_HashMapEmployeeDB {
public static void main(String[] args) {
HashMap<Integer, String> employees = new HashMap<Integer, String>();
Scanner in = new Scanner(System.in);
int id = -1;
String name= "";
while(id != 0){
System.out.println("Enter an ID: ");
id = in.nextInt();
if(id == 0) break;
if(!employees.containsKey(id)){
System.out.println("Enter a name: ");
name = in.next();
employees.put(id,name);
}
else{
System.out.println("This ID exists!");
}
}
System.out.println("These are the employees saved in the DB:");
for(int i: employees.keySet()){
System.out.println("ID: " +i + " Name: " + employees.get(i));
}
}
}
最后
以上就是高贵含羞草为你收集整理的加拿大卡尔顿大学暑课两个月入门Java全记录_1Java Scanner 类的全部内容,希望文章能够帮你解决加拿大卡尔顿大学暑课两个月入门Java全记录_1Java Scanner 类所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复