Java_SSD3_Experiment 7 "String and Text I/O"


Please refer to the following articles for the knowledge used below:

The knowledge points and methods of the Java string String class advanced version

Java file input and output PrintWriter and Scanner summary

Scanner working mechanism-mark reading method, in-depth understanding of the difference between next() and nextline()


1. The purpose of the experiment

  1. The use of string processing methods in the String class
  2. Programming and running of passing parameters from the command line to the main method
  3. File category and file input and output

2. Experimental content

  1. [Password detection] Some websites have set some rules for specifying passwords. Write a method to detect whether a string is a valid password. Assume that the password rules are as follows:

  1. The password must have at least 8 characters.
  2. The password can only include numbers and letters.
  3. The password must have at least 2 digits.

Write a program that prompts the user to enter a password. If the password meets the rules, it will display "Valid Password", otherwise it will display "Invalid Password".

 

1.1 Experimental results and analysis

1) Test data one

Analysis: When a valid password is entered, the degree operation result is correct

 

2) Test data two

Analysis: When the entered password is wrong, the program will remind the user to re-enter

 

It can be seen from the above test results that the program fully meets the experimental requirements.

1.2 Experience

  Java's string class has many convenient methods, which can be used flexibly to solve problems efficiently.

This experiment can gradually determine whether the input password meets the requirements

1.3 The source code is as follows

package Lab7;  
  
import java.util.Scanner;  
  
/*1.【检测密码】一些网站设定了一些指定密码的规则。编写一个方法,检测一个字符串是否是合法的密码。假定密码规则如下: 
   密码必须至少有8个字符。 
   密码只能包括数字和字母。 
   密码必须至少有2个数字。 
 
编写一个程序,提示用户输入密码,如果该密码符合规则就显示“Valid Password”,否则显示“Invalid Password”。 
 
 
 
 */  
public class Program1String {  
  public static boolean isValid(String s){  
      int len = s.length(),count_num=0;  
      if(len < 8)  
          return false;  
      for (int i = 0; i < len; i++) {  
          if(!Character.isDigit(s.charAt(i)) && !Character.isLetter(s.charAt(i)))  
              return false;  
          if(Character.isDigit(s.charAt(i)))  
              count_num++;  
      }  
      if(count_num <2 )  
          return false;  
      return true;  
  }  
  
    public static void main(String[] args) {  
        Scanner input = new Scanner(System.in);  
        System.out.println("Please enter a password:");  
        boolean flag = true;  
        while (flag)  
        {  
            String s = input.nextLine();  
            if(isValid(s))  
            {  
                System.out.println("Valid Password");  
                flag = false;  
            }  
            else  
            {  
                System.out.println("Invalid Password");  
                System.out.println("Please re-enter:");  
            }  
        }  
    }  
  
}  

2. [Count the number of characters, words and lines in a character] Write a program to count the number of characters (except the control characters \r and \n), the number of words and the number of lines in a file. Words are separated by spaces, tabs, carriage returns, or newlines. The file name is passed as a command line parameter. As shown below:

2.1 Experimental results and analysis

1 ) Test data one

Test data in the file:

Output result:

2) Test data two

Test data in the file:

Output result:

 

3 ) Test data three

When the file does not exist, the program outputs the result:

 

Result analysis:

All test data of this program are correct and fully meet the experimental requirements.

 

2.2 Experience

 The program should pay attention to three issues:

  1. A method for adding parameters to commands in IDEA : Click the Run option in the upper toolbar, click the Edit option, and enter the command line parameters in the Program arguments column.
  2. Know the working mechanism of Scanner and can use Scanner flexibly
  3. Java files generally use relative paths, and the same level directory is at the same level as the src file, which is the first level under the project file.

Related knowledge reference link:

Java file input and output PrintWriter and Scanner summary

Scanner working mechanism-mark reading method, in-depth understanding of the difference between next() and nextline()

 

2.3 The source code is as follows

 

package Lab7;  
  
import java.io.File;  
import java.io.FileNotFoundException;  
import java.util.Scanner;  
  
import static jdk.nashorn.internal.runtime.regexp.joni.Syntax.Java;  
  
/*【统计一个字符中的字符数、单词数和行数】编写程序统计一个文件中的字符数(控制字符\r和\n除外)、单词数以及行数。 
单词由空格、Tab、回车或换行符分隔。文件名作为命令行参数传递。如下图所示: 
 
 */  
public class Program2fileandmain {  
    public static void main(String[] args) throws FileNotFoundException {  
        File file = new File(args[0]);  
        String s ;  
        int count_word = 0, count_char = 0,count_line = 0;  
        try(  
                Scanner input = new Scanner(file);  
                ){  
           while (input.hasNext()){  
               s = input.nextLine();  
               count_line++;        //读取一行加一  
               count_char+= s.length();  
               Scanner temp = new Scanner(s); //在一行字符串中读取标记读取单词  
               String t ;  
               while (temp.hasNext()){  
                   t = temp.next();  
                   count_word++;  
               }  
           }  
            System.out.println(file.getName()+" has\n"  
                             +"words:"+count_word+  
                             "\ncharacters:"+count_char  
                             +"\nLine:"+count_line  
                                   );  
        }  
  
  
  
  
  
    }  
  
}  

 


 

3. [Read and write data] Write a program, if the file named Exercise9_19.txt does not exist, create the file. Use text I/O to write randomly generated 10 integers to the file. The integers in the file are separated by spaces. Read the data back from the file, and then display the sorted data.

3.1 Experimental results and analysis

1) Test result one

When the file Exercise9_19.txt does not exist, the program output result is:

The data in the file Exercise9_19.txt is:

2) Test result two

When the file exists, the output of the program is:

The data in the file Exercise9_19.txt is:

 

Result analysis: In many cases, the program runs correctly and meets the experimental requirements.

 

3.2 Experience

   Programming should develop these good habits: to determine whether the file exists; when using PrintWriter and Scanner, try-with-sources as much as possible. Avoid unnecessary mistakes.

 

3.3 source code

package Lab7;  
  
import java.io.File;  
import java.io.FileNotFoundException;  
import java.io.PrintWriter;  
import java.util.Arrays;  
import java.util.Scanner;  
  
/*.【读写数据】编写一个程序,如果名为Exercise9_19.txt的文件不存在,则创建该文件。 
使用文本I/O编写随机产生10个整数给文件。文件中的整数由空格分开。从文件中读回这些数据,然后显示排好序的数据。 
 
 */  
public class Program3fileoi {  
    public static void main(String[] args) throws FileNotFoundException {  
        File file = new File("Exercise9_19.txt");  
        if(!file.exists()){  
            System.out.println("没有找到该文件,创建一个Exercise9_19.txt文件:");  
            try(  
                    PrintWriter output = new PrintWriter(file);  
                    )  
            {  
                for (int i = 0; i < 10; i++) {  
                    output.print((int)(Math.random() * 100));  
                    output.print(" ");  
                }  
            }  
        }  
  
  
        int[] list = new int[10];  
       try (  
               Scanner input = new Scanner(file);  
       ){  
            for (int i = 0; i < 10; i++) {  
                list[i] = input.nextInt();  
            }  
        }  
        Arrays.sort(list);  
        System.out.println("Exercise9_19.txt 文件中的数据排好序后为:");  
        System.out.println(Arrays.toString(list));  
  
  
    }  
}  

 

Guess you like

Origin blog.csdn.net/qq_45768060/article/details/106507232