System.out.println("How many items will be supplied by this supplier?");
SPItemAmount = SupplierEntry.nextInt();
System.out.println("Ok, your item ID with this supplier is:");
for(int i = 1;i <= SPItemAmount; i++) {
System.out.println("I" + i);
}
public String getSupplierDetails() {
return "SP" + AddSupplier.getSupplierID() + SPName+
}
我的ItemID将根据用户输入生成。当来到getSupplierDetails时,我如何用一个变量打印所有ItemID?还是有另一种方式?感谢您的帮助。
答案 0 :(得分:0)
虽然您的问题对于手头的问题非常简单,但当您提出问题时,您应提供尽可能多的相关代码。这将消除许多猜测和假设。至少提供将编译的代码。
您可以做的一种方法是为 for 循环的每次迭代填充(追加)一个字符串变量(请参阅下面的 getSupplierID()方法)。虽然不是强制性的,但允许您的方法接受参数,以便变量不必是全局类。
public static void main(String args[]) {
Scanner supplierEntry = new Scanner(System.in);
// Get supplier name...
String sPName = "";
// Continue to ask for Supplier Name if validation fails.
while(sPName.equals("")) {
System.out.println("What is the Supplier's Name (c to cancel):");
sPName = supplierEntry.nextLine().trim();
// Privide a Quit option.
if (sPName.toLowerCase().equals("c")) {
System.out.println("User Quit!");
System.exit(0); // Close the application.
}
// Supplier Name validation...
if (sPName.equals("")) {
System.err.println("Invalid Supplier Name Provided! Try again.\n");
}
}
// Get number of items supplied by supplier...
int sPItemAmount = 0;
// Continue to ask for Items Count if validation fails.
while (sPItemAmount == 0) {
System.out.println("How many items will be supplied by " + sPName + "?");
// Trap exception for Numerical validation...
try {
sPItemAmount = supplierEntry.nextInt();
} catch(InputMismatchException ex) {
System.err.println("Invalid Items Amount Provided! " +
"Whole Numbers Only! Try again.\n");
}
supplierEntry.nextLine(); // Clear scanner buffer
}
// Generate the Supplier ID
String supplierID = getSupplierID(sPItemAmount);
// Get Supplier Details.
String supplierDetails = getSupplierDetails(sPName, supplierID);
// Display information...
System.out.println("Ok, your item ID with " + sPName + " is: " + supplierID);
System.out.println("Supplier Details Are: " + supplierDetails);
// Close the Scanner object.
supplierEntry.close();
}
public static String getSupplierID(int itemAmount) {
String itemID = "";
for(int i = 1; i <= itemAmount; i++) {
itemID+= "I" + i;
// which is the same as:
// itemID = itemID + "I" + i;
}
return itemID;
}
public static String getSupplierDetails(String supplName, String itemID) {
// Replace any whitespaces in Supplier Name with
// the underscore character ( _ ). You can remove
// the .replace() method if you don't want this.
return "SP" + itemID + supplName.replace(" ", "_");
}