1

Java is returning string values when reading off a text file, but it will only return "0" for my integer values and "0.0" for my doubles.

  Cars car[] = new Cars[5];
  int cnt = 0;
  String line = inF.readLine();

  while(line != null){
     String[] field = line.split("\\s+");

     int yrData = Integer.parseInt(field[2]);
     double disData = Double.parseDouble(field[3]);

     car[cnt] = new Cars(field[0], field[1], yrData, disData);
     cnt++; 
     line = inF.readLine();
  }

  for(int i=0; i<cnt;  i++){
     System.out.println(i+1 +": "+ car[i]);
  }

Example: What Java Returns---> 1: Name: Opel Model: Astra Year: 0 Disp: 0.0

What is in the text file:Opel Astra 1997 2.8

This is my constructor:

Cars(String dataForName, String dataForModel, int dataForYear, double dataForDisp){name = dataForName; model = dataForModel; int year = dataForYear; double disp = dataForDisp;}

This is my toString method:

public String toString(){String s = "Name: "+name+" Model: "+model+" Year: "+year+" Disp: "+disp; return s;}

The delimiter of the text is space(s).

3
  • 2
    Can you include the code for you constructor? This should work. Commented May 28, 2015 at 18:28
  • And for the toString method as well. Commented May 28, 2015 at 18:37
  • What is the Delimiter of the text? is it space(s) (or) TAB (\t) ? Commented May 28, 2015 at 18:39

1 Answer 1

3

The problem is in your constructor:

Cars(String dataForName, String dataForModel, int dataForYear, double dataForDisp){
    name = dataForName; 
    model = dataForModel; 
    int year = dataForYear; 
    double disp = dataForDisp;
}

you declare a new variable year and disp inside the constructor instead of setting the field in your class. As a result, those values are never set so they use the default values of 0 and 0.0 respectively.

changing it to

 Cars(String dataForName, String dataForModel, int dataForYear, double dataForDisp){
    name = dataForName; 
    model = dataForModel; 
    year = dataForYear; 
    disp = dataForDisp;
 }

should work.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.