如何使用linkedList类中的方法以相反的顺序打印我的链表数组:
for (int j = 0; j < FutureValueLinkedList.size(); j++)
{
String myArrayLinkedList = FutureValueLinkedList.get(j);
System.out.println(myArrayLinkedList + "\t");
}
System.out.println();
addLast()能够做到吗?
import java.util.*;
import java.text.*;
public class FutureValueApp
{
public static void main(String[] args)
{
LinkedList<String> FutureValueLinkedList = new LinkedList<>();
// display a welcome message
System.out.println("Welcome to the Future Value Calculator");
System.out.println();
// perform 1 or more calculations
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
// get the input from the user
System.out.println("DATA ENTRY");
double monthlyInvestment = getDoubleWithinRange(sc,
"Enter monthly investment: ", 0, 1000);
double interestRate = getDoubleWithinRange(sc,
"Enter yearly interest rate: ", 0, 30);
int years = getIntWithinRange(sc,
"Enter number of years: ", 0, 100);
// calculate the future value
double monthlyInterestRate = interestRate/12/100;
int months = years * 12;
double futureValue = calculateFutureValue(
monthlyInvestment, monthlyInterestRate, months);
// get the currency and percent formatters
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
percent.setMinimumFractionDigits(1);
// format the result as a single string
String results =
"Monthly investment:\t"
+ currency.format(monthlyInvestment) + "\n"
+ "Yearly interest rate:\t"
+ percent.format(interestRate/100) + "\n"
+ "Number of years:\t"
+ years + "\n"
+ "Future value:\t\t"
+ currency.format(futureValue) + "\n";
// print the results
System.out.println();
System.out.println("FORMATTED RESULTS");
System.out.println(results);
String monthlyInvestmentFormat = currency.format(monthlyInvestment);
String interestRateFormat = percent.format(interestRate/100);
String futureValueFormat = currency.format(futureValue);
FutureValueLinkedList.add(monthlyInvestmentFormat + "\t" +
interestRateFormat + "\t" + Integer.toString(years) +
"\t" + futureValueFormat);
// see if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
System.out.println("Future Value Calculations ");
System.out.println();
System.out.print("Inv/Mo.\tRate\tYears\tFuture Value\n");
for (int j = 0; j < FutureValueLinkedList.size(); j++)
{
String myArrayLinkedList = FutureValueLinkedList.get(j);
System.out.println(myArrayLinkedList + "\t");
}
System.out.println();
}
答案 0 :(得分:1)
如果您只想输出反转列表,可以使用descendingIterator作为Ostap建议。但是,如果你想在某处存储反向列表,那么你可以这样做:
LinkedList<String> reversedFutureValueLinkedList = Collections.reverse(FutureValueLinkedList );
答案 1 :(得分:1)
查看LinkedList#descendingIterator()
LinkedList<Integer> l = new LinkedList<Integer>();
l.add(1);
l.add(2);
l.add(3);
Iterator i = l.descendingIterator();
while(i.hasNext()) {
System.out.print(i.next() + " ");
}
打印出来:
3 2 1