java - 无法将从文件读取的数据推送到通用堆栈

标签 java generics

我正在尝试创建一个名为reverser的通用类,它获取文本文件的内容并反转内容的顺序。我需要使用提供的通用堆栈类来执行此操作。我必须确保它适用于两种类型:字符串和 float ,因为它们已在 main 中实例化。

我知道我无法将 int 值(由 BufferedInputStream 返回)插入堆栈。我的问题是这个问题的解决方案是什么,我应该实例化两个不同版本的通用堆栈类,一个用于字符串,一个用于 float ,还是有另一种解决方案?

public class project_5 
{
    public static void main(String[] args) throws Exception
    {
        Reverser<String> reversePoem = new Reverser<String>();
        Reverser<Float> majiGame = new Reverser<Float>();



    }
}




class Reverser<E>
{
    private Stack<E> tempStack;
    int k = 0;
    int val = 0;

    public Reverser()
    {
        tempStack = new Stack<E>();
    }

    void FileToStack(String fileIn) throws Exception
    {   
        E item = null;

        try
        {
            BufferedInputStream readFile = new BufferedInputStream(new FileInputStream(fileIn));

            for(k = 0; (val = readFile.read()) != -1; k++)
            {
                tempStack.push(val);
            }

            readFile.close();
        }
        catch(FileNotFoundException e)
        {
            System.out.print("File: " + fileIn + " Not Found");
        }
        catch(IOException e)
        {
            System.out.print("Reached end of file.");
        }
    }

    void StackToFile(String fileIn)
    {
        try
        {
            PrintWriter fileOut = new PrintWriter(fileIn);

            fileOut.println();

            fileOut.close();
        }
        catch(FileNotFoundException e)
        {

        }
    }
}






//Class Stack ---------------------------------------
class Stack<E>
{
 // pointer to first node in stack
 private Node<E> top;

 // constructor
 public Stack()
 {
    top = null;
 }

 public boolean isEmpty()
 {
    return top == null;
 }

 public void push(E data)
 {   
    if (data == null) 
       return;
    // build a node and place it on the stack
    Node<E> newNode = new Node<E>(data);
    newNode.next = top;
    top = newNode;
 }  

 public E pop()
 {
    Node<E> temp;

    temp = top;
    if (isEmpty())
       return null;

    top = top.next; 
    return temp.getData();     
 }

 // console display
 public String toString()
 {
    Node<E> p;

    String showAll = "";
    // Display all the nodes in the stack
    for( p = top; p != null; p = p.next )
       showAll += p.toString() + "\n";
    return showAll;  
 }
}

编辑:删除图片,添加文本格式的代码。

最佳答案

我对您的逻辑进行了更改,您正在读取文件然后放入堆栈, 您还没有放置您的 Node 类,因此我相应地添加了该类

从文件读取时,您需要类型转换您的值

注意:如果文件包含不正确的数据,您将收到转换错误,需要处理

source.txt

1 2 3 4 5

target.txt

5
4
3
2
1

Code

import java.io.*;
import java.util.Arrays;

public class Test
{
    public static void main(String[] args) throws Exception
    {
        Reverser<String> reversePoem = new Reverser<String>(String.class);
        Reverser<Float> majiGame = new Reverser<Float>(Float.class);

        majiGame.FileToStack("source.txt");

        majiGame.StackToFile("target.txt");

    }
}




class Reverser<E>
{
    private Stack<E> tempStack;
    private Class<E> tClass;

    public Reverser(Class<E> tClass)
    {
        tempStack = new Stack<E>();
        this.tClass = tClass;
    }

    public static <E> E convertInstanceOfObject(String value, Class<E> clazz) {
    try {
        // add custom casting, casting could be varies as par usage 
        if (clazz.getName().equals("java.lang.Integer")) {
            return (E)Integer.valueOf(value);
        } else if (clazz.getName().equals("java.lang.Float")) {
            return (E)Float.valueOf(value);
        } else if (clazz.getName().equals("java.lang.String")) {
            return (E)value;
        }
        return clazz.cast(value);
    } catch(ClassCastException e) {
        return null;
    }
}

    void FileToStack(String fileIn) throws Exception
    {
        BufferedReader br;
        try
        {
            br = new BufferedReader(new FileReader(fileIn));
            String line = null;
            while((line = br.readLine()) != null)
            {
                String[] valueArray= line.split(" ");

                for (String v : valueArray) {
                    E item = convertInstanceOfObject(v, tClass);
                    tempStack.push(item);
                }
            }
            br.close();
        }
        catch(FileNotFoundException e)
        {
            System.out.print("File: " + fileIn + " Not Found");
        }
        catch(IOException e)
        {
            System.out.print("Reached end of file.");
        }
    }

    void StackToFile(String fileIn)
    {
        try
        {
            PrintWriter fileOut = new PrintWriter(new FileWriter(fileIn));

            E d = null;
            while (!tempStack.isEmpty()) {
                d = tempStack.pop();
                fileOut.println(d);
            }


            fileOut.close();
        }
        catch(IOException e)
        {

        }
    }
}




class Node<E> {

    Node<E> next;
    private E data;

    public Node(E data) {
        this.data = data;
    }

    public Node<E> getNext() {
        return next;
    }

    public void setNext(Node<E> next) {
        this.next = next;
    }

    public E getData() {
        return data;
    }

    public void setData(E data) {
        this.data = data;
    }
}

//Class Stack ---------------------------------------
class Stack<E>
{
    // pointer to first node in stack
    private Node<E> top;

    // constructor
    public Stack()
    {
        top = null;
    }

    public boolean isEmpty()
    {
        return top == null;
    }

    public void push(E data)
    {
        if (data == null)
            return;
        // build a node and place it on the stack
        Node<E> newNode = new Node<E>(data);
        newNode.next = top;
        top = newNode;
    }

    public E pop()
    {
        Node<E> temp;

        temp = top;
        if (isEmpty())
            return null;

        top = top.next;
        return temp.getData();
    }

    // console display
    public String toString()
    {
        Node<E> p;

        String showAll = "";
        // Display all the nodes in the stack
        for( p = top; p != null; p = p.next )
            showAll += p.toString() + "\n";
        return showAll;
    }
}

关于java - 无法将从文件读取的数据推送到通用堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59297628/

相关文章:

java - vararg 参数可以是 <? super 对象>?

java - 我想扩展枚举和对象(通用)

c# - 采用构造函数的方法参数

带有newInstance的java泛型类型参数

java - 同时处理Recyclerview和CardView的点击事件

java - 如何删除java hashmap中特定对象的所有映射?

java - Axis2 Web 服务故障 - 找不到端点引用的服务

java - 查找 ArrayList<Object> 中的特定类型(即 Object = String 等)

java - Netbeans 未正确生成 javadoc

java - 无法为 SyncResponse Payload 创 build 备对象