当前位置:网站首页>Problems encountered in special flow & properties property set instances and Solutions
Problems encountered in special flow & properties property set instances and Solutions
2022-07-29 02:16:00 【Wang Xiaoya】
Catalog
stem 1:
Write a small program , Record the number of times the program runs , Satisfy 5 Next time , Give hints , The number of trials has reached , Please register !
analysis :
1. Encapsulate the configuration file as File object , Judge whether the file exists , If it doesn't exist, create it yourself
2. A counter is required ;
3. The value of the counter , The life cycle is longer than the application life cycle , You need to persist the value of the counter .count = 1, What is stored inside should be the key value method ,Map aggregate , To be associated with the data on the device , need IO technology . aggregate + IO = Properties.
Their thinking :
1. Write a small program class , Take guessing numbers as an example , stay 1-100 Randomly generate an arbitrary natural number , Input the numbers in turn and compare them to generate numbers , Correct answer exit , Once ;
System.out.println(" Please enter a number (1-100):");
int number=sc.nextInt();// Used to receive the numbers entered by the console
// Only jump out of the loop when you guess right , Program end
while(true){
if (number < i) {
System.out.println("sorry, You guess it's small ");
} else if (number > i) {
System.out.println("sorry, You guessed big ");
} else if (number==i){
System.out.println(" congratulations , bingo ");
break;
}
System.out.println(" Please enter a number :");
number=sc.nextInt();
}
2. Create a data source directory File object , The path is a Temp\\applet.txt, Judge whether the file exists , If it doesn't exist, create it yourself ;
File file = new File("E:\\IdeaProjects\\firstProject\\Temp\\applet.txt");
if (!file.exists()) {
file.createNewFile();// create a file
}
3. Once it's created applet.txt Remember to write the initialization object into the file later count=0( Remember that !!!)
4. Read data from file to Properties aggregate , use load() Method realization ;
FileReader fr = new FileReader("E:\\IdeaProjects\\firstProject\\Temp\\applet.txt");
// Read data from file to Properties aggregate , use load() Method realization
Properties prop = new Properties();// Read the attribute list from the input character stream ( Bond and element pair )
prop.load(fr);
fr.close(); // Release resources
5. Determine whether the number of times has reached 5 Time ,
If it comes to , Give hints : The number of trials has reached , Please register !
If not, you can continue to run
// Determine whether the number of times has reached 5 Time
if (number >= 5) {
// If it comes to , Give hints : The number of trials has reached , Please register !
System.out.println(" The number of trials has reached , Please register !");
} else {
// Can continue to run
Running02 running = new Running02();
running.start();
}
6. Run once +1, Write back the file , use Properties Of store() Method realization
// frequency +1, Write back the file , use Properties Of store() Method realization
number++;
prop.setProperty("count", String.valueOf(number));
FileWriter fw = new FileWriter("Temp\\applet.txt");
prop.store(fw, null);
fw.close();
Problems and solutions :
problem 1: Run and exit directly , Report errors
reason :if Statement area error
solve : take “}” Just put it in the right place
problem 2:
reason :
prop.load(fr); Release resources before writing , Nature is null, Error string conversion type error , Write the content and it will work normally
solve :
problem 3: Can't read data
reason :applet.txt There are no initialization times in the file count
solve : Write initialization object count=0
matters needing attention :
1. At first I tried to use FileReader Create a data source directory File object , But I made a mistake in judging whether the file exists , Find out File.exists() More convenient , So I changed the code ,
First create File Object reuse File.exists() Judge whether it exists ,
If it does not exist, use file.createNewFile() create a file ,
Then write the newly created FileReader In the object
File file = new File("E:\\IdeaProjects\\firstProject\\Temp\\applet.txt");
if (!file.exists()) {
file.createNewFile();// create a file
}
FileReader fr = new FileReader("E:\\IdeaProjects\\firstProject\\Temp\\applet.txt");
// Read data from file to Properties aggregate , use load() Method realization
Properties prop = new Properties();// Read the attribute list from the input character stream ( Bond and element pair )
prop.load(fr);
fr.close(); // Release resources
2. Once it's created applet.txt Remember to write the initialization object into the file later count=0( Remember that !!!)
Running results :
Complete code :
Operation class :
package com.B.IOStream_14.Properties;
import java.util.Random;
import java.util.Scanner;
// The class that runs the code
public class Running02 {
public static void start() {
// Generate a 1~100 The random number
Random r=new Random();
int i=r.nextInt(100);
// Enter the guessed number on the keyboard
Scanner sc=new Scanner(System.in);
System.out.println(" Please enter a number (1-100):");
int number=sc.nextInt();// Used to receive the numbers entered by the console
// Only jump out of the loop when you guess right , Program end
while(true){
if (number < i) {
System.out.println("sorry, You guess it's small ");
} else if (number > i) {
System.out.println("sorry, You guessed big ");
} else if (number==i){
System.out.println(" congratulations , bingo ");
break;
}
System.out.println(" Please enter a number :");
number=sc.nextInt();
}
}
}
Test class :
package com.B.IOStream_14.Properties;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
//2. Write a small program , Record the number of times the program runs , Satisfy 5 Next time , Give hints , The number of trials has reached , Please register !
// analysis :
// 1. Encapsulate the configuration file as File object , Judge whether the file exists , If it doesn't exist, create it yourself
// 2. A counter is required ;
// 3. The value of the counter , The life cycle is longer than the application life cycle , You need to persist the value of the counter .
// count = 1, What is stored inside should be the key value method ,Map aggregate , To be associated with the data on the device , need IO technology .
// aggregate + IO = Properties
public class A2 {
public static void main(String[] args) throws IOException {
// Create a data source directory File object , The path is a Temp\applet.txt
File file = new File("E:\\IdeaProjects\\firstProject\\Temp\\applet.txt");
if (!file.exists()) {
file.createNewFile();// create a file
}
FileReader fr = new FileReader("E:\\IdeaProjects\\firstProject\\Temp\\applet.txt");
// Read data from file to Properties aggregate , use load() Method realization
Properties prop = new Properties();// Read the attribute list from the input character stream ( Bond and element pair )
prop.load(fr);
fr.close(); // Release resources
// adopt Properties Set to get the number of games played
String count = prop.getProperty("count");
int number = Integer.parseInt(count);
// Determine whether the number of times has reached 5 Time
if (number >= 5) {
// If it comes to , Give hints : The number of trials has reached , Please register !
System.out.println(" The number of trials has reached , Please register !");
} else {
// Can continue to run
Running02 running = new Running02();
running.start();
}
// frequency +1, Write back the file , use Properties Of store() Method realization
number++;
prop.setProperty("count", String.valueOf(number));
FileWriter fw = new FileWriter("Temp\\applet.txt");
prop.store(fw, null);
fw.close();
}
}
stem 2:
Use code to realize the following requirements
(1) Define the student class , Include name (String name), Gender (String gender), Age (int age) Three attributes , Generate null and parametric constructions ,set and get Method ,toString Method
(2) Keyboard Entry 6 Student information ( Input format : Zhang San , male ,25), Two identical messages are required , take 6 Student information is stored in ArrayList Collection
(3) There will be 6 Student information ArrayList The collection object is written to D:\\StudentInfo.txt In file
(4) Read D:\\StudentInfo.txt In the document ArrayList object
(5) Yes ArrayList In the collection 6 Students were de duplicated and sorted in order of age
(6) take ArrayList The sorted results in the set are used PrintWriter Stream write to E:\\StudentInfo.txt In file ( Write format : Zhang San - male -25)
Their thinking :
1. Define the student class , Include name (String name), Gender (String gender), Age (int age) Three attributes , Generate null and parametric constructions ,set and get Method ,toString Method ;
private String name;
private String gender;
private int age;
public Student03() {
}
public Student03(String name, String gender, int age) {
this.name = name;
this.gender = gender;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student03{" +
"name='" + name + '\'' +
", gender='" + gender + '\'' +
", age=" + age +
'}';
2. Create a collection object
ArrayList<Student03> array = new ArrayList<Student03>();
3. Enter the data required by the student object with the keyboard
// Enter the data required by the student object with the keyboard
Scanner sc = new Scanner(System.in);
System.out.println(" Please enter the student's name :");
String name = sc.nextLine();
System.out.println(" Please enter the student's gender :");
String gender = sc.nextLine();
System.out.println(" Please enter the age of the student :");
int age = sc.nextInt();
4. Create student objects , Assign the data entered by the keyboard to the member variables of the student object , Add a student object to the collection
Student03 s = new Student03();
s.setName(name);
s.setGender(gender);
s.setAge(age);
// Add a student object to the collection
array.add(s);
5. There will be 6 Student information ArrayList The collection object is written to StudentInfo.txt file
FileWriter fw = new FileWriter(new File("Temp\\StudentInfo.txt"));
for (Student03 stu03 : array) {
fw.write(String.valueOf(stu03));
fw.flush();
}
System.out.println(" Copy complete !");
fw.close();
6. In order to improve the reusability of code , We use methods to call methods addStudent, Ergodic set , The general traversal format is used to realize
// In order to improve the reusability of code , We use methods to call methods addStudent
for (int i =0; i<6;i++){
addStudent(array);
}
// 6: Ergodic set , The general traversal format is used to realize
for (int i = 0; i < array.size(); i++) {
Student03 s = array.get(i);
System.out.println(s.getName() + ","+s.getGender()+"," + s.getAge());
}
}
What happened :
problem 1: Enter name, gender and age , Output name and age of results , Gender loss
But look at the constructed StudentInfo There is gender in it , Strange !
reason : Solved the case ! When traversing the output, it is not added orz……
solve :
Running results :
Complete code :
Students :
package com.B.IOStream_14.Properties;
//3. Use code to realize the following requirements
//(1) Define the student class , Include name (String name), Gender (String gender), Age (int age) Three attributes , Generate null and parametric constructions ,set and get Method ,toString Method
//(2) Keyboard Entry 6 Student information ( Input format : Zhang San , male ,25), Two identical messages are required , take 6 Student information is stored in ArrayList Collection
//(3) There will be 6 Student information ArrayList The collection object is written to D:\\StudentInfo.txt In file
//(4) Read D:\\StudentInfo.txt In the document ArrayList object
//(5) Yes ArrayList In the collection 6 Students were de duplicated and sorted in order of age
//(6) take ArrayList The sorted results in the set are used PrintWriter Stream write to E:\\StudentInfo.txt In file ( Write format : Zhang San - male -25)
public class Student03 {
private String name;
private String gender;
private int age;
public Student03() {
}
public Student03(String name, String gender, int age) {
this.name = name;
this.gender = gender;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student03{" +
"name='" + name + '\'' +
", gender='" + gender + '\'' +
", age=" + age +
'}';
}
}
Test class :
package com.B.IOStream_14.Properties;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
//3. Use code to realize the following requirements
//(1) Define the student class , Include name (String name), Gender (String gender), Age (int age) Three attributes , Generate null and parametric constructions ,set and get Method ,toString Method
//(2) Keyboard Entry 6 Student information ( Input format : Zhang San , male ,25), Two identical messages are required , take 6 Student information is stored in ArrayList Collection
//(3) There will be 6 Student information ArrayList The collection object is written to D:\\StudentInfo.txt In file
//(4) Read D:\\StudentInfo.txt In the document ArrayList object
//(5) Yes ArrayList In the collection 6 Students were de duplicated and sorted in order of age
//(6) take ArrayList The sorted results in the set are used PrintWriter Stream write to E:\\StudentInfo.txt In file ( Write format : Zhang San - male -25)
public class A3 {
public static void main(String[] args) throws IOException {
// Create objects
ArrayList<Student03> array = new ArrayList<Student03>();
// In order to improve the reusability of code , We use methods to call methods addStudent
for (int i =0; i<6;i++){
addStudent(array);
}
// 6: Ergodic set , The general traversal format is used to realize
for (int i = 0; i < array.size(); i++) {
Student03 s = array.get(i);
System.out.println(s.getName() + ","+s.getGender()+"," + s.getAge());
}
}
/*
Two clear :
return type :void
Parameters :ArrayList<Student03> array
*/
public static void addStudent (ArrayList<Student03> array) throws IOException {
// Enter the data required by the student object with the keyboard
Scanner sc = new Scanner(System.in);
System.out.println(" Please enter the student's name :");
String name = sc.nextLine();
System.out.println(" Please enter the student's gender :");
String gender = sc.nextLine();
System.out.println(" Please enter the age of the student :");
int age = sc.nextInt();
// Create student objects , Assign the data entered by the keyboard to the member variables of the student object
Student03 s = new Student03();
s.setName(name);
s.setGender(gender);
s.setAge(age);
// Add a student object to the collection
array.add(s);
// There will be 6 Student information ArrayList The collection object is written to D:\\StudentInfo.txt In file
FileWriter fw = new FileWriter(new File("Temp\\StudentInfo.txt"));
for (Student03 stu03 : array) {
fw.write(String.valueOf(stu03));
fw.flush();
}
System.out.println(" Copy complete !");
fw.close();
}
}
Last thing I want to say :
Writing code seems simple but not simple , Many times, small details that seem inconspicuous can often determine success or failure , My life is boundless, but my study is boundless , Work hard together to refuel !
边栏推荐
- Probability Density Reweight
- Mathematical modeling -- heat conduction of subgrade on Permafrost
- QT memory management tips
- Motionlayout -- realize animation in visual editor
- H5 background music is played automatically by touch
- Mathematical modeling -- cold proof simulation of low temperature protective clothing with phase change materials
- Rgbd point cloud down sampling
- Verilog procedure assignment statements: blocking & non blocking
- 年中总结 | 与自己对话,活在当下,每走一步都算数
- 费曼学习法(符号表)
猜你喜欢
TI C6000 TMS320C6678 DSP+ Zynq-7045的PS + PL异构多核案例开发手册(2)
Type analysis of demultiplexer (demultiplexer)
Flexible layout single selection
基于C51实现数码管的显示
Understand the working principle of timer in STM32 in simple terms
Web crawler API Quick Start Guide
Anti crawler mechanism solution: JS code generates random strings locally
字符流综合练习解题过程
Solution of Lenovo notebook camera unable to open
什么是作用域和作用域链
随机推荐
Solution of Lenovo notebook camera unable to open
druid. IO custom real-time task scheduling policy
Rgbd point cloud down sampling
JS dom2 and dom3
JetPack--Navigation实现页面跳转
费曼学习法(符号表)
Mathematical modeling -- heat conduction of subgrade on Permafrost
In 2022, the official data of programming language ranking came, which was an eye opener
"Wei Lai Cup" 2022 Niuke summer multi school training camp 3, sign in question cajhf
(arxiv-2018) reexamine the time modeling of person Reid based on video
RGBD点云降采样
Read the recent trends of okaleido tiger and tap the value and potential behind it
年中总结 | 与自己对话,活在当下,每走一步都算数
The problem of modifying the coordinate system of point cloud image loaded by ndtmatching function in autoware
Comprehensive use method of C treeview control
[circuit design] peak voltage and surge current
Click back to the top JS
记一次 ERROR scheduler.AsyncEventQueue: Dropping event from queue shared导致OOM
[electronic components] zener diode
Leetcode exercise - Sword finger offer 45. arrange the array into the smallest number