首先,你正在閱讀的輸入錯誤:
這條線:
String name1 = in.toString();
應該是:
String name1 = in.next();
通過調用in.toString()
您所呼叫的方法,該方法將返回這個Scanner
的字符串表示形式。這個方法被Object
類覆蓋,該類是Java中所有類的父類,通常用於調試目的。
當您撥打in.next()
時,您將讀取Scanner
的輸入流中的下一個String
令牌。
其次,您沒有在循環中使用name1
變量或int price
變量。
對於這一部分:
方案應然後提示輸入名稱的用戶和產品目錄中的每個產品的價格。
現在,你正在做的是創造可變name1
和price
你的循環中,而不是將其用於任何東西。在您的上一個打印語句中,打印的name
和price
是您在程序開始時分配的值。
// the values shown bellow are printed
// ...
private static final String price = null;
// ...
int name = 1;
// ...
所以,你的程序總是打印:
Product = 1$ null
你應該只刪除final static String price
變量,因爲沒有任何真正的目的吧。
對於存儲產品,您可能需要使用Java Collection中的對象,如ArrayList
。爲此,您應該創建一個名爲Product
的類,其中包含產品名稱和價格,然後構建它們的列表。
class Product {
String name;
int price;
}
這將是一個更好,更清潔,面向對象的方法來解決您的問題。但是,您也可以通過兩個變量跟蹤最大的價格和產品名稱(因爲看起來您的計劃是這樣),所以我會告訴您如何做到這一點。
一旦輸入所有產品,程序應輸出目錄中最昂貴產品的產品信息(名稱和價格)。
所以,你可以使用兩個變量,String expProdName
和int expProdPrice
保持的最昂貴的產品的信息跟蹤。您還需要兩個臨時變量,String currProdName
和int currProdPrice
以獲取用戶輸入的當前信息。
在你的循環中,你使用變量item
來打印產品的順序,但你可以使用循環計數器i
來做到這一點。
您應該將expProdPrice
(目前爲止最昂貴的價格)初始化爲Integer.MIN_VALUE
,這是可能的最低整數值,以便與新價格進行比較以確定最高價格。但是,考慮到產品的價格不應該爲負數,也可以將其初始化爲-1。
然後在循環中,每次讀取新價格時,都會將其與存儲在expProdPrice
中的值進行比較,如果值較大,則將最高價格更新爲此新價格。 您還需要更新產品名稱。
讓我們來看看代碼的外觀:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of Products: ");
int count = in.nextInt();
String expProdName = ""; // expensive product name
int expProdPrice = Integer.MIN_VALUE; // expensive product price
String currProdName = ""; // current product name
int currProdPrice = -1; // current product price
for (int i = 1; i <= count; i++) {
System.out.print("Enter the Name of Product " + i + " :\n");
currProdName = in.next();
System.out.print("Enter the Price of Product " + i + " :\n");
currProdPrice = in.nextInt();
// if current price larger that the most expensive price thus far
// update the most expensive price to the current price and
// update the name of the most expensive product to current product's name
if(currProdPrice > expProdPrice) {
expProdPrice = currProdPrice;
expProdName = currProdName;
}
}
System.out.println("\nMost expensive product is:\n\nProduct name:\t" + expProdName +
"\nProduct price:\t" + expProdPrice + "$");
}
我看到我錯在哪裏,但我也是一個邏輯錯誤是我有是System.out.print(「...」):在那裏我有價格作爲其變量,它實際上應該是別的東西,而不是我的價格問題的變量。 – 2014-09-23 01:06:29
@SamanthaHlad看着我編輯:) – nem035 2014-09-23 01:21:27
我看到我要去哪裏錯了。我改變了in.next();爲我的產品線。我需要改變一些其他的東西,但這是其中的一種,我覺得我應該開槍自殺。我應該知道這一點。嘿,謝謝。 – 2014-09-23 01:27:50