Java-11.19

Exception的分类:异常类
    子类:
    1)编译时期异常:只要不是RuntimeException中的异常都属于编译时期异常:比如:IOException(IO流中的),ParseException(解析异常)
    调用者必须处理,不处理不行,需要编译通过
    2)运行时期异常:RuntimeException
    可能由于我们代码的逻辑不够严谨导致的问题举例,NullPointerException:空指针异常!   需要个对象进行非空判断,来防止该问题的出现!


package org.lemon.Exception;

/**
 * @author zhaojiangbo
 *Exception的分类:异常类
 *  		
 *  	1.编译时期异常:只要不是RuntimeException中的异常都属于编译时期异常
 *     eg:IOException(IO流中的),ParseException(解析异常)
 *  	
 *  	2.运行时期异常:RuntimeException
 *  		NullPointerException:空指针异常! (需要对象进行非空判断,来防止该问题的出现)
 */
public class ExceptionDemo {
   public static void main(String[] args) {
	int a = 1; 
	int b = 0;
	System.out.println(a/b);
}
}

处理异常分为两种方式:
   1.标准格式:try...catch...finally:捕获异常!
   2.throws 抛出异常
  

package org.lemon.Exception;

/**
 * @author zhaojiangbo
 *处理异常方式
 *  1.标准格式:try...catch...finally:捕获异常
 *  2.throws 抛出异常
 * 经常使用的格式:
 * try{
 * 		}catch(异常类名 变量名){
 * 	输出语句处理}
 */
public class ExceptionDemo2 {
	public static void main(String[] args) {
		int a = 1;
		int b = 0;
		try {
			System.out.println(a / b);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("商不能为0");
		}
	}
}

多个异常处理

package org.lemon.Exception;

/**
 * @author zhaojiangbo
 *多个异常存在
 *
 * 		try{
 *			可能会出现问题的多个语句
 * 		}catch(异常类名1 变量名){
 * 				输出语句处理
 * 		}catch(异常类名2 变量名){
 * 				输出语句处理
 *		}
 */
public class ExceptionDemo3 {
	public static void main(String[] args) {
		int a = 1;
		int b = 0;
		int[] arr = { 1, 2, 3, 4, 5 };

		try {
			System.out.println(a / b);

		} catch (ArithmeticException e) {
			System.out.println("商不能是0");
		}
		try {
			System.out.println(arr[5]);
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("不能超过最大索引");
		}
	}
}

新的处理方式:

 

package org.lemon.Exception;

/**
 * @author zhaojiangbo
 *try{
 * 		可能会出现问题的代码
 * 		....
 * 		...
 * 	}catch(异常类名1 | 异常类名2 ....变量名){
 * 		处理异常...
 * }
 * 
 * 注意事项:
 *    1.针对多个异常类名之间是一种平级关系
 * 	  2.这种格式在实际开发中,虽然有多个异常,但是针对具体的异常给出具体的处理!
 */
public class ExceptionDemo4 {
	public static void main(String[] args) {
	int a = 1;
	int b = 0;
	int [] arr = {1,2,3,4,5} ;
	try{
		System.out.println(a / b);
		System.out.println(arr[5]);
	}catch(ArithmeticException|ArrayIndexOutOfBoundsException e){
		System.out.println("出现问题");
		e.printStackTrace();
	}
}
}


package org.lemon.Exception2;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author zhaojiangbo
 * 编译时期异常:Java程序必须给予处理,否则编译不通过(必须显示处理)
 * 运行时期异常:可以处理,也可以进行显示处理
 */
public class ExceptionDemo {
	public static void main(String[] args) {

		int a = 1;
		int b = 0;
		if (b != 0) {
			System.out.println(a / b);
		}
		method();
	}

	// String日期"文本"格式---->Date格式: 解析
	private static void method() {
		String s = "2017-11-22";
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date date = simpleDateFormat.parse(s);
			System.out.println(date);
		} catch (Exception e) {
			System.out.println("出现解析异常");
		}

	}
}


常用的方法:
   public String getMessage()   消息字符串
   public String toString()
   描述字符串:
    1.当前类的全路径名称(指的是当前异常类名所在的包的全路径名称)
    2.  ": "(冒号和一个空格)
  
   public void printStackTrace():
   该方法是里面包含了消息字符串以及当前出现错误的异常的时候所描述哪个包下以及代码中具体的错误出现第几行
   返回值是void,也就直接在控制台输出

package org.lemon.Exception2;

import java.text.SimpleDateFormat;
import java.util.Date;


public class ExceptionDemo2 {
   public static void main(String[] args) {
	String s = "2017-11-22";
	SimpleDateFormat sdf = new SimpleDateFormat();
	try {
		Date date = sdf.parse(s);
		System.out.println(date);
	}catch(Exception e) {
		System.out.println(e.getMessage());
		System.out.println(e.toString());
		e.printStackTrace();
		e.printStackTrace();
	}
}
}

异常处理第二种方式:
   throws:抛出异常

package org.lemon.Exception2;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author zhaojiangbo
 *异常处理第二种方式:
 * 		throws:抛出异常
 *      在方法声明上抛出异常,由于,编译时期异常,调用者必须要处理
 */
public class ExceptionDemo3 {
	public static void main(String[] args) throws ParseException, ArithmeticException {

		// 抛出异常,必须处理
		method();

		try {
			method2();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// throw
	private static void method2() throws Exception {
		int a = 10;
		int b = 0;
		if (b == 0) {
			System.out.println(a / b);
			throw new ArithmeticException();// 跟的异常对象
		} else {
			System.out.println("没有问题");
		}
	}

	private static void method() throws ParseException {
		String s = "2017-11-19";

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = sdf.parse(s);

		System.out.println(date);

	}
}

finally经常用在数据库中或者IO流中,用来释放资源的
   finally中的代码一定会执行.
  
   finally中的不执  就是Jvm退出了---------->System.exit(0) ;

package org.lemon.ExceptionFinally;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author zhaojiangbo
 */
public class ExceptionDemo {
  public static void main(String[] args) {
	String s = "2017-11-22";
	SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
	try {
		Date date = simpleDateFormat.parse(s);
		System.out.println(date);
	}catch(Exception e) {
		//e.printStackTrace();
		System.out.println("解析有问题");
		//System.exit(0);
	}finally {
		System.exit(0);
		System.out.println("代码定会执行,除非Jvm退出");
	}
}
}

如果catch里面有return语句,那么finally中的代码会执行;在return 前执行!

package org.lemon.ExceptionFinally;

/**
 * @author zhaojiangbo
 */
public class ExceptionDemo2 {
	public static void main(String[] args) {
		System.out.println(getInt());
	}

	private static int getInt() {
		int a = 10;
		try {
			System.out.println(a / 0);
			a = 20;
		} catch (ArithmeticException e) {
			a = 30;
			return a;
            } finally {
			a = 40;
		}
		return a;
     }
}
//结果是  40  finally中代码定执行  在return之前执行

  自定义一个异常类,继承自Exception或者继承自RuntimeException

package org.lemon.myException;

/**
 * @author zhaojiangbo
 *      自定义一个类,继承自Exception或者继承自RuntimeException
 */
public class MyException extends Exception{
    public MyException(){
		}
    public MyException(String message){
		super(message) ;
	}
}

package org.lemon.myException;

import java.util.Scanner;

public class Student {
	public static void main(String[] args) {

		// 创建键盘录入对象
		Scanner sc = new Scanner(System.in);

		System.out.println("请输入一个分数:");
		int score = sc.nextInt();

		// 创建Teacher对象
		Teacher t = new Teacher();
		try {
			t.check(score);
		} catch (MyException e) {
			e.printStackTrace();
		}
	}
}

package org.lemon.myException;

public class Teacher {

	public void check(int score) throws MyException {
		// TODO Auto-generated method stub
		if (score > 100 || score < 0) {
			throw new MyException("分值在0到100之间");
		} else {
			System.out.println("分值是正常范围...");
		}

	}

}

File类 描述文件或者目录(文件夹)的路径的抽象表现形式

  构造方法:
       public File(String pathname):给定路径名以字符串来表示当前这个文件或者文件夹(开发中推荐使用第一种构造方法)
       public File(String parent,String child)根据 parent 路径名字符串和 child 路径名字符串创建一个新 File对象
       public File(File parent, String child)根据 parent 抽象路径名和 child 路径名字符串创建一个新 File 实例

package org.lemon.File;

import java.io.File;
import java.io.IOException;

/**
 * @author Lemon
 *File  用来描述文件或者目录(文件夹)的路径的抽象表现形式
 *
 * 要表示当前计算机d盘下一个demo文件夹中的一个a.txt文件    File file = new File("D:\\demo\\a.txt") ;
 */
public class FileDemo {
   public static void main(String[] args) throws IOException {
	File file = new File("D:\\demo");
	System.out.println("mkdir:"+file.mkdir());
	File file2 = new File("D:\\demo\\abc.txt");
	System.out.println("createNewFile:"+file2.createNewFile());
	
	File file3 = new File("D:\\a\\b\\c\\d");
	System.out.println("mkdir:"+file3.mkdir());
	
	File file4 = new File("abc.txt");//没有带盘符,默认到当前项目下创建了文件
	System.out.println("mkdir:"+file4.mkdir());
}
}

创建有关的成员方法:
    public boolean mkdir()创建此抽象路径名指定的目录(文件夹)。
            如果当前某个盘符下已经有了这个目录(文件夹),不会在创建了.
    public boolean createNewFile():创建文件的,如果已经有这个文件了,不在创建,并且该方法本身就会编译时期异常IOExceptio     throws IOException
    public boolean mkdirs()创建此抽象路径名指定的目录,包括所有必需但不存在的父目录。(创建文件夹,文件夹不存在,才开始创建)
       
     没有带盘符,默认到当前项目下创建文件或者文件夹..


   public boolean delete()删除此抽象路径名表示的文件或目        删除不能删除带有文件或者文件夹的目录
   注意事项:
      删除的方法不能删除带有目录或者文件的文件夹
      删除多个目录,必须逐一删除!

package org.lemon.File;

import java.io.File;

/**
 * @author Lemon
 *public boolean delete()删除此抽象路径名表示的文件或目录
 * 		                               不能删除带有文件或者文件夹的目录 
 */
public class FileDemo2 {
    public static void main(String[] args) {
		File file = new File("abc.txt");
		System.out.println("delete:"+file.delete());
		//删除多个目录,必须逐一删除
		File file2 = new File("a\\b\\c");
		System.out.println("delete:"+file2.delete());
		File file3 = new File("a\\b");
		System.out.println("delete:"+file3.delete());
		File file4 = new File("a");
		System.out.println("delete:"+file4.delete());
		
	}
}

File类中的重命名功能:
      public boolean renameTo(File dest)重新命名此抽象路径名表示的文件。
    
       1.使用这个功能:当两个抽象路径一致,那么只是重命名
       2.当这两个抽象路径不一致,有剪切并且改名了...

package org.lemon.File;

import java.io.File;

/**
 * @author Lemon
 *public boolean renameTo(File dest)       重新命名此抽象路径名表示的文件。
 *      1.当两个抽象路径一致,那么只是重命名
 * 		2.当这两个抽象路径不一致,有剪切并且改名
 */
public class FileDemo3 {
   public static void main(String[] args) {
	File file = new File("疾风剑豪.jpg");
	File file2 = new File("压缩.jpg");
	boolean renameTo = file.renameTo(file2);
	
	File file3 = new File("压缩.jpg");
	File file4 = new File("D:\\疾风剑豪.jpg");
	file3.renameTo(file4);
}
}

File类中的判断功能:
   public boolean isDirectory():判断是否是文件夹  经常用到
   public boolean isFile():判断是否是一个标准文件  经常用到
   public boolean canRead():判断是否可读
   public boolean canWriter():判断是否可写
   public boolean isHidden():判断是否是隐藏文件
   public boolean isAbsolute():判断次路径名是否是绝对路径


package org.lemon.File;

import java.io.File;

/**
 * @author Lemon
 *File类中的判断功能:
 *		public boolean isDirectory():判断是否是文件夹		
 *		public boolean isFile():判断是否是一个标准文件		
 */
public class FileDemo4 {
     public static void main(String[] args) {
		
    	 File file = new File("abc.txt");
    	 System.out.println(file.isDirectory());
    	 System.out.println(file.isFile());
    	 System.out.println(file.canRead());
    	 System.out.println(file.canWrite());
    	 System.out.println(file.isAbsolute());
    	 System.out.println(file.isHidden());
	}
}

File类中的获取功能:
        public File getAbsolutePath():获取当前文件或者文件夹绝对路径
        public String getPath():获取相对路径
        public long length()返回由此抽象路径名表示的文件的长度
        public long lastModified()返回此抽象路径名表示的文件最后一次被修改的时间
        public String getName():获取名称
package org.lemon.File;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * @author Lemon
 *   File类中的获取功能
 */
public class FileDemo5 {
   public static void main(String[] args) {
	File file = new File("abc.txt");
	System.out.println(file.getAbsolutePath());
	System.out.println(file.getPath());
	System.out.println(file.length());
	System.out.println(file.lastModified());
	System.out.println(file.getName());
	
	
	//Date---->String"日期文本格式"
	Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat();
    String s = sdf.format(date);
    System.out.println(s);
	
}
}

File类的高就获取功能:
     public String[] list():返回对象是一个字符串数组,当前哪个一盘符下的所有的文件以及文件夹的字符串名称数组
     public File[] listFiles():返回对象是一个File数组,当前哪个盘下的所有的文件以及文件夹的File数组

package org.lemon.File;

import java.io.File;

/**
 * @author Lemon
 *需求:获取e盘下所有的文件夹以及文件的字符串名称数组
 */
public class FileDemo6 {
  public static void main(String[] args) {
	File file = new File("D:\\");
	String[] str = file.list();
	if(str!=null) {
		for(String s : str) {
			System.out.println(s);
		}
	}
	
	File[] listFiles = file.listFiles();
	if(listFiles!=null) {
		for(File f : listFiles) {
			System.out.println(f);
		}
	}
}
}


package org.lemon.File;

import java.io.File;

/**
 * @author Lemon
 * 判断D盘目录下是否有后缀名为.jpg的文件,如果有,就输出此文件名称
 */
public class FileTestDemo {
   public static void main(String[] args) {
	File file = new File("D:\\");
	File[] listArray = file.listFiles();
	if(listArray!=null) {
		for(File f :listArray) {
			if(file.isFile()) {
				if(file.getName().endsWith(".jpg")) {
					System.out.println(f.getName());
				}
			}
		}
	}
}
}


package org.lemon.File;

import java.io.File;
import java.io.FilenameFilter;

/**
 * @author Lemon
 *判断D盘目录下是否有后缀名为.jpg的文件,如果有,就输出此文件名称
 *
 *匿名内部类方式
 */
public class FileTestDemo2 {
    public static void main(String[] args) {
		File file = new File("D:\\");
String[] strArray = file.list(new FilenameFilter() {
			
			@Override
			public boolean accept(File dir, String name) {
//				return false;
				
				return new File(dir,name).isFile() && name.endsWith(".jpg") ;
			}
		});
		
		//遍历字符串数组
		for(String s : strArray){
			System.out.println(s);
		}
	}
}


针对输出流中写数据的方法:
       public abstract void write(int b):将指定的字节写入到输出流中
       public void write(byte[] b):将指定的字节数组写入到输出流中
       public void write(byte[] b, int off,int len):将字节数组的一部分写入到输出流中

package org.lemon.IO;

import java.io.IOException;
import java.io.FileOutputStream;

public class FileOutputStreamDemo {
   public static void main(String[] args) throws  IOException {
	FileOutputStream fos = new FileOutputStream("fos.txt");
	fos.write(97);
	fos.write(65);
	
	//public void write(byte[] b):将指定的字节数组写入到输出流中
	byte[] bys = {97,98,99,100,101} ;
	fos.write(bys) ;
	
	fos.write(bys, 1, 3) ;
	
	//关闭资源
	fos.close() ;
}
}

    需要写入换行符号,每一个系统他们对应IO这块换行符号是不一样的
    windows操作系统:换行符号:\r\n
    Linux操操作系统:\n
    Mac操作系统:\r

  给文件追加写入数据
   public FileOutputStream(File file,boolean append):第二个参数设置为true,表示写入文件的末尾处

package org.lemon.IO;


import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author Lemon
 *给文件追加写入数据
 * 	public FileOutputStream(File file,boolean append):第二个参数设置为true,表示写入文件的末尾处
 */
public class FileOutputStreamDemo2 {
   public static void main(String[] args) throws IOException {
	   FileOutputStream fos = new FileOutputStream("fos.txt",true) ;
		
		//写数据
		for(int x = 0 ; x <10 ; x ++){
			fos.write(("helo"+x).getBytes()) ;
		//换行符号
			fos.write("\r\n".getBytes());
		}
		//关闭资源
		fos.close() ;
}
}

IO流中加入异常操作

package org.lemon.IO;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author Lemon
 *    IO流中加入异常操作
 */
public class FileOutputStreamDemo3 {
   public static void main(String[] args) {
	   FileOutputStream fos = null ;
		
		try {
			fos = new FileOutputStream("fos.txt") ;
		//写数据
			fos.write("woaini".getBytes()) ;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(fos !=null){
				try {
					fos.close() ;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
}
}

IO流:设备和设备之间的数据传输
    设备和设备指的是:硬盘和内存之间的数据传输
  
   IO流的分类:
    按流的方向分:
                         输入流:读数据的
                         输出流:写数据的
  
    按数据类型分:
            (字节流)
                        字节输入流:InputStream
                        字节输出流:OutputStream
            (字符流)
                        字符输入流:Reader
                        字符输出流:Writer


package org.lemon.IO;


import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author Lemon
 * 需求:输出一个文本文件,给文本文件中写一句话:hello,IO,Im'coming...
 */
public class IODemo {
    public static void main(String[] args) throws IOException {
		FileOutputStream fos = new FileOutputStream("fos.txt");
		
		fos.write("hello,IO,Im'coming...".getBytes());
		
		fos.close();
		//不能再写入了
	}
}










  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,根据您的需求,我为您编写了如下代码。 首先,我们需要加载所需的包和数据: ```R library(xlsx) library(randomForest) library(keras) library(e1071) data_path <- "D:/Desktop/002362hwkj.xlsx" stk_data <- read.xlsx(data_path, sheetIndex = 1) ``` 然后,我们将数据按时间升序排列,并将日期列转化为日期格式: ```R stk_data$Date <- as.Date(stk_data$Date) stk_data <- stk_data[order(stk_data$Date),] ``` 接下来,我们将数据划分为训练集和测试集。由于您没有指定测试集的时间范围,这里我将最后一年的数据作为测试集: ```R train_data <- stk_data[1:(nrow(stk_data)-252),] test_data <- stk_data[(nrow(stk_data)-251):nrow(stk_data),] ``` 然后,我们为每个模型准备数据。对于随机森林和支持向量机,我们只需要选择需要的特征并将其转化为矩阵格式。对于长短期记忆神经网络,我们需要将数据转化为时间序列格式,并将其标准化。 ```R # 随机森林和支持向量机 train_rf_svm <- train_data[,c("Open", "Close", "Volume")] train_rf_svm <- data.matrix(train_rf_svm) test_rf_svm <- test_data[,c("Open", "Close", "Volume")] test_rf_svm <- data.matrix(test_rf_svm) # 长短期记忆神经网络 train_lstm <- train_data[,c("Close")] train_lstm <- data.matrix(train_lstm) scaler <- preProcess(train_lstm, method = c("scale", "center")) train_lstm <- predict(scaler, train_lstm) test_lstm <- test_data[,c("Close")] test_lstm <- data.matrix(test_lstm) test_lstm <- predict(scaler, test_lstm) train_lstm <- array(train_lstm, dim = c(nrow(train_lstm), 1, 1)) test_lstm <- array(test_lstm, dim = c(nrow(test_lstm), 1, 1)) ``` 接下来,我们分别训练随机森林、长短期记忆神经网络和支持向量机,并对测试集进行预测: ```R # 随机森林 rf_model <- randomForest(train_rf_svm[,1:2], train_rf_svm[,3], ntree = 500) rf_pred <- predict(rf_model, test_rf_svm[,1:2]) # 长短期记忆神经网络 lstm_model <- keras::keras_model_sequential() lstm_model %>% layer_lstm(units = 50, input_shape = c(1, 1)) %>% layer_dense(units = 1) lstm_model %>% compile(loss = 'mean_squared_error', optimizer = 'adam') lstm_model %>% fit(train_lstm[,1:1,], train_lstm[,1,], epochs = 100, batch_size = 32) lstm_pred <- predict(lstm_model, test_lstm)[,1] # 支持向量机 svm_model <- svm(train_rf_svm[,1:2], train_rf_svm[,3], kernel = "linear") svm_pred <- predict(svm_model, test_rf_svm[,1:2]) ``` 最后,我们计算三个模型的准确率,并绘制时间序列图: ```R # 计算准确率 rf_accuracy <- sum(rf_pred == test_rf_svm[,3])/nrow(test_rf_svm) lstm_accuracy <- sum(round(lstm_pred) == test_lstm[,1])/nrow(test_lstm) svm_accuracy <- sum(svm_pred == test_rf_svm[,3])/nrow(test_rf_svm) cat("随机森林准确率:", rf_accuracy, "\n") cat("LSTM准确率:", lstm_accuracy, "\n") cat("支持向量机准确率:", svm_accuracy, "\n") # 绘制时间序列图 par(mfrow=c(3,1)) plot(test_data$Date, test_data$Close, type = "l", col = "blue", xlab = "", ylab = "Price") lines(test_data$Date, rf_pred, col = "red") legend("bottomright", legend = c("Actual", "Predicted"), col = c("blue", "red"), lty = c(1, 1)) plot(test_data$Date, test_data$Close, type = "l", col = "blue", xlab = "", ylab = "Price") lines(test_data$Date, round(lstm_pred), col = "red") legend("bottomright", legend = c("Actual", "Predicted"), col = c("blue", "red"), lty = c(1, 1)) plot(test_data$Date, test_data$Close, type = "l", col = "blue", xlab = "", ylab = "Price") lines(test_data$Date, svm_pred, col = "red") legend("bottomright", legend = c("Actual", "Predicted"), col = c("blue", "red"), lty = c(1, 1)) ``` 注意:由于数据未提供证券代码,代码中的模型训练和预测均基于数据的 Close 列。如果您的数据中包含多个证券的交易数据,请修改代码以适配您的数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值