I'm trying to scan a text file that has a format like this:
reviewers: 0
open: Sunday 08:00 16:00,Monday 06:00 20:00,Tuesday 06:00 20:00,Wednesday 06:00 20:00,Thursday 06:00 20:00,Friday 06:00 20:00,Saturday 06:00 01:00
name: The Lyre of Orpheus
city: San Francisco
cost: $$
category: Greek,Breakfast & Brunch,Seafood,Salad,Soup
rank: 0
and saving each line as a string or double, but i keep getting null with the sys.out.println inside of my forloop, anything I can change? My thought is that I'm resetting my variables inside my try too early or something.
public class Yulp {
//instance vars
ArrayList<Restaurant> resList = new ArrayList<Restaurant>();
public static void main(String args[]) {
Yulp yelp = new Yulp();
yelp.scan();
for(int i = 0; i < yelp.resList.size(); i++){
System.out.println(yelp.resList.get(i).getCity());
}
}
public void scan() {
try {
Restaurant tempRes = new Restaurant();
String name, city, category, cost;
double rank, reviewers;
Scanner scan = new Scanner(new File("randomizedList.txt"));
while (scan.hasNext()) {
//name = null; city = null; category = null; cost = null; rank = 0.0; reviewers = 0;
String line = scan.nextLine();
String rest = omitPrefix(line, "reviewers:");
if (rest != null) {
reviewers = Double.parseDouble(rest);
tempRes.setReviewers(reviewers);
}
rest = omitPrefix(line, "rank:");
if (rest != null) {
rank = Double.parseDouble(rest);
}
rest = omitPrefix(line, "name:");
if (rest != null) {
name = rest;
}
rest = omitPrefix(line, "city:");
if (rest != null) {
city = rest;
}
rest = omitPrefix(line, "category:");
if (rest != null) {
category = rest;
}
rest = omitPrefix(line, "cost:");
if (rest != null) {
cost = rest;
}
resList.add(tempRes);
}
scan.close();
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
}
private String omitPrefix(String line, String prefix) {
if (line.startsWith(prefix))
return line.substring(prefix.length());
return null;
}
}
Here's what I have
import java.io.InputStream;
import java.util.Scanner;
public class Snippet {
public void scan() throws Exception {
Scanner scan = new Scanner(new File("randomizedList.txt"));
while (scan.hasNext()) {
String line = scan.nextLine();
String rest = omitPrefix(line, "reviewers:");
if (rest != null) {
System.out.println(rest);
}
rest = omitPrefix(line, "name:");
if (rest != null) {
System.out.println(rest);
}
rest = omitPrefix(line, "city:");
if (rest != null) {
System.out.println(rest);
}
rest = omitPrefix(line, "category:");
if (rest != null) {
System.out.println(rest);
}
}
scan.close();
}
private String omitPrefix(String line, String prefix) {
if (line.startsWith(prefix))
return line.substring(prefix.length());
return null;
}
public static void main(String[] args) throws Exception {
new Snippet().scan();
}
}
Main points:
Instead of line = new Scanner(scan.nextLine()); temp = line.nextLine(); you can just do scan.nextLine.
For getting the remainder of a line (for instance the part that follows the "name:" part) I introduced a helper method called omitPrefix(line, prefix) which returns line sans prefix if line starts with prefix, or null otherwise.
Here's another way of doing it.
public class FileParser {
public void scan() {
try {
File list = new File("randomizedList.txt");
Scanner scan = new Scanner(list);
String temp;
Scanner line;
while (scan.hasNext()) {
line = new Scanner(scan.nextLine());
temp = line.nextLine();
if (temp.startsWith("reviewers:")) {
System.out.println(temp.split(":",2)[1]);
}
if (temp.startsWith("name:",1)) {
System.out.println(temp.split(":",2)[1]);
}
if (temp.startsWith("open:")) {
System.out.println(temp.split(":",2)[1]);
}
if (temp.startsWith("city:")) {
System.out.println(temp.split(":",2)[1]);
}
if (temp.startsWith("category:")) {
System.out.println(temp.split(":",2)[1]);
}
}
scan.close();
}
catch(FileNotFoundException e){
System.out.println("File's MISSIN!");
}
catch(NoSuchElementException e){
System.out.println("NoSuchElementException dangus.");
}
}
public static void main(String[] args) {
new FileParser().scan();
}
}
Check the line with startsWith to find the introductory key word.
Then use split the string around the : which returns an array of two strings.
The second string in the returned array is reached by [1] and this produces the above output
There are further improvements that can be made to this code though.
The if statements should be refactored and extracted as a separate method.
The strings constants should extracted and each line should only be checked once.
Once a match is made you should move on to the next line.
Related
I am reading a file with a disease name and its remedies. Therefore, i want to save the name as key and remedies in a set as the value. How can i reach that? It seems there is some problems in my code.
public static HashMap<String,Set<String>> disease = new HashMap <> ();
public static void main(String[] args) {
Scanner fin = null;
try {
fin = new Scanner (new File ("diseases.txt"));
while (fin.hasNextLine()) {
HashSet <String> remedies = null;
String [] parts = fin.nextLine().split(",");
int i = 1;
while (fin.hasNext()) {
remedies.add(parts[i].trim());
i++;
}
disease.put(parts[0],remedies);
}
fin.close();
}catch(Exception e) {
System.out.println("Error: " + e.getMessage());
}
finally {
try {fin.close();} catch(Exception e) {}
}
Set <String> result = disease.get("thrombosis");
display(result);
public static <T> void display (Set<T> items) {
if (items == null)
return;
int LEN = 80;
String line = "[";
for (T item:items) {
line+= item.toString() + ",";
if (line.length()> LEN) {
line = "";
}
}
System.out.println(line + "]");
}
here is my code
cancer,pain,swelling,bleeding,weight loss
gout,pain,swelling
hepatitis A,discoloration,malaise,tiredness
thrombosis,high heart rate
diabetes,frequent urination
and here is what the txt contains.
In your code , you haven't initialized the remedies HashSet(thats why it is throwing NullPointerException at line number 14).
and second issue is : i is getting incremented by 1 and you are not checking with size of your pats array ( i > parts.length) .
I edited your code :
Scanner fin = null;
try {
fin = new Scanner(new File("diseases.txt"));
while (fin.hasNextLine()) {
HashSet<String> remedies = new HashSet<String>();
String[] parts = fin.nextLine().split(",");
int i = 1;
while (fin.hasNext()&&parts.length>i) {
remedies.add(parts[i].trim());
i++;
}
disease.put(parts[0], remedies);
}
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
import java.io.File;
import java.util.Set;
public class Solution {
public static HashMap<String, Set<String>> disease = new HashMap<>();
public static void main(String[] args) {
Scanner fin = null;
try {
fin = new Scanner (new File("diseases.txt"));
while (fin.hasNextLine()) {
HashSet <String> remedies = new HashSet<>();
String [] parts = fin.nextLine().split(",");
for (int i=1; i < parts.length; i++) {
remedies.add(parts[i].trim());
}
disease.put(parts[0],remedies);
}
fin.close();
}catch(Exception e) {
System.out.println("Error: " + e.getMessage());
}
finally {
try {fin.close();} catch(Exception e) {}
}
Set <String> result = disease.get("thrombosis");
display(result);
}
public static <T> void display(Set<T> items) {
if (items == null)
return;
int LEN = 80;
String line = "[";
for (T item : items) {
line += item.toString() + ",";
if (line.length() > LEN) {
line = "";
}
}
System.out.println(line + "]");
}
}
Here is full working code. As suggested by #Pratik that you forget to initialize HashSet that's why NullPointerException error was coming.
You have a few issues here:
no need for inner while loop (while (fin.hasNext()) {) - instead use `for(int i=1; i
HashSet <String> remedies = null; - this means the set is not initialized and we cannot put items in it - nede to change to: HashSet<String> remedies = new HashSet<>();
It is better practice to close() the file in the finally part
The 'display' method will delete the line (if it is longer than 80 characters) before printing it.
it is better to use StringBuilder when appending strings
So the corrected code would be:
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class TestSOCode {
public static HashMap<String,Set<String>> disease = new HashMap<>();
private static int LINE_LENGTH = 80;
public static void main(String[] args) {
Scanner fin = null;
try {
fin = new Scanner(new File("diseases.txt"));
while (fin.hasNextLine()) {
HashSet<String> remedies = new HashSet<>();
String[] parts = fin.nextLine().split(",");
disease.put(parts[0], remedies);
for (int i = 1; i < parts.length; i++) {
remedies.add(parts[i].trim());
}
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
} finally {
try {
fin.close();
} catch (Exception e) {
System.out.println("Error when closing file: " + e.getMessage());
}
}
Set<String> result = disease.get("thrombosis");
display(result);
}
public static <T> void display (Set<T> items) {
if (items == null)
return;
StringBuilder line = new StringBuilder("[");
int currentLength = 1; // start from 1 because of the '[' char
for (T item:items) {
String itemStr = item.toString();
line.append(itemStr).append(",");
currentLength += itemStr.length() + 1; // itemStr length plus the ',' char
if (currentLength >= LINE_LENGTH) {
line.append("\n");
currentLength = 0;
}
}
// replace last ',' with ']'
line.replace(line.length() - 1, line.length(), "]");
System.out.println(line.toString());
}
}
I'm doing a Phone Directory project and we have to read from a directory file telnos.txt
I'm using a Scanner to load the data from the file telnos.txt, using a loadData method from a previous question I asked here on StackOverflow.
I noticed attempts to find a user always returned Not Found, so I added a few System.out.printlns in the methods to help me see what was going on. It looks like the scanner isn't reading anything from the file. Weirdly, it is printing the name of the file as what should be the first line read, which makes me think I've missed something very very simple here.
Console
run:
telnos.txt
null
loadData tested successfully
Please enter a name to look up: John
-1
Not found
BUILD SUCCESSFUL (total time: 6 seconds)
ArrayPhoneDirectory.java
import java.util.*;
import java.io.*;
public class ArrayPhoneDirectory implements PhoneDirectory {
private static final int INIT_CAPACITY = 100;
private int capacity = INIT_CAPACITY;
// holds telno of directory entries
private int size = 0;
// Array to contain directory entries
private DirectoryEntry[] theDirectory = new DirectoryEntry[capacity];
// Holds name of data file
private final String sourceName = "telnos.txt";
File telnos = new File(sourceName);
// Flag to indicate whether directory was modified since it was last loaded or saved
private boolean modified = false;
// add method stubs as specified in interface to compile
public void loadData(String sourceName) {
Scanner read = new Scanner("telnos.txt").useDelimiter("\\Z");
int i = 1;
String name = null;
String telno = null;
while (read.hasNextLine()) {
if (i % 2 != 0)
name = read.nextLine();
else
telno = read.nextLine();
add(name, telno);
i++;
}
}
public String lookUpEntry(String name) {
int i = find(name);
String a = null;
if (i >= 0) {
a = name + (" is at position " + i + " in the directory");
} else {
a = ("Not found");
}
return a;
}
public String addChangeEntry(String name, String telno) {
for (DirectoryEntry i : theDirectory) {
if (i.getName().equals(name)) {
i.setNumber(telno);
} else {
add(name, telno);
}
}
return null;
}
public String removeEntry(String name) {
for (DirectoryEntry i : theDirectory) {
if (i.getName().equals(name)) {
i.setName(null);
i.setNumber(null);
}
}
return null;
}
public void save() {
PrintWriter writer = null;
// writer = new PrintWriter(FileWriter(sourceName));
}
public String format() {
String a;
a = null;
for (DirectoryEntry i : theDirectory) {
String b;
b = i.getName() + "/n";
String c;
c = i.getNumber() + "/n";
a = a + b + c;
}
return a;
}
// add private methods
// Adds a new entry with the given name and telno to the array of
// directory entries
private void add(String name, String telno) {
System.out.println(name);
System.out.println(telno);
theDirectory[size] = new DirectoryEntry(name, telno);
size = size + 1;
}
// Searches the array of directory entries for a specific name
private int find(String name) {
int result = -1;
for (int count = 0; count < size; count++) {
if (theDirectory[count].getName().equals(name)) {
result = count;
}
System.out.println(result);
}
return result;
}
// Creates a new array of directory entries with twice the capacity
// of the previous one
private void reallocate() {
capacity = capacity * 2;
DirectoryEntry[] newDirectory = new DirectoryEntry[capacity];
System.arraycopy(theDirectory, 0, newDirectory,
0, theDirectory.length);
theDirectory = newDirectory;
}
}
ArrayPhoneDirectoryTester.java
import java.util.Scanner;
public class ArrayPhoneDirectoryTester {
public static void main(String[] args) {
//create a new ArrayPhoneDirectory
PhoneDirectory newTest = new ArrayPhoneDirectory();
newTest.loadData("telnos.txt");
System.out.println("loadData tested successfully");
System.out.print("Please enter a name to look up: ");
Scanner in = new Scanner(System.in);
String name = in.next();
String entryNo = newTest.lookUpEntry(name);
System.out.println(entryNo);
}
}
telnos.txt
John
123
Bill
23
Hello
23455
Frank
12345
Dkddd
31231
In your code:
Scanner read = new Scanner("telnos.txt");
Is not going to load file 'telnos.txt'. It is instead going to create a Scanner object that scans the String "telnos.txt".
To make the Scanner understand that it has to scan a file you have to either:
Scanner read = new Scanner(new File("telnos.txt"));
or create a File object and pass its path to the Scanner constructor.
In case you are getting "File not found" errors you need to check the current working directory. You could run the following lines and see if you are indeed in the right directory in which the file is:
String workingDir = System.getProperty("user.dir");
System.out.println("Current working directory : " + workingDir);
You need to also catch the FileNotFoundException in the function as follows:
public void loadData(String sourceName) {
try {
Scanner read = new Scanner(new File("telnos.txt")).useDelimiter("\\Z");
int i = 1;
String name = null;
String telno = null;
while (read.hasNextLine()) {
if (i % 2 != 0)
name = read.nextLine();
else {
telno = read.nextLine();
add(name, telno);
}
i++;
}
}catch(FileNotFoundException ex) {
System.out.println("File not found:"+ex.getMessage);
}
}
You are actually parsing the filename not the actual file contents.
Instead of:
new Scanner("telnos.txt")
you need
new Scanner( new File( "telnos.txt" ) )
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
I keep getting an error with my program after it craws the first 2 URL's "Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 0". The first couple of URL's craw as I want them to and I get the text from them using a method in another class. The other class could be the problem I don't know. Please have a look at my code and see whats happening.
package WebCrawler;
import java.util.Scanner;
import java.util.ArrayList;
import static TextAnalyser.Textanalyser.analyse;
public class Crawler {
public static void main(String[] args) {
// java.util.Scanner input = new java.util.Scanner(System.in);
// System.out.print("Enter a URL: ");
// String url = input.nextLine();
crawler("http://www.port.ac.uk/"); // Traverse the Web from the a starting url
}
public static void crawler(String startingURL) {
ArrayList<String> listOfPendingURLs = new ArrayList<String>();
ArrayList<String> listOfTraversedURLs = new ArrayList<String>();
listOfPendingURLs.add(startingURL);
while (!listOfPendingURLs.isEmpty() && listOfTraversedURLs.size() <= 100) {
String urlString = listOfPendingURLs.remove(0);
if (!listOfTraversedURLs.contains(urlString)) {
listOfTraversedURLs.add(urlString);
String text = urlString;
text = ReadTextfromURL.gettext(text);
text = analyse(text);
System.out.println("text : " + text);
System.out.println("Craw " + urlString);
for (String s: getSubURLs(urlString)) {
if (!listOfTraversedURLs.contains(s)) {
listOfPendingURLs.add(s);
}
}
}
}
}
public static ArrayList<String> getSubURLs(String urlString) {
ArrayList <String> list = new ArrayList<String>();
try {
java.net.URL url = new java.net.URL(urlString);
Scanner input = new Scanner(url.openStream());
int current = 0;
while (input.hasNext()) {
String line = input.nextLine();
current = line.indexOf("http:", current);
while (current > 0) {
int endIndex = line.indexOf("\"", current);
if (endIndex > 0) { // Ensure that a correct URL is found
list.add(line.substring(current, endIndex));
current = line.indexOf("http:", endIndex);
} else {
current = -1;
}
}
}
} catch (Exception ex) {
System.out.println("Error: " + ex.getMessage());
}
return list;
}
}
So, I have looked through just about every suggestion on this forum so far and none of them can really help me towards the answer that I need.
Here is the my main code:
I've left out the implements as this works fine.
public class Management {
private static int Price1 = 0;
private static int Price2 = 0;
public static void main(String[] args) {
try
{
Scanner file = new Scanner(new File("friendsfile"));
String s;
while(file.hasNext())
{
s = file.nextLine();
if(s.contains("House 1"))
{
Price1 = getPrice(s);
}
if(s.contains("House 2"))
{
Price2 = getPrice(s);
}
}
Filewriter fw = new Filewriter();
fw.fileWriter(Price1,Price2);
}
catch(FileNotFoundException fnfe)
{
System.out.println("File not found");
}
catch(Exception e)
{
System.out.println("HERE IS AN ERROR MATE!");
}
}
private static int getPrice(String s)
{
StringTokenizer st = new StringTokenizer(s,";");
st.nextToken();
int price1 = Integer.parseInt(st.nextToken().replace(" ",""));
return price1;
}
}
Now the Filewriter looks like this:
public class Filewriter {
public static void fileWriter(int price1, int price2)
{
System.out.println("Ye");
final String FILE_PATH = "housesfile";
final String MARKER_LINE1 = "price1";
final String TEXT_TO_ADD1 = "price1: "+price1;
final String MARKER_LINE2 = "price2";
final String TEXT_TO_ADD2 = "price2: "+price2;
List<String> fileLines = new ArrayList<String>();
Scanner scanner = null;
try {
scanner = new Scanner(new File(FILE_PATH));
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
fileLines.add(line);
if (line.trim().equalsIgnoreCase(MARKER_LINE1)) {
fileLines.add(TEXT_TO_ADD1);
}
if (line.trim().equalsIgnoreCase(MARKER_LINE2)) {
fileLines.add(TEXT_TO_ADD2);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (scanner != null) {
scanner.close();
}
}
PrintWriter pw = null;
try {
pw = new PrintWriter(new File(FILE_PATH));
for (String line : fileLines) {
pw.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (pw != null) {
pw.close();
}
}
}
}
Basically I want:
House 1: price; 520592
House 2: price; 342038
Those price numbers from one file, converted into this file, which is another one.
house #1
owner: -NAME-
price1: 500000
info: 3 bedrooms, 3 bathrooms.
last changed: - DATE -
rented: no
house #2
owner: -NAME-
price2: 150000
info: 3 bedroom, 3 bathroom.
last changed: -date-
rented: no
Now, it doesn't change anything in the file, why is this? Please help.
That is because you use equalsIgnoreCase() in your Filewriter class and compare it with price1, price2. However, your file has values like price1: 500000.
Hence, change equalsIgnoreCase() to contains() and it should work.
Better, change both to lower or upper cases and then match:
line.trim().toLowerCase().contains(MARKER_LINE1.toLowerCase())
Hence, you while loop within Filewrite class would be:
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
fileLines.add(line);
if (line.trim().toLowerCase().contains(MARKER_LINE1.toLowerCase())) {
fileLines.add(TEXT_TO_ADD1);
}
if (line.trim().toLowerCase().contains(MARKER_LINE2.toLowerCase())) {
fileLines.add(TEXT_TO_ADD2);
}
}
EDIT:
Tried and your code works, except it also includes the previously added price1, price2 values which you may want to exclude/overwrite (in the modified if statements above itself):
house #1
owner: -NAME-
price1: 500000
price1: 520592
info: 3 bedrooms, 3 bathrooms.
last changed: - DATE -
rented: no
house #2
owner: -NAME-
price2: 150000
price2: 342038
info: 3 bedroom, 3 bathroom.
last changed: -date-
rented: no
SOLVED IT
I've written a program that loads Strings after an equal sign, and has it count how many times its done this. After counting, I tell it to tell me how large the int is. The value I'm looking for is 3, and it tells me, 3. I then change it to an String, the value stays three. Then, I put it into an 4d array, and It tells me the value is 2. What happened?
The Code:
int times=0;
else if (list.equals("Weapon")) {//If the word weapon is before the =
weapon = value; //take the string after the = and put it into String weapon
troopStats[times][1][weaponTimes][0] = weapon;
weaponTimes++;
System.out.println(weaponTimes+"weapontimes"+times);
}
weaponTimesStr = Integer.toString(weaponTimes);
System.out.println(weaponTimesStr+"string");
troopStats[times][1][0][1] = weaponTimesStr;
System.out.println(troopStats[times][1][0][1]+"InArray");
times++
//loops
The Output:
3weapontimes //Counted the equals sign 3 times, Note that this is from the part of the
omitted code
3string // Changed the integer to a string and got 3
2InArray // Put it into an array, and got 2 back
What Is going on?
(I know that I could just add 1 to the value, but I want to use this code for a unknown number of things later on)
To help, I've posted the entire code:
public class TroopLoader {
static String[][][][] troopStats;
static int times = 0;
static int weaponTimes = 0;
static int armorTimes = 0;
static int animalTimes = 0;
static String weaponTimesStr;
static String armorTimesStr;
static String animalTimesStr;
static String troop;
static String weapon;
static String armor;
static String animal;
static String speed;
static int total = 0;
/*
* [][][]
*
* [total number of troops (total)]
*
* [stats] 0= name 1= weapon 2= armor 3= animal 4= speed
*
* [different things within stat]
*/
public void readTroop() {
File file = new File("resources/objects/troops.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
// repeat until all lines is read
while ((text = reader.readLine()) != null) {
StringTokenizer troops = new StringTokenizer(text, "=");
if (troops.countTokens() == 2) {
String list = troops.nextToken();
if (list.equals("Troop")) {
total++;
}
else {
}
} else {
}
}
troopStats = new String[total][5][10][2];
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
File file2 = new File("resources/objects/troops.txt");
BufferedReader reader2 = null;
try {
reader2 = new BufferedReader(new FileReader(file2));
String text = null;
// repeat until all lines is read
while ((text = reader2.readLine()) != null) {
StringTokenizer troops = new StringTokenizer(text, "=");
if (troops.countTokens() == 2) {
String list = troops.nextToken();
String value = troops.nextToken();
if (list.equals("Troop")) {
troop = value;
troopStats[times][0][0][0] = troop;
}
else if (list.equals("Weapon")) {
weapon = value;
troopStats[times][1][weaponTimes][0] = weapon;
weaponTimes++;
System.out.println(weaponTimes+"weapontimes"+times);
}
else if (list.equals("Armor")) {
armor = value;
troopStats[times][2][armorTimes][0] = armor;
armorTimes++;
}
else if (list.equals("Animal")) {
animal = value;
troopStats[times][3][animalTimes][0] = animal;
animalTimes++;
}
else if (list.equals("Speed")) {
speed = value;
troopStats[times][4][0][0] = speed;
}
else if (list.equals("Done")) {
weaponTimesStr = Integer.toString(weaponTimes);
System.out.println(weaponTimesStr+"string");
armorTimesStr = Integer.toString(armorTimes);
animalTimesStr = Integer.toString(animalTimes);
troopStats[times][1][0][1] = weaponTimesStr;
troopStats[times][1][0][1] = armorTimesStr;
troopStats[times][1][0][1] = animalTimesStr;
System.out.println(troopStats[times][1][0][1]+"InArray"+times);
times++;
troop = "";
weapon = "";
armor = "";
animal = "";
speed = "";
weaponTimes = 0;
armorTimes = 0;
animalTimes = 0;
}
else {
}
} else {
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
if (reader2 != null) {
reader2.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
In the earlier part of the code, I had the program store a value in the location on the array with the weaponTimes variable, not storing the weaponTimes variable. My mistake, sorry for wasting your time.
I wrote a SSCCE with what you posted and it prints what you would expect:
public static void main(String[] args) {
String[][][][] troopStats = new String[4][4][4][4];
int times = 2;
int weaponTimes = 3;
String weaponTimesStr = Integer.toString(weaponTimes);
System.out.println(weaponTimesStr + "string"); //prints 3string
troopStats[times][1][0][1] = weaponTimesStr;
System.out.println(troopStats[times][1][0][1] + "InArray"); //prints 3InArray
}
So the problem is most likely something/somewhere else.
The following:
public class Foo {
public static void main(String[] args) {
String[][][][] troopStats = new String[2][2][2][2];
String weaponTimesStr = Integer.toString(3);
System.out.println(weaponTimesStr+"string");
troopStats[0][1][0][1] = weaponTimesStr;
// You said in a comment that 'times' is equal to 0 in this case so have subbed that in
System.out.println(troopStats[0][1][0][1]+"InArray");
}
}
Gives me the expected output:
3string
3InArray
Sorry I've wasted your time, my mistake was because I stored values in the array using the values of weaponTimes, and not storing weaponTimes in the array.
troopStats[times][1][weaponTimes][0] = weapon;
That was the mistake.