我对这个为我写的课程有疑问。除了一个小细节之外,它的功能正是我需要的。我的while循环在我的打印语句的末尾添加了一个额外的“+”。在JAVA中摆脱额外的输出虽然循环
public class Fractions
{
public static void main (String[] args)
{
//-----declare variables-----
int numOfFractions = 0,
numerator = 0;
double total = 0;
DecimalFormat df1 = new DecimalFormat("#0.##");
Scanner stdIn = new Scanner(System.in);
//----Welcome MSG------
System.out.println("");
System.out.println("\t* * * Welcome to Fractions * * * ");
System.out.println("");
//-----get numOfFractions------
System.out.print("Enter the number of fractions: ");
numOfFractions = stdIn.nextInt();
//----begin loop-------
numerator = 1;
while(numerator <= numOfFractions)
{
while(numOfFractions > 0)
{
System.out.print("" + numerator + "/" + numOfFractions + " " + "+" + " ");
total += (double)numerator/numOfFractions;
numOfFractions--;
numerator++;
}
}
System.out.println("");
System.out.println("");
System.out.print("The total: " + df1.format(total));
System.out.println("");
System.out.println("\nThanks for using the Fraction Adder program\n");
} // end main
} // end pgm
Here is a picture of my output
只需更换DF1 .format(total)with df1.format(total.substring(0,total.length() - 1))。 (假设多余的+是你的字符串中的最后一个字符) –