我需要从数组中获取一个数字并将其初始化为变量,以便我可以将其用作对象。我不确定是否只是这样,
intsmallSpaces = 1;
例如。
有人知道我该怎么做吗?
public class Port {
public static void main(String[] args) throws IOException {
Scanner console = new Scanner(System.in);
String shipSize = null;
String shipName = null;
int smallSpaces = 1;
int mediumSpaces = 2;
int largeSpaces = 3;
int[][] dockSpaces = {
{1, 1, 1, 1, 1, 2, 2, 2, 3, 3},
{1, 1, 1, 1, 1, 2, 2, 2, 3, 3},
{1, 1, 1, 1, 1, 2, 2, 2, 3, 3},
};
int waitingList = 10;
int menuChoice = 0;
while (true) {
System.out.println("SHIP PORT APPLICATION");
System.out.println("\n1. Add ship to port.");
System.out.println("\n2. Remove ship from port.");
System.out.println("\n3. View report.");
System.out.println("\n4. Exit.");
menuChoice = console.nextInt();
switch (menuChoice) { // Using a switch case for the menu options
case 1:
System.out.println("Add ship to port");
break;
case 2:
System.out.println("Remove ship from port");
break;
case 3:
System.out.println("View report");
break;
case 4:
System.out.println("Exit");
break;
default:
System.out.println("Invalid Choice");
}
try {
FileWriter write = new FileWriter("PortLog.txt", true);
BufferedWriter out = new BufferedWriter(write);
if (menuChoice == 1) {
System.out.println("Please select ship size(1. Cargo /n 2.Container /n 3. SuperContainer)");
shipSize = console.next();
System.out.println("Please enter the name of your ship");
shipName = console.next();
if (shipSize.equals("1")) {
smallSpaces++;
System.out.println("test");
write.write("SMALL"); // Printing line to output file about the transaction details
out.newLine(); //Adding new line to file writer
out.close();
}
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
}
最佳答案
初始化一个int
int a = 1;
就够了。但是,虽然这是一个变量,但它不是一个对象,而是一个原始类型。对象需要使用关键字new来创建,而基本类型则不需要,在java中基本类型有byte、short、int、long、float、double、boolean、char。从初始化的角度来看,字符串是一种特殊情况,因为它可以用字符串文字进行初始化。
原语:
int a = 1;
char c = 'c';
boolean b = true;
...
对象:
Object a = new Object();
ClassA class = new ClassA();
...
关于java - 如何从数组中初始化一个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29524957/