publicclassfactorial{ publicstaticvoidmain(String[] args){ int sum = 0; int n = 1; int next = 0; while (next <= 10000) { sum = sum + fun(n); next = sum + fun(++n); } System.out.printf("累加之和为 %d, 数字 n 为 %d\n", sum, n-1); } publicstaticintfun(int n){ if (n == 1 || n == 0) return1; return n * fun(n - 1); } }
2. 从标准输入端输入一个字符,判断字符是数字、还是西文字母还是其他的字符。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
import java.util.Scanner; publicclassjudge{ publicstaticvoidmain(String[] args){ while (true) { Scanner scanner = new Scanner(System.in); System.out.println("请输入一个字符以进行判断,输入Q结束程序:"); char c = scanner.next().charAt(0); if (c == 'q' || c == 'Q') break; if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') System.out.println(c + "是一个西文字母"); elseif (c >= '0' && c <= '9') System.out.println(c + "是一个数字"); else System.out.println(c + "是其他字符"); } } }
import java.util.Scanner; publicclassChinese_remainder_theorem{ publicstaticvoidmain(String[] args){ for (int i = 1000; i <= 1100; i++) if (i % 3 == 2 && i % 5 == 3 && i % 7 == 2) System.out.println(i); } }
classA{ public String Show(D obj){ return ("A and D"); } public String Show(A obj){ return ("A and A"); } } classBextendsA{ public String Show(B obj){ return ("B and B"); } public String Show(A obj){ return ("B and A"); } } classCextendsB{ public String Show(C obj){ return ("C and C"); } public String Show(B obj){ return ("C and B"); } } classDextendsB{ public String Show(D obj){ return ("D and D"); } public String Show(B obj){ return ("D and B"); } }
publicclassmainTest{ publicstaticvoidmain(String args[]){ A a1 = new A(); A a2 = new B(); B b = new B(); C c = new C(); D d = new D(); System.out.println(a1.Show(b)); System.out.println(a1.Show(c)); System.out.println(a1.Show(d)); System.out.println(a2.Show(b)); System.out.println(a2.Show(c)); System.out.println(a2.Show(d)); System.out.println(b.Show(b)); System.out.println(b.Show(c)); System.out.println(b.Show(d)); }}
分析:
第一个输出:B自动转换为父类A,因此输出A and A;
第二个输出:与上面同理,自动转换为父类A,因此输出A and A;
第三个输出:调用A类的第一个Show函数,输出A and A;
第四个输出:首先因为引用类型为A类,所以系统想要执行A类的方法,但A类并没有找到类型匹配的方法,于是将参数b自动转化为父类,执行Show(A obj)方法,又因为a1实际指向了B类的对象,子类B重写了这个方法,因此优先执行子类的方法,于是输出B and A;
第五个输出:与上面同理,只是又将参数c多转化了一步,输出B and A;
第六个输出:与第四个类似,由于a2的引用类型是A类,而class A包含Show(D obj)方法,因此直接输出A and D;
第七个输出:直接调用B的Show(B obj)方法,因此输出B and B;
第八个输出:因为没有匹配的方法,因此参数c自动转换为父类B,因此调用Show(B obj)方法,输出B and B;
第九个输出:因为B的父类A类中方法Show(D obj)匹配,因此调用此方法输出A and D。
答案:
1 2 3 4 5 6 7 8 9
A and A A and A A and D B and A B and A A and D B and B B and B A and D
publicclassAnimalFactory{ static Tiger tiger = new Tiger(); static Rabbit rabbit = new Rabbit(); static Bear bear = new Bear(); static Panda panda = new Panda();
@Override publicvoidIncreaseanimals(){ this.count++; } @Override publicvoidgetAnimalCount(){ System.out.println("The current total number of " + this.getClass().getName().substring(12) + "(s) is: " + this.count); }
@Override publicvoidgetAnimalCount(){ System.out.println("The current total number of "+this.getClass().getName().substring(12)+"(s) is: " + this.count); } }
publicstaticvoidmain(String[] args){ Scanner scanner = new Scanner(System.in); System.out.println("********* Welcome to the Animal Factory! *********"); System.out.println("There are the following animals to choose from: \nBear, Panda, Rabbit, Tiger"); System.out.println("If you want to add an animal, you only need to enter the name of the above animal, not case sensitive."); System.out.println("Type q to exit."); while (true) { System.out.print("\nPlease input an animal: "); String in = scanner.next(); if(in.equalsIgnoreCase("q")) break; AnimalFactory.getAnimal(in); System.out.println("The current total number of all animals is: " + Animal.sumall); } }
publicclassStudentManager{ publicstaticvoidmain(String[] args){ System.out.println("---------------- Welcome to the Student Management System ----------------");
ArrayList<Student> stuCollection = new ArrayList<Student>(); Student stu1 = new Student("08190001","Alex",20,"Chaoyang District, Beijing"); Student stu2 = new Student("08190018","Christian",21,"Quanshan District, Xuzhou City"); Student stu3 = new Student("08198888","Edward",19,"Brooklyn, New York City"); Student stu4 = new Student("08199900","Herman",20,"East Bay, San Francisco");
publicstaticvoidaddStudent(ArrayList<Student> stuCollection){ Scanner sc = new Scanner(System.in); String stuid;
while (true) { System.out.println("Enter student ID:"); stuid = sc.nextLine();
int i = findStudent(stuCollection, stuid); if (i != -1) { System.out.println("⚠ The student information you want to add already exists The student information you want to add already exists!"); } else { break; } }
System.out.println("Enter the student's name:"); String name = sc.nextLine();
System.out.println("Enter the age of the student:"); int age = sc.nextInt();
System.out.println("Enter the student's residential address:"); String address = sc.next();
Student stu = new Student(stuid, name, age, address); stuCollection.add(stu); System.out.println("✅️Added successfully.");
}
publicstaticintfindStudent(ArrayList<Student> stuCollection, String stuid){ for (int i = 0; i < stuCollection.size(); i++) { Student stu = stuCollection.get(i); if (stuid.equals(stu.getStuID())) { return i; } } return -1; }
publicstaticvoidfindStudentAndDisplay(ArrayList<Student> stuCollection){ System.out.println("Please enter the student ID of the student you want to find:"); Scanner sc = new Scanner(System.in); String stuid = sc.nextLine(); int i = findStudent(stuCollection,stuid); if (i == -1) { System.out.println("⚠ The student's information you want to find does not exist!"); return; } System.out.println("Find the following students:"); System.out.format("%-14s%-14s%-14s%-14s","StudentID","Name","Age","Address"); System.out.println(); System.out.format("%-14s%-14s%-14s%-14s\n", stuCollection.get(i).getStuID(),stuCollection.get(i).getName(),stuCollection.get(i).getAge(),stuCollection.get(i).getAddress());
}
publicstaticvoidviewAllStudent(ArrayList<Student> stuCollection){ if (stuCollection.size() == 0) { System.out.println("⚠ No student found."); return; } System.out.format("%-14s%-14s%-14s%-14s","StudentID","Name","Age","Address"); System.out.println(); for (Student student : stuCollection) { System.out.format("%-14s%-14s%-14s%-14s\n",student.getStuID(),student.getName(),student.getAge(),student.getAddress()); } }
publicstaticvoiddeleteStudent(ArrayList<Student> stuCollection){ System.out.println("Please enter the student ID you want to delete:"); viewAllStudent(stuCollection); Scanner sc = new Scanner(System.in); String stuid = sc.nextLine();
int i = findStudent(stuCollection, stuid); if (i == -1) { System.out.println("⚠ The student's information you want to delete does not exist!"); return; } stuCollection.remove(i); System.out.println("✅️Deleted successfully."); }
publicstaticvoidmodifyStudentInformation(ArrayList<Student> stuCollection){ System.out.println("Please enter the student ID of the student you want to modify:"); viewAllStudent(stuCollection); Scanner sc = new Scanner(System.in); String stuid = sc.nextLine();
int i = findStudent(stuCollection, stuid); if (i == -1) { System.out.println("⚠ The student's information you want to modify does not exist"); return; }
System.out.println("Please enter the revised name:"); String name = sc.nextLine();
System.out.println("Please enter the revised age:"); int age = sc.nextInt();
System.out.println("Please enter the revised address:"); String address = sc.next();
Student s = new Student(stuid, name, age, address); stuCollection.set(i, s); System.out.println("✅️Modified successfully."); } }
publicclassNonQuadraticEquationExceptionextendsException{ public String message; publicNonQuadraticEquationException(){ message = "The input equation is not a binary linear equation!"; } public String toString(){ return message; } }
CalcPanel() { this.setLayout(new GridLayout(0,1,10,10)); text1 = new JTextField(); text1.setPreferredSize(text1.getSize()); text2 = new JTextField(); text2.setPreferredSize(text1.getSize()); text3 = new JTextField(); text3.setPreferredSize(text1.getSize()); Font font = new Font(Font.SERIF, Font.PLAIN, 20); label1 = new JLabel("Quadratic Term Coefficient"); label2 = new JLabel("Primary Term Coefficient"); label3 = new JLabel("Constant Term"); label1.setFont(font); label1.setHorizontalAlignment(SwingConstants.HORIZONTAL); label2.setFont(font); label2.setHorizontalAlignment(SwingConstants.HORIZONTAL); label3.setFont(font); label3.setHorizontalAlignment(SwingConstants.HORIZONTAL); button1 = new JButton("Solve"); button2 = new JButton("Clear the input box"); button3 = new JButton("Exit"); button4 = new JButton("Deserialize"); button2.setSize(300,25); button2.addActionListener(this::actionPerformedClear); button3.addActionListener(this::actionPerformedExit); button4.addActionListener(this::actionPerformedDeserialize);
add(label1); add(text1); add(label2); add(text2); add(label3); add(text3); add(button1); add(button2); add(button3); add(button4); } //Clear publicvoidactionPerformedClear(ActionEvent e){ this.text1.setText(""); this.text2.setText(""); this.text3.setText(""); } //Exit publicvoidactionPerformedExit(ActionEvent e){ int result = JOptionPane.showConfirmDialog(null, "Confirm to exit the interface?", "Exit",JOptionPane.OK_CANCEL_OPTION,JOptionPane.INFORMATION_MESSAGE); if (result == JOptionPane.OK_OPTION) { System.exit(0); } } //Deserialize publicvoidactionPerformedDeserialize(ActionEvent e){ try(FileInputStream fis = new FileInputStream("file1.data"); ObjectInputStream ois = new ObjectInputStream(fis)) { BinaryLinearEquation ex = (BinaryLinearEquation) ois.readObject(); JOptionPane.showMessageDialog(null,ex.getInfo(),"Deserialized Object",JOptionPane.INFORMATION_MESSAGE); }catch (ClassNotFoundException | IOException exception){ JOptionPane.showMessageDialog(null,exception.getMessage(),"IOException",JOptionPane.WARNING_MESSAGE); } } }
publicclassMainPanelextendsJFrameimplementsActionListener{ CalcPanel panel; JTextArea textArea; BinaryLinearEquation BLEquation; publicMainPanel(){ this.setLayout(new BorderLayout()); panel = new CalcPanel(); panel.button1.addActionListener(this); textArea = new JTextArea(); textArea.setBounds(getX(), getY(), 100, 100); Font font2 = new Font("苹方",Font.PLAIN,20); textArea.setFont(font2); add(panel, BorderLayout.NORTH); add(textArea, BorderLayout.CENTER); setBounds(450, 300, 600, 600); setVisible(true); setTitle("Binary Linear Equation Calculator"); validate();
} //Solve publicvoidactionPerformed(ActionEvent e){ try(FileOutputStream fos = new FileOutputStream("file1.data"); ObjectOutputStream oos = new ObjectOutputStream(fos)) { BLEquation = new BinaryLinearEquation(Double.parseDouble(panel.text1.getText()), Double.parseDouble(panel.text2.getText()), Double.parseDouble(panel.text3.getText())); BLEquation.Solve(); oos.writeObject(BLEquation); }catch (IOException ioException) { ioException.printStackTrace(); JOptionPane.showMessageDialog(null,ioException.getMessage(),"IOException",JOptionPane.WARNING_MESSAGE); } catch (NumberFormatException e1) { JOptionPane.showMessageDialog(null,e1.getMessage(),"Input error!",JOptionPane.ERROR_MESSAGE); this.textArea.setText(BinaryLinearEquation.show); } catch (NonQuadraticEquationException e2) { JOptionPane.showMessageDialog(null,e2.toString(),"Error in the form of the quadratic equation",JOptionPane.ERROR_MESSAGE); } this.textArea.setText(BinaryLinearEquation.show); } }
publicclassGUI{ publicstaticvoidmain(String[] args){ new MainPanel(); } }
publicstaticvoidmain(String[] args){ while (true) { Scanner scanner = new Scanner(System.in); System.out.println("Please input mode:"); System.out.println("[P]Password\t\t\t\t[E]Email\n[I]Citizen ID number\t[Q]Quit"); String mode = scanner.next(); if (mode.equalsIgnoreCase("P")) { Scanner sc = new Scanner(System.in); System.out.println("Please input your password:"); String pwd = sc.nextLine(); boolean isPwdSafe = validatePassword(pwd); if (isPwdSafe) System.out.println("Your password is acceptable."); else System.out.println("Your password does not meet the requirements."); } elseif (mode.equalsIgnoreCase("E")){ Scanner sc = new Scanner(System.in); System.out.println("Please input your email:"); String email = sc.nextLine(); boolean isEmail = validateEmail(email); if (isEmail) System.out.println("Your Email address is acceptable."); else System.out.println("Your Email address is not correct."); } elseif (mode.equalsIgnoreCase("I")){ Scanner sc = new Scanner(System.in); System.out.println("Please input your citizen ID number:"); String id = sc.nextLine(); boolean isIDNum = validateID(id); if (isIDNum) System.out.println("Your citizen ID number is acceptable."); else System.out.println("Your citizen ID number is not correct."); } elseif (mode.equalsIgnoreCase("Q")){ break; } } }
publicclassMain{ publicstaticvoidmain(String[] args){ new Control(); } }
classControlextendsJFrame{ JLabel label1; Control(){ this.setBounds(200,450,400,200); this.setTitle("控制中心"); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Font font = new Font("微软雅黑", Font.PLAIN, 23); label1 = new JLabel("点击本窗口以同时启动三个线程"); label1.setFont(font); add(label1); this.addMouseListener(new MouseAdapter() { @Override publicvoidmouseClicked(MouseEvent e){ actionPerformed(); } }); this.setVisible(true); }
publicvoidactionPerformed(){ myThread ta = new myThread(200,100,0); myThread tb = new myThread(500,100,1); myThread tc = new myThread(800,100,2); ta.setVisible(true); tb.setVisible(true); tc.setVisible(true); }
}
classmyThreadextendsJFrameimplementsRunnable{ int i = 0; int tid; Thread t;
myThread(int i, int j, int shape) { this.tid = shape; this.setBounds(i, j, 300, 300); this.setTitle("Thread "+ shape); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); startThreadA(); }
voidstartThreadA(){ t = new Thread(this); try { t.start(); }catch (Exception e){ System.err.println(e.toString()); } System.out.println("Thread "+this.tid +" has started successfully."); }