Hello forum, Vaironl here.
I have to do an assignment for school and I was about 3 hours designing the prototype and everything was going right but I had to add arrays and a for loop to my system and after that everything just got ugly. Therefore I started from reading a file and for some reason everything works fine except printing the variable I get from the file.... Is confusing but here it is.

This is a custom class BTW.

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

public class read {
	//variables
private File file = new File("C:\\Users\\Vairon\\Documents\\Learning Java\\ReadingFiles\\src\\snakes.txt");	
private String[] name = new String[4];
private String snake; private boolean power; private int age; private double weight;

//method1
public void readf(){
	
	try{
	Scanner	scanner = new Scanner(file);
	
		while(scanner.hasNextLine()){
		name[0]= scanner.next();//add stuff after each name
		name[1]= scanner.next();
		name[2]= scanner.next();
		name[3]= scanner.next(); 
		
		System.out.println("Success \n \n");
 }
}
catch(FileNotFoundException e){
	e.printStackTrace();
}
	
	}


/*
public void convert(String snake, boolean power, int age, double weight){
snake = name[0];
power = Boolean.parseBoolean(name[1]);
age = Integer.parseInt(name[2]);
weight = Double.parseDouble(name[3]);	
}
*/

public void convert(String snake){
	snake = name[0];
	
}

public String getName(){
	return snake;
	
}
	public void showName(){
		System.out.printf(" name is %s",snake);
		
	}
	
}

everything works fine except printing the variable I get from the file.

What happens then? Can you copy and paste here the console when you run the program?
Add comments describing the problem and show what the output should be.

To copy the contents of the command prompt window:
Click on Icon in upper left corner
Select Edit
Select 'Select All' - The selection will show
Click in upper left again
Select Edit and click 'Copy'

Paste here.

scanner.next() return only 1 character each time. You should use nextLine() instead. Oh wait... Is that what you want though? If not, you need to loop through instead of doing like that. The problem is that if the line you are calling has only 3 characters, the last one will be wrong.

scanner.next() return only 1 character each time.

Hi Taywin - I think this must have been a keyboard error (I'm sure you know what next() does really) ;-)

public String next()
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.

What happens then? Can you copy and paste here the console when you run the program?
Add comments describing the problem and show what the output should be.

Well that is not a problem. The purpose of the program is to read 4 different data types and then print the contents. I'm actually suppose to use 4 arrays of Strings, booleans, ints, and doubles .
I'm just trying one line of a text file, since I thought I might confused myself if I did all 4 of them. Let me post the quote of my assignment.

You run a zoo and wish to electronically store information about a specific animal at the zoo. Create a custom class that could be used to describe the animal. Your class should have at least one String, one int, one boolean, and one double data type, as well as a way to store a String identifier (a name). Your class should have a default constructor as well as a second, overloaded constructor.

Create a second class that reads in a textfile containing an initial set of animal information and stores that information in an array. Your program should print the contents of the array using a for loop.

Therefore I believe I need 3 classes a main class, a custom class and a class which read the file.

If I'm not wrong the variables from the read class should be inserted to the custom and then be returned.

Ok back to the main question. "What happens then? Can you copy and paste here the console when you run the program?"
After inserting a String that is "empty" not null, to the parameters of convert I receive.

Success


name is null

By the way the text file says. "pokey true 5 45.5"

I'm actually suppose to use 4 arrays of Strings, booleans, ints, and doubles

Are you sure? The problem description you gave us says

Create a custom class that could be used to describe the animal. Your class should have at least one String, one int, one boolean, and one double data type, as well as a way to store a String identifier (a name). ... an initial set of animal information and stores that information in an array

That's a single array containing Animal objects, each of which has Strings etc. That's not the same as four arrays,

Are you sure? The problem description you gave us says

That's a single array containing Animal objects, each of which has Strings etc. That's not the same as four arrays,

Sorry for that, I also had problem understanding it in school. I can say that my English is not well developed and I lack communication skills. So I apologize.

So your telling me that it's basically snake1[4] snake2[4] and so on?

Something like (in pseudocode)

main class:
Animal[] allTheAnimals = new Animal[10]; // array to hold up to 10 Animals

while the user has more data to enter...
   read name, weight etc from the Scanner
   Animal nextAnimal = new Animal(name, weight ...);
   allTheAnimals[next empty array index] = nextAnimal ;

class Animal {
   String name;
   int weight;
   .....

   public Animal(String name ...   // constructor with all the values
   OR
   public Animal() {}  
   public void setName(String name)...  // defaut constructor then set the values

Going back to your original problem... about line 21 you should print out the four array elements to see if they are what you expect. If they are OK, then go a bit further down the program and print the variables there, and keep doing that until you see where things are going wrong.
This is a general process that you should use whenever you have code that's not doing what you expect.

Something like (in pseudocode)

It looks like one array holding everything I will keep trying .

That's right. One array holding lots of Animals. Each Animal has its own name, weight etc with methods to get those values when you need them

That's right. One array holding lots of Animals. Each Animal has its own name, weight etc with methods to get those values when you need them

When I print it in line 21 it works and also in the convert name, for some reason the only one which does not work is the showName.

By the way I was getting a bit confused so I made myself this picture in paint to help me better understand the concept.

[IMG]http://img153.imageshack.us/img153/1957/snakearray.jpg[/IMG]

String[] snake = snake[4];
snake[0]= new String[4] so name would be snake[0][0]... etc I think

You have too many arrays. One one-dimensional array is enough.
It is an array of Animal objects. Each Animal object has one name, one age, one weight, one boolean. You don't need any other arrays. Have another look at the pseudocode I posted earlier.

If it helps, here is a little example of the same kind of thing, using an collection of compact disks. It's not complete, and there's nothing here you can copy/paste, but if you understand it you could use it as a model for a good way to structure your application

class CD {  // each instance of this class holds info one one Compact Disk.
   private String name, artist;  
   private int duration;
   public CD(String n, String a, int d) { // constructor
      name = n;
      artist = a;
      duration = d;
   }
   public String getName() {
      return name;
   }
   public String getArtist() // etc
}

// somewhere main class:
   CD[] myCDs = new CD[100];  // just one array, 1-dimensional
   
   for (int i = 0; i<100; i++) {
      String aName = scanner.next();
      String anArtist = scanner.next();
      int aDuration = scanner.nextInt();
      myCDs [i] = new CD(aName, anArtist, aDuration)
   }


   void printAllCDs() {
      for (int i = 0; i<100; i++) {
        System.out.println(myCDs[i].getName() ... etc
      }
    }

You have too many arrays. One one-dimensional array is enough.

To tell you the truth I understand a large amount of the main idea and the code.
What I don't understand is using the class has an array.

Wouldn't that mean it's basically going to get the same names on the text file every time?
I really can't understand the pseucode well either , it is my fault but I will try my best to build the program.
Thanks for the help I will post the code as soon as I finish , I will work on it today the whole day

Hi Taywin - I think this must have been a keyboard error (I'm sure you know what next() does really) ;-)

Oops :P I didn't look at the definition of the method because I don't use it. Just thought it was that way, I am sorry. >_<

Thanks for the help I will post the code as soon as I finish , I will work on it today the whole day

OK. Concentrate on defining the Animal class and creating a single instance of that class. Don't even think about arrays until you can create a single instance.

OK. Concentrate on defining the Animal class and creating a single instance of that class. Don't even think about arrays until you can create a single instance.

I got it to work thought I really don't know how to make an array of constructors.

Main file

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package reading.files;

/**
 *
 * @author SOAD
 */
public class main {
    public static void main(String[] args){
      String n = new String();
  read reado = new read(); reado.readf();
 snakes snakeo = new snakes(reado.getName());
System.out.println(snakeo.snake1());
snakes snakeo2 = new snakes(reado.getName2());
System.out.println(snakeo2.snake1());
    }
    
}

Snakes(constructor file)

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package reading.files;

/**
 *
 * @author SOAD
 */
public class snakes {
private String snake; private boolean venomous; private int age; private double weight;
    
public snakes(){
snake = "empty";
venomous = false;
age = 2;
weight = 5.23;
    }
    
public snakes(String n){
    snake = n;
}
public String snake1(){
    return snake;
}

}

File input

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package reading.files;
import java.util.*;
import java.io.*;
 
public class read {
	//variables
private File file = new File("C:\\Users\\SOAD\\Documents\\ComputerScience\\Reading files\\src\\reading\\files\\snake.txt");	
private String[] name = new String[16]; 
//method1
public void readf(){ 
	try{
	Scanner	scanner = new Scanner(file);
 
		while(scanner.hasNextLine()){
		for (int i=0;i<16;i++){
                    name[i]= scanner.next();
                }
                 }
}
catch(FileNotFoundException e){
	e.printStackTrace();
}
     
	}

  public String getName(){
      return name[0];
  }
  public String getName2(){
      return name[4];
  }
  public String getName3(){
  return name[8];
  }
  public String getName4(){
      return name[12];
  }
  

  }

Snakes txt file

pokey true 4 2.34
sakie false 2 1.54
rackie true 1 5.12
vairon true 5 10.32

how to make an array of constructors.

You don't put constructors in the array. You put instances of the class in the array.
The class's constructor is the code that initializes the instance of the class.
You create instances of the class using new

You don't put constructors in the array. You put instances of the class in the array.
The class's constructor is the code that initializes the instance of the class.
You create instances of the class using new

Thanks once again I got it to work yesterday. Though there is one small problem when I read the files and I try to convert the String to booleans and ints etc..
I get just an empty value (I am parsing it). Does it mean the scanner is also reading the white space in my textfile?
in my teacher's example she separated the words/arguments with a %. Any ideas.

when I read the files and I try to convert the String to booleans and ints etc..
I get just an empty value

Can you show the code and the contents of the file it is reading?

Can you show the code and the contents of the file it is reading?

This might look a little messy but the focus is on the read file. The snake file is the same.

Main:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package reading.files;

/**
 *
 * @author SOAD
 */
public class main {
    public static void main(String[] args){
      String n = new String();
  read reado = new read(); reado.readf(); reado.stringToBoolean();
snakes[] snakesArray = new snakes[4];

snakesArray[0] = new snakes(reado.getName(),reado.getBoolean(),reado.getInt(),reado.getDouble());
snakesArray[1] = new snakes(reado.getName2(),reado.getBoolean2(),reado.getInt2(),reado.getDouble2());
snakesArray[2] = new snakes(reado.getName3(),reado.getBoolean3(),reado.getInt3(), reado.getDouble3());
snakesArray[3] = new snakes(reado.getName4(), reado.getBoolean4(),reado.getInt4(),reado.getDouble4());
 for(int i= 0; i<4;i++){
   System.out.println(snakesArray[i].snake1()+"\n");
 }
        
    }
    
}

Read:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package reading.files;
import java.util.*;
import java.io.*;
 
public class read {
	//variables
private File file = new File("C:\\Users\\SOAD\\Documents\\ComputerScience\\Reading files\\src\\reading\\files\\snake.txt");	
private String[] name = new String[16];
private boolean[] bools = new boolean[4];
private int[] age = new int[4];
private double[] weight = new double[4];

public void readf(){ 
	try{
	Scanner	scanner = new Scanner(file);
 
		while(scanner.hasNextLine()){
		for (int i=0;i<16;i++){
                    name[i]= scanner.next();
                }
                 }
}
catch(FileNotFoundException e){
	e.printStackTrace();
}
     
	}
        
public void stringToBoolean(){
   for (int i=1; i<14;i+=4){
       int o = 0;
       bools[o]= Boolean.parseBoolean(name[i]);
               o++;
   }
}
public void stringToInt(){
    for (int i=2; i<15;i+=4){
        int o = 0;
        age[o]= Integer.parseInt(name[i]);
        o++;
    }
   
    }
    
     public void stringToDouble(){
        for(int i= 3;i<16;i+=4){
            int o = 0;
            weight[o]= Double.parseDouble(name[i]);
            o++;
        }
     }

  public String getName(){return name[0];} public boolean getBoolean(){return bools[0];} public int getInt(){return age[0];} public double getDouble(){return weight[0];}
  public String getName2(){return name[4];} public boolean getBoolean2(){return bools[1];} public int getInt2(){return age[1];} public double getDouble2(){return weight[1];}
  public String getName3(){return name[8];} public boolean getBoolean3(){return bools[2];} public int getInt3(){return age[2];} public double getDouble3(){return weight[2];}
  public String getName4(){return name[12];} public boolean getBoolean4(){return bools[3];} public int getInt4(){return age[3];} public double getDouble4(){return weight[3];}
  

  }

snakes(constructor)

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package reading.files;

/**
 *
 * @author SOAD
 */
public class snakes {
private String snake; private boolean venomous; private int age; private double weight;
    
public snakes(){
snake = "empty";
venomous = false;
age = 2;
weight = 5.23;
    }
    
public snakes(String n, boolean v, int a, double w){
    snake = n;
    venomous = v;
    age = a;
    weight =w;
}
public String snake1(){
    return snake;
}
}

Too much code to just read a file. Also you forgot to post the contents of the file.
Make a small program 20-30 lines that reads the file and displays its contents.

problem when I read the files and I try to convert the String to booleans and ints etc.. I get just an empty value (I am parsing it).

This is the problem we're trying to solve.
Is the problem in the reading or in the parsing?

The rest of the code you posted is in the way for solving the problem.

If you can't make a small program, then try debugging your code by adding printlns to every place that the data goes from when it is read in to where it is becoming empty.
Print out all the values of all the variables the data is assigned to.
If you read the data ok, then somewhere in the process of getting it to the variables it is being lost. Print out the history of where it goes and maybe you'll see where.

If you can't make a small program, then try debugging your code by adding printlns to every place that the data goes from when it is read in to where it is becoming empty.
Print out all the values of all the variables the data is assigned to.
If you read the data ok, then somewhere in the process of getting it to the variables it is being lost. Print out the history of where it goes and maybe you'll see where.

Thanks for the suggestion I was doing that earlier but I din't know it might become that useful.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.