我有一项任务是从用户那里获取输入(不是特定次数),并最终将所有这些输入作为列表输出到最后。输入是整数,这需要在不使用for循环的情况下完成。 我试图自己做,但是我发现在最后一次显示所有值时出现问题。由于每次用户输入值,它都会覆盖它。任何建议赞赏。
import java.util.Scanner;
class dispay
{
public static void main(String[]args)
{
Scanner stdIn=new Scanner(System.in);
System.out.print("Please enter the ammount or '-1' to exit:");
String input=stdIn.nextLine();
int inputInt=0;
while(!(input.equals("-1")))
{
inputInt=Integer.parseInt(input);
System.out.print("Please enter the ammount or '-1' to exit:");
input=stdIn.nextLine();
}
System.out.println("Original price: "+inputInt);
}
}
答案 0 :(得分:1)
我认为这样做的最好方法是使用向量。这与您需要定义大小才能继续的数组不同。矢量可以增长和缩小。有关详细信息,请参阅[http://docs.oracle.com/javase/7/docs/api/java/util/Vector.html]。基于你已经给出的代码,我建议如下:
import java.util.*; /*edited this line*/
class dispay
{
public static void main(String[]args)
{
Scanner stdIn=new Scanner(System.in);
System.out.print("Please enter the ammount or '-1' to exit:");
String input=stdIn.nextLine();
int inputInt=0;
Vector v=new Vector(1,1); /*defines an empty vector of ints*/
while(!(input.equals("-1")))
{
inputInt=Integer.parseInt(input);
v.addElement(new Integer(inputInt)); /*adds the new integer to the vector of ints*/
System.out.print("Please enter the ammount or '-1' to exit:");
input=stdIn.nextLine();
}
System.out.println("Original price: "+v.toString()); /*prints the full vector in string representation*/
}
}
或者代替' v.toString()'可以使用以下内容:
for(int i=0; i<v.size()-1; ++i){
System.out.print(v.get(i) + " ");
}
答案 1 :(得分:1)
import java.util.*; /*edited this line*/
class dispay
{
public static void main(String[]args)
{
Scanner stdIn=new Scanner(System.in);
System.out.print("Please enter the ammount or '-1' to exit:");
String input=stdIn.nextLine();
int inputInt=0;
Vector v=new Vector(1,1); /*defines an empty vector of ints*/
while(!(input.equals("-1")))
{
inputInt=Integer.parseInt(input);
v.addElement(new Integer(inputInt)); /*adds the new integer to the vector of ints*/
System.out.print("Please enter the ammount or '-1' to exit:");
input=stdIn.nextLine();
}
System.out.println("Original price: "+v.toString()); /*prints the full vector in string representation*/
}
}
或者代替&#39; v.toString()&#39;可以使用以下内容:
for(int i=0; i<v.size()-1; ++i){
System.out.print(v.get(i) + " ");
}
感谢您的工作,就像我希望的那样。