我需要从数组中获取一个数字并将其初始化为变量,以便将其用作对象。我不确定它是否只是,
例如 int smallSpaces = 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());
}
}
}
}
答案 0 :(得分:0)
初始化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();
...
答案 1 :(得分:0)
如果你想使用一个对象,Java中的原始类型也有相应的对象,如Integer,Double等。 例如:
Integer myInt = new Integer(5);
答案 2 :(得分:0)
我需要从数组中获取一个数字并将其初始化为变量,以便将其用作对象。我不确定它是否只是
int[] nums = {1,2,3,4,5};
int myVar = nums[0]; //will get first array element (initialize it to a variable)
如果您想将用于对象。
int[] nums = {1,2,3,4,5};
MyClass m = new MyClass(nums[0]); //m's value (x) will be updated to num[0]
class MyClass
{
int x;
public MyClass(int x){ //Constructor
this.x = x;
}
}
如果您想将用作对象。
//Use a wrapper class according to the array element's data type:
Integer val = new Integer(nums[0]);