简体   繁体   English

编写一个Java程序,查询用户一系列单词。 当用户输入“退出”时程序退出

[英]Write a java program that queries the user for a series of words. The program exits when the user enters 'quit'

QUES Write a java program that queries the user for a series of words. 问题编写一个Java程序,向用户查询一系列单词。 The program exits when the user enters quit . 当用户输入quit时,程序退出。 Before the program exit, it should display all the list of words being entered. 在程序退出之前,它应显示所有输入的单词列表。

I have tried solving this ques but when the list of the word is displayed the spaces left for the array is also printed. 我尝试解决此问题,但是当显示单词列表时,也会打印出数组剩余的空格。 Am new in java programming so please help me. Java编程中的新手,请帮助我。

import java.util.Scanner;
class ques1
{
    public static void main(String[] args)
    {
        String [] str=new String[20];
        Scanner sc=new Scanner(System.in);
        System.out.println("enter series of words and to exit write quit");
        int i=0;
         while(true){
                str[i]=sc.nextLine();
                    if(str[i].equals("quit") || str[i].equals("QUIT"))
                       break;
                    else
                        i++;
        }
        System.out.println();
        System.out.println("----------------------------");
        for (int j=0;j<str.length;j++)
        {
          System.out.println(str[j]);
        }     
    }
}

use ArrayList<String> it's a dynamic array and is more suitable for this functionality 使用ArrayList<String>它是一个动态数组,更适合此功能

ArrayList<String> words = new ArrayList<>();
while(true){
  String word = sc.nextLine();
  if (!word.toLowerCase().equals("quit"))
    word.add(word);
  else
    break;
 }

for(String word : words)
  System.out.println(word);

Arrays have fixed space allocated (in your case is 20) filled with null and will will produce ArrayIndexOutOfBounds if the user enter more than 20 words. 数组分配有固定的空间(在您的情况下为20),该空间填充为null,并且如果用户输入20个以上的单词,将产生ArrayIndexOutOfBounds。

Expect that, since you are storing the index of the last inserted array element you can simple loop from 0 to i that are the only filled spaces of the array: 可以预期的是,由于要存储最后插入的数组元素的索引,因此可以简单地从0循环到i ,这是数组唯一填充的空间:

    for (int j=0; j <= i; j++) {
      System.out.println(str[j]);
    }     

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM