Forums > Java

make variable from inlet input, use in other objects

April 20, 2011 | 5:46 pm

I’m trying to set the filepath for a Scanner object, but I can’t get the class to resolve the variable from my inlet class.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

import com.cycling74.max.*;

public class LineReader extends MaxObject {

public LineReader() {
declareInlets(new int[]{DataTypes.INT,DataTypes.ALL});
declareOutlets(new int[]{DataTypes.INT,DataTypes.ALL});
}
public class Fold {
public static String sc;
}

public void input(String Fold.sc, Atom[] args) {
Scanner sc = new Scanner(new File());
if (getInlet() == 1){
post("hello anything " + Fold.sc + " " + Atom.toOneString(args) + "!");
outlet(1, s, args);

} else
post("uh");
}
public void inlet(int a) {
//post("hello integer " + a + "!");
//outlet(0, a);

String info = "";
int startLine = a;
int endLine = a;
// read prior junk
System.out.println();
for (int i = 0; i < startLine; i++) { info = sc.readLine(); }
for (int i = startLine; i < endLine + 1; i++) {
info = sc.readLine();
System.out.println(info);
post("hello integer " + a + "!");
outlet(0, info);
}
}
}

Any help is appreciated.


April 21, 2011 | 3:05 pm

Hi
I can see a few problems in your code:

Scanner doesn’t have a readLine method – it should be nextLine().

The File constructor needs an argument for the filepath.

You’ve declared a static variable in the inner class Fold – this isn’t allowed in an inner class. I’m not certain what you’re trying to do here.

By default Scanner is searching for white space – not a new line. You can change this with its useDelimiter method

Using a Scanner, you must create a new scanner and step through the whole file from the start every time you want to read a line. An alternative would be to scan the whole file in your input method (storing the lines in an ArrayList or similar), then reading the relevant line from the list in your inlet method.

e.g.:


import java.io.*;
import java.util.Scanner;
import com.cycling74.max.*;
import java.util.ArrayList;
import java.util.List;

public class linereader extends MaxObject {

   private List lines;

   public linereader() {
      declareInlets(new int[]{DataTypes.INT, DataTypes.ALL});
      declareOutlets(new int[]{DataTypes.INT, DataTypes.ALL});
      lines = new ArrayList();
   }

   public void input(Atom[] args) {
      try {
         Scanner sc = new Scanner(new File(Atom.toOneString(args)));
         sc.useDelimiter("n");

         lines.clear();
         while (sc.hasNextLine())
            lines.add(sc.nextLine());

         sc.close();
      }
      catch(FileNotFoundException fnfe) {
         fnfe.printStackTrace();
      }
   }

   @Override
   public void inlet(int line) {
      if (line >= 0 && line < lines.size())
         outlet(0, lines.get(line));
   }

}

HTH a bit


Viewing 2 posts - 1 through 2 (of 2 total)