我正在尝试在主类中运行该类的内容,但是我找不到解决方法。我尝试了从导入package.class和创建实例到其他选项的不同选项。这是否与构造此类的方式有关。如果那不可能的话,我只是不想继续转动轮子。对此问题的逻辑深表感谢。
package stockapplication;
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class Database {
public int empNum;
public String empFirst;
public String empLast;
public int empSal;
public Database(int c, String a, String b, int s) {
empNum = c;
empFirst = a;
empLast = b;
empSal = s;
}
public int getEmpNum() {
return empNum;
}
public String getEmpFirst() {
return empFirst;
}
public String getEmpLast() {
return empLast;
}
public int getSalary() {
return empSal;
}
public static void Stock() {
Database[] array = new Database[3];
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
System.out.printf("Please enter your employee number:");
int c = sc.nextInt();
System.out.printf("Please enter employee first name:");
String a = sc.next();
System.out.printf("Please enter employee last name:");
String b = sc.next();
System.out.printf("Please enter your salary:");
int s = sc.nextInt();
array[i] = new Database(c, a, b, s);
try {
File f = new File("Database1.txt");
PrintWriter pw = new PrintWriter(new FileOutputStream(f, true));
pw.append("\n" + c + "," + a + "," + b + "," + s + ",");
pw.close();
} catch (Exception e) {
}
}
}
}
答案 0 :(得分:0)
添加另一个类,您将在其中添加逻辑并将Database对象保留为模型。然后,从您的Main
调用这个新类并运行它的方法。
public class ServiceDB {
public ServiceDB() {
//Empty
}
public void writeDB() {
Database[] array = new Database[3];
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
System.out.printf("Please enter your employee number:");
int c = sc.nextInt();
System.out.printf("Please enter employee first name:");
String a = sc.next();
System.out.printf("Please enter employee last name:");
String b = sc.next();
System.out.printf("Please enter your salary:");
int s = sc.nextInt();
array[i] = new Database(c, a, b, s);
try {
File f = new File("Database1.txt");
PrintWriter pw = new PrintWriter(new FileOutputStream(f, true));
pw.append("\n" + c + "," + a + "," + b + "," + s + ",");
pw.close();
} catch (Exception e) {
// Never a good idea to leave it empty, at least print the error.
e.printStackTrace();
}
}
}
}
主要
public static void main(String[] args) {
ServiceDB serviceDB = new ServiceDB();
serviceDB.writeDB();
}
当然,我跳过了导入。如果您需要我添加它们,请告诉我。