Java 使用Vector类和while循环的应用程序有什么问题?

Java 使用Vector类和while循环的应用程序有什么问题?,java,string,vector,while-loop,Java,String,Vector,While Loop,你们能帮我处理一下我不工作的申请吗?首先,它必须提示用户输入一个字符串,提示将继续执行while循环,直到用户键入退出,然后应用程序将通过将字符串添加到向量中来显示他/她输入的字符串列表。这是我的密码。提前谢谢 import java.util.Scanner; import java.util.Vector; class TestVector { public static void main(String [] args) { String prompt = "Please en

你们能帮我处理一下我不工作的申请吗?首先,它必须提示用户输入一个字符串,提示将继续执行while循环,直到用户键入退出,然后应用程序将通过将字符串添加到向量中来显示他/她输入的字符串列表。这是我的密码。提前谢谢

import java.util.Scanner;
import java.util.Vector;

class TestVector {

public static void main(String [] args)
{
    String prompt = "Please enter a string or type QUIT to finish";
    Scanner userInput = new Scanner(System.in);
    Vector <String> names = new Vector <String>();
    System.out.println(prompt); 

    while(userInput.hasNextLine() && !(userInput.nextLine()).equals("QUIT"))
    {
        names.add(userInput.nextLine());
        System.out.println(prompt);
        Scanner userInput2 = new Scanner(System.in);
        names.add(userInput2.nextLine());
    }

    for(String s: names)
    {
        System.out.println("You typed: "):
        System.out.println(s);
    }
}
}

您创建了一个扫描仪,然后立即检查它是否有userInput.hasNextLine的输入。这将始终为false,并且while循环的主体将始终被跳过

如果需要用户的输入,只需调用nextLine。然后,您的程序将等待用户键入内容,然后再继续。以下是一个例子:

Scanner cin = new Scanner(System.in); // cin is a commonly used name for "console input"
String s = cin.nextLine();            // Initial read
while (!s.equals("quit")) {           // Check input
    System.out.println(s);            // Do something with input, like print it
    s = cin.nextLine();               // Read
}
试试这个:

import java.util.Scanner;
import java.util.Vector;

public class Main
{

    public static void main(String[] args)
    {
        String prompt = "Please enter a string or type QUIT to finish";
        Scanner userInput = new Scanner(System.in);
        Vector<String> names = new Vector<String>();
        System.out.println(prompt);

        String input = null;
        while (userInput.hasNextLine())
        {
            input = userInput.nextLine();
            if (input.equals("QUIT"))
                break;

            names.add(input);
        }

        for (String s : names)
        {
            System.out.println("You typed: ");
            System.out.println(s);
        }
    }
}

它是否告诉您错误在哪里?重复创建新扫描仪将无法工作。您在while循环的条件和主体中调用nextLine两次。我相信您希望查找退出或存储名称,但不要添加一些随机的非退出文本,然后输入输入。@jhobbie它已编译,我仍在使用crimson编辑器:如果第一个单词不是,这个循环将永远不会结束quit@Typo哎呀,我忘了读循环里面的输入了,哈哈。现在修好了。作为将来的参考,当出现类似的明显错误时,请使用“编辑”按钮,而不是insta downvoting。@Rainbolt,这是一种引起注意的方法。别担心,这件事总是发生在我身上,所以尼克说:嗨,非常感谢你的帮助,我现在设法让它工作起来了;顺便说一句,我能问你一些事吗?我不太明白你是怎么把字符串变量input声明为null的?呃,为什么要这样做,为什么不能在while循环中将其声明为String input=userInput.nextLine;内存分配。如果在重用同一区域之前定义了它。如果将其放入循环中,则创建一个新对象并对前一个对象进行垃圾收集。