java How to load in a string value - java

Hello I have an application that loads in values. The values are x,y,and a string value. I want to know how to load in a string because I only know how to o it with an integer. Take a look at this code:
public static void loadStars() {
try {
BufferedReader bf = new BufferedReader(new FileReader ("files/cards.txt"));
for (int i = 0; i < 10; i++) {
String line;
while ((line = bf.readLine()) != null) {
String[] args = line.split(" ");
int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]);
String name = Integer.parseInt(args[2]);
play.s.add(new Star(x,y,name));
}
}
bf.close();
} catch (Exception e) {
e.printStackTrace();
}
}
I have
play.s.add(new star(x,y,name));
I know how to load in x and y but I don't know how to load in name.
Please help me.
Edit----
In the file that is loaded in it is formatted like this:
x y name
example:
10 10 jack
100 500 conor
each star is represented by 1 line.
public class Star extends BasicStar {
private Image img;
public Star(int x, int y,String starname) {
this.x = x;
this.y = y;
this.starname = starname;
r = new Rectangle(x, y, 3, 3);
}
public void tick() {
if (r.contains(Comp.mx, Comp.my) && Comp.ml) {
remove = true;
}
}
public void render(Graphics g) {
if (!displaySolar) {
ImageIcon i2 = new ImageIcon("res/planets/star.png");
img = i2.getImage();
g.drawImage(img, x, y, null);
}
}
}

Array args[] is already String so you just need to change
String name = Integer.parseInt(args[2]);
to
String name = args[2];
And that's it.

Try this.
public static void loadStars() {
try {
BufferedReader bf = new BufferedReader(new FileReader ("files/cards.txt"));
for (int i = 0; i < 10; i++) {
String line;
while ((line = bf.readLine()) != null) {
String[] args = line.split(" ");
int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]);
String name = args[2]; // args array contain string, no need of conversion.
play.s.add(new Star(x,y,name));
}
}
bf.close();
} catch (Exception e) {
e.printStackTrace();
}
}

you improve your code by using a StringTokenizer. Try This.
public static void loadStars()
throws IOException {
String line;
BufferedReader bf = new BufferedReader(new FileReader ("files/cards.txt"));
try
{
while((line = bf.readLine()) != null)
{
if (line == null || line.trim().isEmpty())
throw new IllegalArgumentException(
"Line null!");
StringTokenizer tokenizer = new StringTokenizer(line, " ");
if (tokenizer.countTokens() < 3)
throw new IllegalArgumentException(
"Token number not valid (<= 3)");
int x, y;
String xx = tokenizer.nextToken(" ").trim();
String yy = tokenizer.nextToken(" ").trim();
String name = tokenizer.nextToken(" ").trim();
try
{
x = Integer.parseInt(xx);
}catch(ParseException e){throw new IllegalArgumentException(
"Number format not valid!");}
try
{
y = Integer.parseInt(yy);
}catch(ParseException e){throw new IllegalArgumentException(
"Number format not valid!");}
play.s.add(new Star(x,y,name));
}
} catch (NoSuchElementException | NumberFormatException | ParseException e) {
throw new IllegalArgumentException(e);
}
}

Array args[] is already String so you just need to change
String name = Integer.parseInt(args[2]);
// If you are using this values anywhere else you'd do this so de GC can collects the arg[] array
String name = new String(args[2]);
Be aware that if you have spaces in string arguments each word will be a new argument. If you have a call like:
java -jar MyProgram 1 2 This is a sentence.
Your arg[] will be:
{"1", "2", "This", "is", "a", "sentence."}
If you need the sentence to be one String you should use apostrophes:
java -jar MyProgram 1 2 "This is a sentence."
Your arg[] will be:
{"1", "2", "This is a sentence."}

Related

Java set array size of 2D-array after declaration

I have a method that should return a 2D-array which is always structured like this:
int [][] = {{100}, {5}, {1,5,7,8,30,60,...}
My problem is that when I call the method I don't know how long the 3rd array will be. This is my code right now:
public static int[][] readFile(int max, int types, String fileName) {
int [][]result = new int[3][];
try {
FileReader reader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
int currentLine = 0;
while ((line = bufferedReader.readLine()) != null) {
String[] numbers = line.split(" ");
System.out.println(line);
if (currentLine == 0) {
result[0][0] = Integer.parseInt(numbers[0]);
result[1][0] = Integer.parseInt(numbers[1]);
}else if (currentLine == 1) {
int []theSlices = new int[numbers.length];
result[2][0] = theSlices; //-> obviously error
for(int i = 0; i<numbers.length; i++) {
theSlices[i] = Integer.parseInt(numbers[i]);
}
return result;
}
currentLine++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
;
return null;
}
My code right now is obviously not working but how can I fix it? Happy for every help :)

How to read float values from a file and initialize array?

i am trying to read float values from a .txt file to initialize an array but it is throwing a InputMismatchException
Here's the method and the sample values i am trying to read from the file are 4 2 1 4
public class Numbers {
private Float [] numbers;
public int default_size = 10;
String fileName = new String();
public void initValuesFromFile()
{
Scanner scan = new Scanner(System.in);
fileName = scan.next();
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader(fileName));
String input = null;
while ((input = reader.readLine()) != null) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Float.parseFloat(input);
}
}
}
catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
}
}
You need to read line from the file and split using space or even better \\s+ and then run a for loop for all items split into an array of strings and parse each number and store them in a List<Float> and this way will work even if you have multiple numbers in further different lines. Here is the code you need to try,
Float[] numbers = new Float[4];
Scanner scan = new Scanner(System.in);
String fileName = scan.next();
scan.close();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(fileName));
String input = null;
while ((input = reader.readLine()) != null) {
String nums[] = input.trim().split("\\s+");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Float.parseFloat(nums[i]);
}
break;
}
System.out.println(Arrays.toString(numbers));
} catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
This prints,
[4.0, 2.0, 1.0, 4.0]

How a read a txt file in a array and then print in console some value in Java?

I have a problem. I have a txt file with some value, and I try to use eclipse to read and parse that txt file in a array and then put some condition to write that array in console. The text that I use to read txt file and parse in array is this:
public void Transaction(String filepath, String user)
{
String [] [] myArray = new String[100][3];
Scanner scanIn = null;
int Rowc = 0, Colc = 0;
String InputLine = "";
double xnum = 0;
String username, tranzactie, info;
try
{
scanIn = new Scanner ( new BufferedReader(new FileReader(filepath)));
while(scanIn.hasNextLine())
{
InputLine = scanIn.nextLine();
String[] InArray = InputLine.split(",");
for(int x = 0; x<InArray.length; x++)
{
myArray[Rowc][x] = InArray[x];
}
Rowc++;
}
for (int i = 0; i<Rowc; i++)
{
for (Colc = 0; Colc < 3; Colc ++)
{
System.out.print(myArray[i][Colc]+ ",");
}
System.out.println();
}
}catch (Exception e)
{
System.out.println("Error");
}
}
The txt file is this:
John,SoldInterogation
John,PayInvoice,He pay 30 EUR
Alex,PayInvoice,He pay 15 EUR
Alex,BankTransfer,He transfered 50 EUR
John,SoldInterogation
How can I write in the console just the transaction for john or Alex, or ... . What I must adding in my java code for do this? I must write only the transaction, this mean only the 2 column of the txt file, the user ( John, Alex) this musn't write in the console.
Just test if InArray is length 3, and if it is : add its two last strings to a String variable.
Then just println this String variable after your reading loops.
try
{
// A String variable to println after the reading.
String consoleResume = "";
scanIn = new Scanner ( new BufferedReader(new FileReader(filepath)));
while(scanIn.hasNextLine())
{
InputLine = scanIn.nextLine();
String[] InArray = InputLine.split(",");
for(int x = 0; x<InArray.length; x++)
{
myArray[Rowc][x] = InArray[x];
}
// There is a transaction when you have 3 strings in InArray
if (InArray.length()==3)
consoleResume+=InArray[1]+":"+InArray[2]+"\n";
Rowc++;
}
System.out.println(consoleResume);
}catch (Exception e)
{
System.out.println("Error");
}
You can also println the transactions inside your loop :
try
{
scanIn = new Scanner ( new BufferedReader(new FileReader(filepath)));
while(scanIn.hasNextLine())
{
InputLine = scanIn.nextLine();
String[] InArray = InputLine.split(",");
for(int x = 0; x<InArray.length; x++)
{
myArray[Rowc][x] = InArray[x];
}
// There is a transaction when you have 3 strings in inArray
if (InArray.length()==3)
System.out.println(InArray[1]+":"+InArray[2]);
Rowc++;
}
}catch (Exception e)
{
System.out.println("Error");
}

How to read certain char to certain char from file in java?

I have a text file, which contains positions like this:
The #p shows the x, y coordinates, so the first * after the #p row is at (6, -1). I would like to read the text file as blocks (one block is from the #p to the next #p row).
try {
File file = new File("filename.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
if (line.startsWith("#P")){
Scanner s = new Scanner(line).useDelimiter(" ");
List<String> myList = new ArrayList<String>();
while (s.hasNext()) {
myList.add(s.next());
}
for (int i=0; i<myList.size(); i++){
System.out.println(myList.get(i));
}
System.out.println("xy: "+myList.get(1)+", "+myList.get(2));
}
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
I want to store the coordinates in a two dimensional array, but there goes my other problem. How can I store etc -1, -1?
This doesn't completely solve your problem, but one option here is to use a map to store each block of text, where a pair of coordinates is a key, and the text a value.
Map<String, String> contentMap = new HashMap<>();
String currKey = null;
StringBuffer buffer = new StringBuffer();
while ((line = bufferedReader.readLine()) != null) {
if (line.startsWith("#P")) {
// store previous paragraph in the map
if (currKey != null) {
contentMap.put(currKey, buffer.toString());
buffer = new StringBuffer();
}
currKey = line.substring(3);
}
else {
buffer.append(line).append("\n");
}
}
Once you have the map in memory, you can either use it as is, or you could iterate and somehow convert it to an array.
byte[][] coords = new byte[X_MAX - X_MIN + 1][Y_MAX - Y_MIN + 1]; //your array with 0 and 1 as you wished
try {
File file = new File("filename.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
//StringBuffer stringBuffer = new StringBuffer(); //i don't c why you need it here
String line;
while ((line = bufferedReader.readLine()) != null) {
//stringBuffer.append(line);
//stringBuffer.append("\n");
if (line.startsWith("#P")){
String[] parts = line.split(" ");
int x = Integer.parseInt(parts[1]);
int y = Integer.parseInt(parts[2]);
coords[x - X_MIN][y - Y_MIN] = 1;
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
Array indices in Java always start at 0. But that's not really a problem if you know the total ranges of your x and y values (X_MIN <= x < X_MAX and Y_MIN <= y < Y_MAX):
coor[X_MAX - X_MIN + 1][Y_MAX - Y_MIN + 1];
...
void setValue( int x, int y, int value ) {
coor[x - X_MIN][y - Y_MIN] = value;
}
int getValue( int x, int y ) {
return coor[x + X_MIN][y + Y_MIN];
}
A nicer solution would wrap the array into a class, provide range checking and maybe use a different container like ArrayList<ArrayList<int>> .

Reading data file into multidimensional array Java

I have a .dat file that I want to load into a custom array. How do I get it to actually load the data into the array. The data consists of a (String, int, int, double, String).
class CDinventoryItem{
private CDinventoryItem [] inven = new CDinventoryItem[1000];
public CDinventoryItem (String title, int itemNumber, int numberofUnits,
double unitPrice, String genre){
DataInputStream input;
try{
input = new DataInputStream(new FileInputStream("inventory.dat"));
inven = input.read(CDinventoryItem[]); //line I am receiving error on
}
catch ( IOException error ){
JOptionPane.showMessageDialog( null, "File not found",
"" ,JOptionPane.ERROR_MESSAGE);
}
}
}
So now readFile is in its own class...
class readFile {
public CDinventoryItem[] inven;
public readFile(){
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("inventory.dat"));
String line = null;
int i = 0;
while ((line = in.readLine()) != null) {
// process each line
String[] parts = line.split(",");
String title = parts[0];
int itemNumber = Integer.parseInt(parts[1]);
int numberofUnits = Integer.parseInt(parts[2]);
double unitPrice = Double.parseDouble(parts[3]);
String genre = parts[4];
CDinventoryItem item = new CDinventoryItem(title, itemNumber, numberofUnits,
unitPrice, genre);
//add item to array
inven[i] = item;
i++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}}
and I am calling it from my CDinventory class
readFile invenItem = new readFile();
list = new JList(invenItem.inven);
but it gives me a: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
on line:
readFile invenItem = new readFile();
Doesn't seem to like me passing the array that way.
You need to read the file line by line. Split each line on , and create a single CDInventoryItem. Add the item to your array.
Also, note that this method should not be in the constructor of CDInventoryItem. Your CDInventoryItem class should not even have an array of CDInventoryItems. All this should be done in a separate class.
Here is some code to get you started:
public void readFile() {
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("inventory.dat"));
String line = null;
int i = 0;
while ((line = in.readLine()) != null) {
// process each line
String[] parts = line.split(",");
String title = parts[0];
int itemNumber = Integer.parseInt(parts[1]);
int numberOfUnits = Integer.parseInt(parts[2]);
double unitPrice = Double.parseDouble(parts[3]);
String genre = parts[4];
CDinventoryItem item = new CDinventoryItem(title, itemNumber, unitPrice, genre);
//add item to array
inven[i] = item;
i++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Categories