[英]Simple Java Stack Addition
這是我的代碼
package practice;
import java.util.Stack;
public class prac {
public static void main (String[]args){
int K = -1;
do{
System.out.print("Enter the amount of positive numbers to add up: ");
K = In.getInt();
} while(K<0);
int i;
Stack sum = new Stack();
int number;
int totalsum;
System.out.println("Enter " + K + " values between 1 and 100, or a 0 to to ignore the last number submitted");
for(i = 1; i <= K; i++){
number = In.getInt();
if(number == 0)
sum.pop();
else
sum.push(number);
System.out.print(sum);
}
}
}
Java的新手。 只需知道將堆棧中所有值加在一起的SIMPLEST和EASIEST方法即可。 即。 如果堆棧為[1、2、3],則答案為6
我將在您的if(number== 0)
語句中聲明一個名為total
的變量:
while(!sum.isEmpty()){
total += sum.pop();
}
您還應該修改打印語句以打印total
的值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.