java笔记2025
作者:liurw 日期:2025-02-13
Scanner Class in Java
文章来源 https://www.geeksforgeeks.org/scanner-class-in-java/
In Java, Scanner is a class in java.util package used for obtaining the input of the primitive types like int, double, etc. and strings.
Using the Scanner class in Java is the easiest way to read input in a Java program, though not very efficient if you want an input method for scenarios where time is a constraint like in competitive programming.
Java Scanner Input Types
Scanner class helps to take the standard input stream in Java. So, we need some methods to extract data from the stream. Methods used for extracting data are mentioned below:
nextXYZ
XYZ为Int等数据类型
Sometimes, we have to check if the next value we read is of a certain type or if the input has ended (EOF marker encountered).
Then, we check if the scanner’s input is of the type we want with the help of hasNextXYZ() functions where XYZ is the type we are interested in. The function returns true if the scanner has a token of that type, otherwise false. For example, in the below code, we have used hasNextInt(). To check for a string, we use hasNextLine(). Similarly, to check for a single character, we use hasNext().charAt(0).
----------------------------------------------------------------------------
// Java program to read some values using Scanner
// class and print their mean.
import java.util.Scanner;
public class ScannerDemo2 {
public static void main(String[] args)
{
// Declare an object and initialize with
// predefined standard input object
Scanner sc = new Scanner(System.in);
// Initialize sum and count of input elements
int sum = 0, count = 0;
// Check if an int value is available
while (sc.hasNextInt()) {
// Read an int value
int num = sc.nextInt();
sum += num;
count++;
}
if (count > 0) {
int mean = sum / count;
System.out.println("Mean: " + mean);
}
else {
System.out.println(
"No integers were input. Mean cannot be calculated.");
}
}
}
--------------------------------------------------------------------------------------
Important Points About Java Scanner Class
* To create an object of Scanner class, we usually pass the predefined object System.in, which represents the standard input stream. We may pass an object of class File if we want to read input from a file.
* To read numerical values of a certain data type XYZ, the function to use is nextXYZ(). For example, to read a value of type short, we can use nextShort()
* To read strings, we use nextLine().
* To read a single character, we use next().charAt(0). next() function returns the next token/word in the input as a string and charAt(0) function returns the first character in that string.
* The Scanner class reads an entire line and divides the line into tokens. Tokens are small elements that have some meaning to the Java compiler. For example, Suppose there is an input string: How are you
In this case, the scanner object will read the entire line and divides the string into tokens: “How”, “are” and “you”. The object then iterates over each token and reads each token using its different methods.
注:tokens 翻译为标记
-------------------------------------------
Static vs. Public
You will often see Java programs that have either static or public attributes and methods.
In the example above, we created a static method, which means that it can be accessed without creating an object of the class, unlike public, which can only be accessed by objects:
Example
An example to demonstrate the differences between static and public methods:
public class Main {
// Static method
static void myStaticMethod() {
System.out.println("Static methods can be called without creating objects");
}
// Public method
public void myPublicMethod() {
System.out.println("Public methods must be called by creating objects");
}
// Main method
public static void main(String[] args) {
myStaticMethod(); // Call the static method
// myPublicMethod(); This would compile an error
Main myObj = new Main(); // Create an object of Main
myObj.myPublicMethod(); // Call the public method on the object
}
}
------------------------------
2025-02-5
来源 https://www.w3schools.com/java/java_class_methods.asp
*******************************************************
2025-02-6
Import a Package[/b\
There are many packages to choose from. In the previous example, we used the Scanner class from the java.util package. This package also contains date and time facilities, random-number generator and other utility classes.
To import a whole package, end the sentence with an asterisk sign (*). The following example will import ALL the classes in the java.util package:
Example
import java.util.*;
[b]Why Encapsulation?
Better control of class attributes and methods
Class attributes can be made read-only (if you only use the get method), or write-only (if you only use the set method)
Flexible: the programmer can change one part of the code without affecting other parts
Increased security of data
*********
Java Constructors 构造器
A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes:
构造器 基本语法
[修饰符] 方法名(形参列表) {
方法体;
}
*******
Example
Create a constructor:
--------------
// Create a Main class
public class Main {
int x; // Create a class attribute
// Create a class constructor for the Main class
public Main() {
x = 5; // Set the initial value for the class attribute x
}
public static void main(String[] args) {
Main myObj = new Main(); // Create an object of class Main (This will call the constructor)
System.out.println(myObj.x); // Print the value of x
}
}
// Outputs 5
https://www.w3schools.com/java/java_constructors.asp
参考阅读 https://www.runoob.com/java/java-constructor.html
*** 2025-02-17 Mon.
Java - What is OOP?
OOP stands for Object-Oriented Programming.
Procedural programming is about writing procedures or methods that perform operations on the data, while object-oriented programming is about creating objects that contain both data and methods.
Object-oriented programming has several advantages over procedural programming:
OOP is faster and easier to execute
OOP provides a clear structure for the programs
OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes the code easier to maintain, modify and debug
OOP makes it possible to create full reusable applications with less code and shorter development time
创建类
https://www.w3schools.com/java/java_classes.asp
2025-02-18星期二
有参构造方法
可以定义带有参数的构造方法,用来在创建对象时为属性赋值:
实例
public class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
调用有参构造方法时,可以为对象的属性进行初始化:
Person p = new Person("Alice", 25);
https://www.runoob.com/java/java-constructor.html
文章来源 https://www.geeksforgeeks.org/scanner-class-in-java/
In Java, Scanner is a class in java.util package used for obtaining the input of the primitive types like int, double, etc. and strings.
Using the Scanner class in Java is the easiest way to read input in a Java program, though not very efficient if you want an input method for scenarios where time is a constraint like in competitive programming.
Java Scanner Input Types
Scanner class helps to take the standard input stream in Java. So, we need some methods to extract data from the stream. Methods used for extracting data are mentioned below:
nextXYZ
XYZ为Int等数据类型
Sometimes, we have to check if the next value we read is of a certain type or if the input has ended (EOF marker encountered).
Then, we check if the scanner’s input is of the type we want with the help of hasNextXYZ() functions where XYZ is the type we are interested in. The function returns true if the scanner has a token of that type, otherwise false. For example, in the below code, we have used hasNextInt(). To check for a string, we use hasNextLine(). Similarly, to check for a single character, we use hasNext().charAt(0).
----------------------------------------------------------------------------
// Java program to read some values using Scanner
// class and print their mean.
import java.util.Scanner;
public class ScannerDemo2 {
public static void main(String[] args)
{
// Declare an object and initialize with
// predefined standard input object
Scanner sc = new Scanner(System.in);
// Initialize sum and count of input elements
int sum = 0, count = 0;
// Check if an int value is available
while (sc.hasNextInt()) {
// Read an int value
int num = sc.nextInt();
sum += num;
count++;
}
if (count > 0) {
int mean = sum / count;
System.out.println("Mean: " + mean);
}
else {
System.out.println(
"No integers were input. Mean cannot be calculated.");
}
}
}
--------------------------------------------------------------------------------------
Important Points About Java Scanner Class
* To create an object of Scanner class, we usually pass the predefined object System.in, which represents the standard input stream. We may pass an object of class File if we want to read input from a file.
* To read numerical values of a certain data type XYZ, the function to use is nextXYZ(). For example, to read a value of type short, we can use nextShort()
* To read strings, we use nextLine().
* To read a single character, we use next().charAt(0). next() function returns the next token/word in the input as a string and charAt(0) function returns the first character in that string.
* The Scanner class reads an entire line and divides the line into tokens. Tokens are small elements that have some meaning to the Java compiler. For example, Suppose there is an input string: How are you
In this case, the scanner object will read the entire line and divides the string into tokens: “How”, “are” and “you”. The object then iterates over each token and reads each token using its different methods.
注:tokens 翻译为标记
-------------------------------------------
Static vs. Public
You will often see Java programs that have either static or public attributes and methods.
In the example above, we created a static method, which means that it can be accessed without creating an object of the class, unlike public, which can only be accessed by objects:
Example
An example to demonstrate the differences between static and public methods:
public class Main {
// Static method
static void myStaticMethod() {
System.out.println("Static methods can be called without creating objects");
}
// Public method
public void myPublicMethod() {
System.out.println("Public methods must be called by creating objects");
}
// Main method
public static void main(String[] args) {
myStaticMethod(); // Call the static method
// myPublicMethod(); This would compile an error
Main myObj = new Main(); // Create an object of Main
myObj.myPublicMethod(); // Call the public method on the object
}
}
------------------------------
2025-02-5
来源 https://www.w3schools.com/java/java_class_methods.asp
*******************************************************
2025-02-6
Import a Package[/b\
There are many packages to choose from. In the previous example, we used the Scanner class from the java.util package. This package also contains date and time facilities, random-number generator and other utility classes.
To import a whole package, end the sentence with an asterisk sign (*). The following example will import ALL the classes in the java.util package:
Example
import java.util.*;
[b]Why Encapsulation?
Better control of class attributes and methods
Class attributes can be made read-only (if you only use the get method), or write-only (if you only use the set method)
Flexible: the programmer can change one part of the code without affecting other parts
Increased security of data
*********
Java Constructors 构造器
A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes:
构造器 基本语法
[修饰符] 方法名(形参列表) {
方法体;
}
*******
Example
Create a constructor:
--------------
// Create a Main class
public class Main {
int x; // Create a class attribute
// Create a class constructor for the Main class
public Main() {
x = 5; // Set the initial value for the class attribute x
}
public static void main(String[] args) {
Main myObj = new Main(); // Create an object of class Main (This will call the constructor)
System.out.println(myObj.x); // Print the value of x
}
}
// Outputs 5
https://www.w3schools.com/java/java_constructors.asp
参考阅读 https://www.runoob.com/java/java-constructor.html
*** 2025-02-17 Mon.
Java - What is OOP?
OOP stands for Object-Oriented Programming.
Procedural programming is about writing procedures or methods that perform operations on the data, while object-oriented programming is about creating objects that contain both data and methods.
Object-oriented programming has several advantages over procedural programming:
OOP is faster and easier to execute
OOP provides a clear structure for the programs
OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes the code easier to maintain, modify and debug
OOP makes it possible to create full reusable applications with less code and shorter development time
创建类
https://www.w3schools.com/java/java_classes.asp
2025-02-18星期二
有参构造方法
可以定义带有参数的构造方法,用来在创建对象时为属性赋值:
实例
public class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
调用有参构造方法时,可以为对象的属性进行初始化:
Person p = new Person("Alice", 25);
https://www.runoob.com/java/java-constructor.html
[本日志由 liurw 于 2025-02-18 11:52 AM 更新]






评论: 0 | 引用: 0 | 查看次数: 287