Java || 数组元素在 varArr[i] = varInt 后设置为 0

huangapple go评论60阅读模式
英文:

Java || Array elements set to 0 after varArr[i] = varInt

问题

<h3>程序的功能:</h3>
<p>这部分程序检查可购买的物品,显示这些物品,然后询问用户想购买哪些物品。然后它会询问他们想购买该物品的数量,并将该数量添加到一个整数数组中,数组的索引对应于物品名称的索引(因此名称和数量存储在两个数组中,但通过索引对齐)。一旦将整数输入数组中,循环会再次开始询问要购买的物品,直到用户输入“finish”为止,这将停止循环。另一种方法使用该整数数组生成收据。</p>

<h3>我的问题:</h3>
<p>当到达将整数输入数组时,我立即将该数组打印到控制台,然后得到以下结果。</p>

假设,第一个循环将“10”添加到索引“1”。

索引“0”的元素 = 0
索引“1”的元素 = 10
索引“2”的元素 = 0
索引“3”的元素 = 0

然后假设,第二个循环将“20”添加到索引“3”。

索引“0”的元素 = 0
索引“1”的元素 = 0
索引“2”的元素 = 0
索引“3”的元素 = 20

我的问题是,为什么索引“1”会恢复为“0”?

<h3>我的期望:</h3>

<p>我期望整数继续添加到数组中。使用上面的示例,一旦第二个循环完成,我期望以下结果。</p>

索引“0”的元素 = 0
索引“1”的元素 = 10
索引“2”的元素 = 0
索引“3”的元素 = 20

<h3>代码:</h3>

do {
    // 一些代码...
    if (!(amountInput == 0)) {
        soldItems[index] += amountInput;
    } else {
        System.out.println("\nNothing added.");
    }
    for (int i = 0; i < soldItems.length; i++) {
        System.out.println("sldItems at index '" + i + "' " + soldItems[i]);
    }
} while (finishedSale == false);
// 一些代码...
英文:

I hope I can describe this adequately.

<h3>What the program does:</h3>
<p>This section of the program checks to see what items are available for purchase, displays those items and then asks the user which items they want to buy. Then it asks how many of that item they want to purchase and adds that number to an array of integers, where that arrays index corresponds to the index of item names (so the name and quantity are stored in two arrays, but are aligned by index). Once the integer has been entered into the array, the loop starts again asking for an item to purchase, until the user enters 'finish', which stops the loop. Another method uses that integer array to generate a receipt.</p>

<h3>My problem:</h3>
<p>When it comes time to enter the integer into the array, I print that array to console immediately after, and get this result.</p>

Say, the first loop adds '10' to index '1'.

element at index &#39;0&#39; = 0
element at index &#39;1&#39; = 10
element at index &#39;2&#39; = 0
element at index &#39;3&#39; = 0

Then say, the second loop adds '20' to index '3'.

element at index &#39;0&#39; = 0
element at index &#39;1&#39; = 0
element at index &#39;2&#39; = 0
element at index &#39;3&#39; = 20

My question is, why does index '1' revert to '0'?

<h3>What I expect:</h3>

<p>I expect the integers to just keep being added to the array. Using the above example, once the second loop is done, I expect the following result.</p>

element at index &#39;0&#39; = 0
element at index &#39;1&#39; = 10
element at index &#39;2&#39; = 0
element at index &#39;3&#39; = 20

<h3>The code:</h3>
Edit: Added the rest of this block to meet minimal, reproducible example.

do {
	System.out.println(saleMenu);
	String[] availArray = new String[stockName.length];
	for (int i = 0; i &lt; stockLevel.length; i++) {
		if (stockLevel[i] &gt; 0) {
			availArray[i] = stockName[i];
		}
	}
	for (int i = 0; i &lt; availArray.length; i++) {
		System.out.println(availArray[i]);
	}
	System.out.println(&quot;\nType &#39;finish&#39; to generate a receipt.&quot;);
	soldItems = new int[availArray.length];
	System.out.println(saleMenu2);										// Display menu.
	String input = console.nextLine().toLowerCase();					// Get input.
	if (!(input.contains(&quot;finish&quot;))) {									// If input not &quot;finish&quot;.
		for (int i = 0; i &lt; availArray.length; i++) {					// Loop through availableArray
			if (availArray[i].equals(input)) {							// If stock present.
				available = true;										// Set available flag.
				index = i;												// Grab the index.
			}
		}
		if (available == false) {										// If input not available.
			System.out.print(&quot;That is not an option. Try again.\n&quot;);	// Display error.
		}
		if (available == true) {										// If input available.
			available = false;											// Reset available flag.
			System.out.println(&quot;How many would you like to purchase?&quot;);	// Display message.
			amountInput = console.nextInt();							// Get input.
			console.nextLine();											// Capture stray \n
			if (amountInput &lt; 0) {										// Is input &lt; 0.
				System.out.println(&quot;\nSorry, the number must be positive.&quot;);	// Display error.
			} else
				if (!(amountInput == 0)) {								// If input not 0.
					soldItems[index] += amountInput;					// Add input to array at 
																		// &#39;index&#39; grabbed above.
				}
				else
					System.out.println(&quot;\nNothing added.&quot;);				// If input 0, display error.
			for (int i = 0; i &lt; soldItems.length; i++) {								// Debugging
				System.out.println(&quot;sldItems at index &#39;&quot; + i + &quot;&#39; &quot; + soldItems[i]);	// Debugging.
			}
		}
	} else
		finishedSale = true;
} while (finishedSale == false);
processSale(soldItems, stockLevel);
System.out.print(continueOption);
continueYN = console.nextLine().toLowerCase().charAt(0);
if (continueYN == &#39;y&#39;) {
	mainMenuSelect = 0;
}
break;

答案1

得分: 0

do {
    // [...]
    soldItems = new int[availArray.length];
    // [...]
} while (!finishedSale)

你在每次迭代中都重新初始化了数组。每次购买之后,数组都会被清空并重新实例化,其中的元素都变成了零。将实例化的部分移到循环外面。

顺便说一下,与其使用finishedSale == false,用!finishedSale更符合惯用语法。

英文:
do {
    // [...]
    soldItems = new int[availArray.length];
    // [...]
} while (finishedSale == false)

You are resetting the array on each iteration. After each purchase, the array is wiped and newly instantiated -- containing zeroes. Move the instantiation outside the loop.

<sub>Btw, instead of finishedSale == false it is more idiomatic to write !finishedSale.</sub>

huangapple
  • 本文由 发表于 2020年9月18日 15:20:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/63951020.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定