2022.7.11
目录
首先是输入-输出 语句
import java.util.Scanner;
public class Hello {
public static void main(String[] args) {
System.out.print("请输入一个正整数n:");
Scanner in=new Scanner(System.in); //新建一个扫描器,扫描你输入的内容。
int n = in.nextInt();
int factor=1;
for(int i=1;i<=n;i++)
{
factor=factor*i;
}
System.out.print("n的阶乘为"+factor);
}
}
稍稍改一下功能:判断素数
import java.util.Scanner;
public class Hello {
public static void main(String[] args) {
System.out.print("请输入一个正整数n:"+"\n");
Scanner in=new Scanner(System.in);
int n=in.nextInt();
if (!(n>0))
{
System.out.print("请重新输入!"+"\n");
}
boolean isPrime=true; //布尔值
for(int i=2;i<n;i++)
{
if(n%i==0)
{
isPrime=false;
System.out.print(n+"可以整除,i="+i+"\n");
break;
}
}
if(isPrime)
{
System.out.println(n+"是素数");
}
else
{
System.out.println(n+"是非素数");
}
}
}
2022.7.12
第五章 初识数组
public class Hello {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
double sum=0;
int cnt=0;
int[] numbers=new int[5]; //声明并分配一个长度为 5 的 int 类型数组
int x=in.nextInt();
while (x!=-1)
{
numbers[cnt]=x;
sum+=x;
cnt++;
x=in.nextInt();
}
if (cnt>0)
{
double average=sum/cnt;
for(int i=0;i<cnt;i++)
{
if (numbers[i]>average)
{
System.out.println(numbers[i]);
}
}
System.out.println(sum/cnt);
}
}
}
注意:每个类型都有他们各自的包裹类型。
boolean---Boolean
char---Character
int---integer
double---Double
System.out.println(Integer.MAX_VALUE);
//整数int的范围-2147483648~2147483647;因此输出2147483647
static boolean isLowerCase(char ch)
//判断是否是小写字母,输出布尔值0/1
System.out.println(Character.isDigit("1")); //输出true
//以下是Math类型
System.out.println(Math.abs(-12)); //12
System.out.println(Math.round(-12.645)); //-13
System.out.println(Math.random()); //0-1内任意实数
System.out.println(Math.pow(a,b)); //a的b次方
第六章 字符串
String s=new String("Hello");
System.out.println(s+" World!"); //输出Hello World!
下面是比较两个字符串
if(input.equals("bye"))
//比较内容是否相同
if(input=="bye")
//比较是否为同一个
或者重写equals方法 (重写前输出的是包名类名@地址值) 实际是比较地址是否相同
//Student.java
public boolean equals(Object obj){
if(obj==null){
return false;
}
if(obj==this){
return true;
}
if(obj instanceof Person){ //使用向下转型(强转)成Person类
Person p=(Person)obj;
boolean b = this.name.equals(p.name) && this.age==p.age;
return b;
}
return false;
}
student stu1=new Student(name:"张三",age:23);
student stu1=new Student(name:"张三",age:23);
system.out.println(stu1.equals(stu2)); //没有重写前为false,重写后为true
得到子串:s.substring(2,5); //从第二个开始到第五个之前的字符串
寻找字符的位置:s.indexof(c)或者s.indexof(c,n) s.lastIndexof(c) 从右边开始
第七、八章 函数的调用、类和对象
对象识别
package display;
//下面是时钟24小时
public class Display{
private int value=0;
private int limit=0;
public Display(int limit) {
this.limit=limit;
//作用域是 private,因此在类外部无法对它们的值进行设置。为了解决这个问题,可以为类添加一个构造方法,然后在构造方法中传递参数进行修改
}
public void increase(){
value++;
if (value==limit) {
value=0;
}
}
public int getValue() {
int i;
return value;
}
public static void main(String[] args) {
Display d=new Display(24);
for(;;) {
d.increase();
System.out.println(d.getValue());
}
}
}
构造函数:若有一个成员函数的名字和类的名字完全相同,则在创建这个类的每一个对象的时候会自动调用这个函数。 这个函数没有返回类型!
函数重载-----一个类里的同名但参数表不同的函数构成重载关系。
对象=属性(数据)+服务(功能)
私有private:只有类内部可以访问 类内部指类的成员函数和定义初始化。
公有public:任何人都可以访问 任何类的函数或定义初始化中可以使用。
静态变量static:静态变量可以用于引用所有对象的公共属性
静态变量将只获取一次内存,如果任何对象更改静态变量的值,它将保留其值,所有实例均可访问同一变量值。
泛型类
package notebook;
import java.util.ArrayList;
class Value{
private int i;
public void set(int i);{this.i=i;}
public void get(){return i;}
}
public class Notebook{
private ArrayList<String> notes=new ArrayList<String>(); //ArrayList类是一个可以动态修改的数组,与普通数组的区别就是它是没有固定大小的限制,我们可以添加或删除元素。
public void add(String s){
notes.add(s);
}
public void add(String s,int location){
notes.add(location,s)
}
public int getSize(){
return notes.size();
}
public String getNote(int index){
return notes.get(index);
}
public String removeNote(int index){
return notes.remove(index);
}
public String[] list(){
int[] ia=new int[10];
string[] a=new String[notes.size()];
notes.toArray(a); //转化为array
return a;
}
public static void main(String[] args)
{
String[] a=new String[10];
for(int i=0;i<a.length;i++){
a[i]=""+i;
}
System.out.println(ia[0]+2);
System.out.println(a[0].length());
}
{
ArrayList<String> a=new ArrayList<String>();
a.add("first");
a.add("second");
a.add("first");
for(String s:a){
//for-each for (type var : array)<==>for (int i=0; i<arr.length; i++)
System.out.println(s); //first second first
}
System.out.println("-----------");
Hashset<String> s=new Hashset<String>(); //
s.add("first");
s.add("second");
s.add("first");
for(String k:s){ //for-each
System.out.println(k); //second first
}
}
}
HashMap类
HashMap<key,value>映射
public class Coin() {
private HashMap<Integer,String> coinnames=new HashMap<Integer,String>();
public coin() {
coinnames.put(1, "penny");
//......
}
public String getName(int amount) {
if(coinnames.containsKey(amount))
return coinnames.get(amount);
else
return "NOT FOUND";
}
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int amount=in.nextInt();
Coin coin=new Coin();
String name=coin.getname(amount);
System.out.println(name);
}
}
继承
CD.java
package home;
public class CD extends Item{ //继承父类Item
private String title;
private String artist;
private int numofTracks;
private int playingTime;
private boolean gotit=false;
private String comment;
public CD(String title,String artist,int numofTracks,int playingTime,String comment){
//super(); 不写这一行也会调用默认不带参数的初始化父类!
this.title=title;
this.artist=artist;
this.numofTracks=numofTracks;
this.playingTime=playingTime;
this.comment=comment;
}
}
Database.java
package home;
import java.util.ArrayList;
public class Database{
private ArrayList<Item> listItem=new ArrayList<Item>();
public void add(Item item){
listItem.add(item);
}
public void list(){
for(Item item:listItem){
item.print();
}
}
......
}
Item.java
//protected 可以保证父类的对象子类也能访问到 如protected String title
package home;
public class Item{
private String title;
public Item(){
super();
this.title=title;
}
public void print(){
System.out.println("Item");
}
}
同时在CD.java的初始化:super(title); //this.title=title;
同时,在子类调用父类的函数时,应该写为super.xxx();
多态变量
java的对象变量是多态的,它们能保存不止一种类型的对象。
当把子类的对象赋给父类的变量时,就发生了向上造型。
造型cast
java不存在对象对对象的赋值。父类的对象不能赋值给子类的变量。但子类的对象能赋值给父类的变量。可以用造型c = (car) v;
类型转换和造型有着本质不同;例如:int i=(int) 10.2; 强制转换为10
造型的对象本质并没有改变。
object类
是所有类的父类。其中toString就是object类中的方法。
注:一个类若重写了toString方法,则按重写的方式打印。若没有重写,则按默认的方式打印对象的地址值。(@Override)
toString用于返回以一个字符串表示的 Number 对象值。
用封装降低耦合,减少代码重复。(类与类之间的关系称为耦合)
StringBuffer 追加字符串 对象.append(String str)
import java.util.Scanner;
public class Testl9 {
public static void main(String[] args) {
StringBuffer sys = new StringBuffer("校内课程管理");
System.out.println("欢迎进入《"+sys+"》系统");
// 声明课程名称字符串
StringBuffer courseName = new StringBuffer();
System.out.println("请录入本期的五门必修课名称:");
Scanner input = new Scanner(System.in);
// 循环接收控制台输入的字符串
String name = "";
for (int i = 0;i < 5;i++) {
name = input.next();
courseName.append(name+"\t");
if(i == 4) {
System.out.println("录入完毕!");
}
}
System.out.println("本学期的必修课程有:\n"+courseName);
}
以框架+数据提高可扩展性
抽象函数/抽象类:表达概念而无法实现的函数/类
面向接口的编程方式
接口(interface)是抽象方法和常量值的定义的集合。一个类通过继承接口的方式,从而来继承接口的抽象方法。
/* 文件名 : Animal.java */
interface Animal {
public void eat();
public void travel();
}
设计程序时先定义接口,再实现类。
任何需要在函数间传入传出的一定是接口而不是具体的类。
细胞自动机
package cellmachine;
import javax.swing.JFrame;
import cell.Cell;
import field.View;
import field.Field;
public class CellMachine {
public static void main(String[] args) {
Field field = new Field(30,30);
for( int row = 0; row<field.getHeight(); row++ ) {
for( int col = 0; col<field.getWidth(); col++ ) {
field.place(row, col, new Cell());
}
}
for( int row = 0; row<field.getHeight(); row++ ) {
for( int col = 0; col<field.getWidth(); col++ ) {
Cell cell = field.get(row, col);
if( Math.random() < 0.2 ) {
cell.reborn();
}
}
}
View view = new View(field);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setTitle("Cells");
frame.add(view);
frame.pack();
frame.setVisible(true);
for( int i = 0; i<1000; i++ ) {
for( int row = 0; row<field.getHeight(); row++ ) {
for( int col = 0; col<field.getWidth(); col++ ) {
Cell cell = field.get(row, col);
Cell[] neighbour = field.getNeighbour(row, col);
int numOfLive = 0;
for( Cell c : neighbour ) {
if( c.isAlive() ) {
numOfLive++;
}
}
System.out.print("["+row+"]"+"["+col+"]:");
System.out.print(cell.isAlive()?"live":"dead");
System.out.print(":"+numOfLive+"-->");
if( cell.isAlive() ) {
if( numOfLive<2 || numOfLive>3 ) {
cell.die();
System.out.print("die");
}
}else if( numOfLive == 3 ) {
cell.reborn();
System.out.print("reborn");
}
System.out.println();
}
}
System.out.print("UPDATE");
frame.repaint();
try {
Thread.sleep(200);
}catch( InterruptedException e) {
e.printStackTrace();
}
}
}
}
//cell.java
package cell;
import java.awt.Graphics;
public class Cell {
private boolean alive = false;
public void die() { alive = false; }
public void reborn() { alive = true; }
public boolean isAlive() { return alive; }
public void draw(Graphics g, int x, int y, int size) {
g.drawRect(x, y, size, size);
if( alive ) {
g.fillRect(x, y, size, size);
}
}
}
//field.java
package field;
import java.awt.Dimension;
public class View extends JPanel {
private static final long serialVersionUID = -5258995676212660595L;
private static final int GRID_SIZE = 16;
private Field theField;
public View(Field field) {
theField = field;
}
@Override
public void paint(Graphics g) {
super.paint(g);
for( int row = 0; row<theField.getHeight(); row++ ) {
for( int col = 0; col<theField.getWidth(); col++ ) {
Cell cell = theField.get(row, col);
if( cell != null) {
cell.draw(g, col*GRID_SIZE, row*GRID_SIZE, GRID_SIZE);
}
}
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(theField.getWidth()*GRID_SIZE+1, theField.getHeight()*GRID_SIZE+1);
}
public static void main(String[] args) {
Field field = new Field(10,10);
for( int row = 0; row<field.getHeight(); row++ ) {
for( int col = 0; col<field.getWidth(); col++ ) {
field.place(row, col, new Cell());
}
}
View view = new View(field);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setTitle("Cells");
frame.add(view);
frame.pack();
frame.setVisible(true);
}
}
算法练习
1. 爬楼梯问题(力扣70题)
class Solution{
private HashMap<Integer,Integer> step=new HashMap<Integer,Integer>();
public int climbstairs(int n){
if(n==1)
return 1;
if(n==2)
return 2;
if(null!=step.get(n))
return step.get(n);
else{
int result=climbstairs(n-1)+climbstairs(n-2);
step.put(n,result);
return result;
}
}
}
/*
f(n)=1,n=1;
f(n)=2,n=2;
f(n)=f(n-1)+f(n-2),n>=3;
*/
2. 两数之和(力扣第1题)
//常规方法(用数组) 时间复杂度为O(n^2)
class Solution{
public int[] twosum(int[] nums,int target){
int[] result=new int[2];
for(int i=0;i<nums.length;i++){
for(int j=i+1;j<nums.length;j++){
if(nums[i]+nums[j]==target){
result[0]=i
result[1]=j //返回数组下标
return result;
}
}
}
return result;
}
}
//进阶方法(HashMap) get/put 时间复杂度为O(n)
public int[] twosum(int[] nums,int target){
Map<Integer,Integer> storeMap=new HashMap<Integer,Integer>(nums.length,1);
int[] result=new int[2];
for(int i=0;i<nums.length;i++){
int another=target-nums[i];
Integer anotherIndex=storeMap.get(another);
if(null!=anotherIndex){
result[0]=anotherIndex;
result[1]=i;
break;
}
else{
storeMap.put(nums[i],i);
}
}
}
3. 合并两个有序数组(力扣第88题)
注意:Array.sort的Quicksort时间复杂度为O((m+n)log(m+n))
//Array.sort的Quicksort时间复杂度为O((m+n)log(m+n))
//好处:代码简单;缺点:效率低
class Solution{
public void merge(int[] num1,int m,int[] num2,int n){
for(int i=0;i<n;++i)
num1[m+i]=num2[i];
Arrays.sort(num1);
}
}
//效率较高 双指针
class Solution{
public void merge(int[] num1,int m,int[] num2,int n){
int k=m+n;
int[] temp=new int[k];
for(int index=0,num1index=0,num2index=0;index<k;index++){
if(num1index>=m){
temp[index]=num2[num2index++];
}
else if(num2index>=n){
temp[index]=num1[num1index++];
}
else if(num1[num1index]>=num2[num2index]){
temp[index]=num2[num2index++];
}
else{
temp[index]=num1[num1index++];
}
}
for(int i=0;i<k;i++){
num1[i]=temp[i];
}
}
}
4. 移动零 (力扣第283题)
class Solution {
public void moveZeroes(int[] nums) {
if(nums==null){
return;
}
int j=0;
for(int i=0;i<nums.length;i++){
if(nums[i]!=0)
nums[j++]=nums[i];
}
for(int i=j;i<nums.length;i++){
nums[i]=0;
}
}
}
5. 找到所有数组中消失的数字 (力扣第448题)
传统方法超时。
6. 合并两个有序链表(力扣21题)
//时间复杂度:O(m+n)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution { //双指针+循环
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if(list1==null) return list2;
if(list2==null) return list1;
ListNode resultnode=new ListNode(0);
ListNode p=resultnode;
while(list1!=null&&list2!=null){
if(list1.val<list2.val){
p.next=list1;
list1=list1.next;
}
else{
p.next=list2;
list2=list2.next;
}
p=p.next;
}
if(list1!=null)
p.next=list1;
if(list2!=null)
p.next=list2;
return resultnode.next;
}
}
也可以用递归做
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null)
return head;
ListNode currentNode=head;
while(null!=currentNode.next){
if(currentNode.next.val==currentNode.val){
currentNode.next=currentNode.next.next;
}
else{
currentNode=currentNode.next;
}
}
return head;
}
}
7. 环形链表 (力扣141题 )
快慢双指针解决
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null) return false;
ListNode slow=head,fast=head;
while(fast.next!=null&&fast.next.next!=null){
fast=fast.next.next;
slow=slow.next;
if(slow==fast)
return true;
}
return false;
}
}
8.环形链表 II (力扣142题 )
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head==null) return null;
boolean loopexist=false;
ListNode slow=head,fast=head;
while(fast.next!=null&&fast.next.next!=null){
fast=fast.next.next;
slow=slow.next;
if(slow==fast){
loopexist=true;
break;
}
}
if(loopexist){
slow=head;
while(slow!=fast){
fast=fast.next;
slow=slow.next;
}
return slow;
}
return null;
}
}
本文是关于Java开发的学习进阶,涵盖了数组、字符串、函数、类和对象的基本概念,如泛型类、HashMap、继承、多态等。通过力扣题目进行算法练习,包括爬楼梯、两数之和、合并有序数组等,提升编程能力。
642

被折叠的 条评论
为什么被折叠?



