【问题标题】:Check and Validate Java Array using while loop使用 while 循环检查和验证 Java 数组
【发布时间】:2018-08-11 01:45:59
【问题描述】:

我需要一些关于代码的帮助。 我需要;

  • 制作一个程序,询问您将要谈论的主题,然后谈论它们。
  • 程序应检查数组是否有“?”并说出不允许的问题

  • 并检查他们输入的主题并要求他们“告诉更多关于 'x' "

  • 如果在 Joption 中按下取消或如果它包含“再见”则结束

这是我目前的代码;

import java.util.*;
import javax.swing.*;

public class ATSEStage2 {


public static void main(String[] args) {


    String tmma = "Tell me more about ";

    JOptionPane.showMessageDialog(null, "Hi, Welcome to ATSE \nStarting Input taking Phase...");



    int N = Integer.parseInt(JOptionPane.showInputDialog("How many Topics will you be talking about?"));
    double [] topics;
    topics = new double [N];
    String [] kw = new String[N];
    String [] chat = new String [N];

    int i=0; int a=1;
    while(i<N) {
    kw [i] = JOptionPane.showInputDialog("Enter Topic "+a);
    System.out.println(kw [i]);
    i++;
    a++;
    }
    i=0;a=0;

    String formattedString = Arrays.toString(kw)
            .replace("[", "")  
            .replace("]", ""); 

    JOptionPane.showMessageDialog(null,
            "The Topics you entered were, " +formattedString + "\nStarting Chatting phase...");

    int e=0;
    List<String> list = Arrays.asList(kw);


        chat [e] = JOptionPane.showInputDialog(null, tmma + formattedString);

        List<String> list1 = Arrays.asList(chat);
        while(e==0) {

            If (list1.contains("?"));{chat [e] = JOptionPane.showInputDialog(null, tmma + formattedString);
        e++;
        }
        }
    }

谢谢!

【问题讨论】:

  • 这段代码有什么问题?你有错误信息吗?输出不正确?
  • 问题是,无法检查/验证数组中的单词,如果它包含特定单词则循环它
  • 我看到你有一个大写的if。在 Java 中,if 是小写的。
  • if 语句之后还有一个分号。删除那个
  • topics 的用途是什么?

标签: java arrays while-loop contains joptionpane


【解决方案1】:

@Lonath Senevirathne,您正在使用 List 类的 contains() 方法。如果你打开它,你会看到它的描述是Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).。如果您希望能够检查/验证数组中的单词并在它包含特定单词时循环它,您应该遍历所有列表元素

while (e == 0) {

    for (String st : list1) {
        if (st != null && st.contains("?")) {
            chat[e] = JOptionPane.showInputDialog(null, tmma + formattedString);
            e++;
        }
    }
}

while loop

int idx = 0;
while(idx < list1.size()) {
   if (list1.get(idx) != null && list1.get(idx).contains("?")) {
        chat[e] = JOptionPane.showInputDialog(null, tmma + formattedString);
        e++;
   }
   idx++;
}

如果list1 不包含?,你也有无限的while loop

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-08
    • 1970-01-01
    • 2016-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    相关资源
    最近更新 更多