JavaFX 按升序显示单词

标签 java javafx

我在这里做错了什么,因为我没有错误,但我编写的这个程序无法运行。请帮助根据下面的描述运行它。

程序说明:使用JavaFX:编写一个程序,从文本文件中读取单词并按字母升序显示所有单词(允许重复)。单词必须以字母开头。文本文件作为命令行参数传递。我要使用的文本文件名为:example20_1.txt,并且有一个文件输入框和提交按钮,文件结果将显示在框和按钮下方的输入窗口中。这就是我所拥有的:

import java.io.*;
import java.util.*;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.text.Text;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.control.TextArea;
import javafx.event.EventType;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;

public class DisplayingWords extends Application {

   TextField fileName = new TextField();
   Button submitButton = new Button("Submit");
   TextArea outputArea = new TextArea();

   public void main() {
       submitButton.setOnAction(e -> {
           if(fileName.getText().length() > 0) {
               submitButtonClick();
           }
       });
   }

   public void main(String[] args) throws IOException {
       // Check command-line parameter usage
       if (args.length > 0) {
           fileName.setText(args[0]);

           System.out.println("Source file: " + fileName.getText());
       }

       main();
   }

   @Override
   public void start(Stage primaryStage) {
       try {
           BorderPane root = new BorderPane();

           Scene scene = new Scene(root,400,400);
       scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());

           primaryStage.show();

           // Set the stage title
           primaryStage.setTitle("Exercise20_01");

           // Place the scene in the stage
           primaryStage.setScene(scene);

           // Display the stage
           primaryStage.show();

           // Hold a button in an HBox
           HBox inputBox = new HBox();
           inputBox.setSpacing(10);
           inputBox.setAlignment(Pos.CENTER);
           inputBox.getChildren().addAll(new Text("Filename:"));
           inputBox.getChildren().addAll(fileName);
           inputBox.getChildren().addAll(submitButton);
           root.setTop(inputBox);

           //This creates a text box to display the results
           //from reading the file in a pane
           outputArea.setStyle("-fx-text-fill: black");
           outputArea.setStyle("-fx-background-color: grey");
           root.setCenter(outputArea);
       } catch(Exception e) {
           e.printStackTrace();
       }
   }


   public void submitButtonClick() {
       if(fileName.getText().length() > 0) {
//           File sourceFile = new File(fileName.getText());
//           if (!sourceFile.exists()) {
//               System.out.println("Source file " + fileName.getText()
//                   + " does not exist");
//           }
       }

       fileName.setText("Test 1");
   }

   class SortFile
   {
       //sorting function
   void sortArray(String array[]) {
       //Loop for no.of passes
   for(int i=0;i<array.length-1;i++)

       //Repeat no.of comparisons
       for(int j=0;j<array.length-i-1;j++)

           //Comparing adjacent elements
           if(array[j].compareTo(array[j+1])>0)
   {
               //Swap using temp variable
               String temp=array[j];
               array[j]=array[j+1];
               array[j+1]=temp;
              }
   }
   public void main(String args[])
   {
       //Creating File object
       File freader;

       //Scanner for reading
       Scanner filescanner;

       //Array list for dynamic elements adding
   ArrayList <String> array = new ArrayList<String>();

   //If file name is no.of passed as argument is 1
   if(args.length==1)
   {
   try
   {
       //Create file object
       freader = new File(args[0]);

       //Reading from file
       filescanner = new Scanner(freader);

       //Reading until end of file
   while(filescanner.hasNext())
   {
       //Reading each word and to Array List
       array.add(filescanner.next());
   }
   }
   //If file IOException is thrown
      catch(IOException ie)
   {
   System.out.println(ie);
   }String[] newArray = new String[array.size()];

   //Convert Array list to ArraynewArray=array.toArray(newArray);

   System.out.println("List of strings from file Before Sorting : \n");

   //Print before sorting words
   for(int i=0;i<newArray.length;i++)
   System.out.print(newArray[i]+" ");

   //Call sorting method
   sortArray(newArray);
   System.out.println("\nList of strings from file After Sorting : \n");

   //Print after sorting words
   for(int i=0;i<newArray.length;i++)
   System.out.print(newArray[i]+" ");

   System.out.print("\n");
   }
   else
       //If file name is not passed as argument then show usage syntax
       System.out.println("Usage syntax: SoftFile <example20_1.txt>");}
   }
   }

最佳答案

假设您将这些单词从文本文件中添加到单词列表中

List<String> wordList = new ArrayList<>();
        wordList.add("Ann");
        wordList.add("Sam");
        wordList.add("Peter");
        wordList.add("John");
        wordList.add("Watson"); 

方法一:
您的 sortArray 方法应更新为以下内容:

  // you can call this method by sortArray(wordList.toArray(new String[wordList.size()]));
  public  String[] sortArray(String[] array) {
    int index;
    //Loop for no.of passes
    for (int j = 0; j < array.length - 1; j++) {
        index = j;

        for (int i = j + 1; i < array.length; i++) {
            //We keep track of the index to the smallest string
            if (array[i].trim().compareTo(array[index].trim()) < 0) {
                Index = i;
            }
        }
        //We only swap with the smallest string
        if (index != j) {
            String temp = array[j];
            array[j] = array[index];
            array[index] = temp;
        }
    }
    return  array;//it returns the sorted array
}

您可以通过使用迭代循环打印结果来检查它是如何工作的

for (String arrayElement : your_array) {
            System.out.println(arrayElement);
        }

方法二:
这是使用 java 8 lambda 表达式按字母顺序轻松对这些单词进行排序的方法

    List<String> sortedList=wordList
                    .stream().sorted().collect(Collectors.toList());
            sortedList.forEach(i->System.out.println(i));

您将得到以下输出:

Ann
John
Peter
Sam
Watson

关于JavaFX 按升序显示单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33857889/

相关文章:

java.lang.RuntimeException : Camera. setParameters

java - 如何在 JAVA 中将两个或多个 tiff 图像文件组合成一个多页 tiff 图像

java - StyleableProperty : how to change value programatically at runtime?

java - 如何根据鼠标位置在折线图上绘制十字准线

JavaFX Canvas : Draw a shape exclusively within another shape

Java、Android、camerax 编程。错误 : cannot find symbol. 符号:类生成器

java - 如何从包含多种对象类型的数组列表实例化对象

java - 如何迭代hashmap,是否需要在Java中强制转换keySet()?

Java FX 无法加载 Font Awesome 图标

JavaFX 检查事件的 KeyCode 是否为数字键