我对上课时写的这个程序有疑问。它的功能完全按照我需要的方式运行,除了一个小细节。我的while循环在print语句的末尾添加了一个额外的“+”。
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
答案 0 :(得分:0)
有很多方法可以通过简单地使用if / else条件来实现这个最简单的方法,试试这个:
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)
{
if (numOfFractions > 1)
{
System.out.print("" + numerator + "/" + numOfFractions + " " + "+" + " ");
}
else
{
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
答案 1 :(得分:0)
通常,您检查要打印的元素是否是最后一个(或第一个)元素,然后再添加分隔符。这是一个简单的例子,因为我认为它更容易理解发生了什么:
String[] arr = new String[] { "a", "b", "c" };
for (int i = 0; i < arr.length; i++) {
if (i > 0)
System.out.print("+");
System.out.print(arr[i]);
}
我们仅为<{1}}和之前的元素打印分隔符+
实际值。您也可以撤消此操作,并在实际值之后打印index > 0
处所有元素的分隔符。
使用Java 8时,您也可以使用index < arr.length - 1
并在循环后打印内容,如下所示:
StringJoiner
在您的代码中,这看起来像这样:
String[] arr = new String[] { "a", "b", "c" };
StringJoiner joiner = new StringJoiner("+");
for (int i = 0; i < arr.length; i++)
joiner.add(arr[i]);