Home > front end >  public static String return null on a File when accessed
public static String return null on a File when accessed

Time:01-18

I am doing a program to conetarme by network to a file of a machine in the network and when trying to use the value of : (name) it reads it as null, instead when I make a System.out.println (name); I read the value

Main.java

import javax.swing.*;
import java.awt.*;
import java.io.FileNotFoundException;

public class Main {

    public static String text;
public static void main(String[] args) throws FileNotFoundException {

     //int wc = DevolverValor.Leer();
     //String wcs = Integer.toString(wc);
     String name = "";


    JFrame frame = new JFrame ("La tikets");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(650 , 300);

    JPanel panel = new JPanel(); // el panel no está visible en la salida
    JPanel panel2 = new JPanel(); // el panel no está visible en la

    JLabel etiqueta =  new JLabel("Introducir nombre de la maquina");
    JLabel cantidad = new JLabel("Cantidad");

    JButton Buscar = new JButton("Buscar");
    JButton restablecer = new JButton("Restablecer");

    JTextField tf = new JTextField(15); // acepta hasta 10 caracteres

    panel.add(etiqueta); // Componentes agregados usando Flow Layout
    panel.add(cantidad); // Componentes agregados usando
    panel.add(tf);
    panel.add(Buscar);
    panel.add(restablecer);

    panel2.add(cantidad);

    frame.getContentPane().add(BorderLayout.PAGE_START, panel);
    frame.getContentPane().add(BorderLayout.PAGE_END, panel2);
    frame.setVisible(true);




    Buscar.addActionListener(e -> {
        try {
            DevolverValor.Leer();
            text = tf.getText();
        } catch (FileNotFoundException ex) {
            throw new RuntimeException(ex);
        }
    });


    restablecer.addActionListener(e -> tf.setText(""));



}


    public static String getNombre() {
        return text;
    }
}

This is where I try to use the value of (text) of the Main class and then use it in DeolverValue.java which I call it as (name)

DevolverValor.java

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class DevolverValor {

public static int Leer() throws FileNotFoundException {

    String word1 = "Data:";
    String name = Main.getNombre();
    int wordCount = 0;


    File text = new File("\\\\" name "\\C$\\SITA\\BSIA.log.1");

    Scanner s = new Scanner(text);

    while (s.hasNext()) {

        if (s.next().equals(word1)) {
            wordCount  ;
        }
    }

    System.out.println(name);

    return wordCount;
}

}

When running the program returns the following error:

Error

CodePudding user response:

Text is unasinged when you try to read the first time.

Buscar.addActionListener(e -> {
    try {
        DevolverValor.Leer(); //text is null
        text = tf.getText(); // text is asigned know
    } catch (FileNotFoundException ex) {
        throw new RuntimeException(ex);
    }
});

I don't know all the code, but I move asignation to up and then text is asigned when you reat it.

In addition to eite this problem I pass the string like param:

Buscar.addActionListener(e -> {
    try {
        DevolverValor.Leer(tf.getText());
    } catch (FileNotFoundException ex) {
        throw new RuntimeException(ex);
    }
});

And then:

public static int Leer(String name) throws FileNotFoundException {

    String word1 = "Data:";
    int wordCount = 0;

    File text = new File("\\\\" name "\\C$\\SITA\\BSIA.log.1");

    Scanner s = new Scanner(text);

    while (s.hasNext()) {

        if (s.next().equals(word1)) {
            wordCount  ;
        }
    }

    System.out.println(name);

    return wordCount;
}

CodePudding user response:

Look at these two lines:

            DevolverValor.Leer();
            text = tf.getText();

You call the Leer() function which in turn calls getName() which returns the value of text. Only after you do all of this do you set the value of text.

Instead, you need to do these in the opposite order:

            text = tf.getText();
            DevolverValor.Leer();

However, it would make more sense to just pass the value of text as a parameter to Leer():

text = tf.getText();
DevolverValor.Leer(text);

This requires changing

public static int Leer() throws FileNotFoundException {

to

public static int Leer(String name) throws FileNotFoundException {

and removing String name = Main.getNombre(); from inside the function.

This will fix your immediate problem. I have a few additional tips and suggestions:

  1. Use descriptive names for variables. text isn't very descriptive. Find something that better describes what this variable represents.

  2. Learn about how to properly use classes, create instances, and access methods and fields. Also learn about what static means. All of your methods are currently static. Generally, there should only be one static method named main(). All other methods should not be static, at least for now. There are good uses for static, but as a beginner you probably will over use this. If you force yourself to not use it for a while, you will learn better habits in writing your code.

  • Related