Failing to retrieve information from text file java - java

I have created a very simple java program (I am only a beginner) that involves data from an array being stored in a text file at the end of the program; this works fine. I am experiencing issues when the program is run again. It should retrieve all the data but doesn't. I have tested it using: System.out.println("test"); The function I am using seems to be starting and the text file has the correct data.
Here is the function:
public static void getArrayData(String [][] array){
try {
Scanner scan2 = new Scanner(new File("arrayData.txt"));
System.out.println(array.length);
for(int i=0; i<array.length; i++)
{
for(int j=0; j<array[i].length; j++)
{
System.out.println("Test 1");
System.out.println(array[i][j]);
if ( ! scan2.hasNext() ) //if there's nothing left to read
return;
array[i][j]=scan2.next();
}
}
}
catch (FileNotFoundException e)
{
System.out.println("Test 2");
e.printStackTrace();
}
}
All the function seems to be returning is test null test null test null. Obviously this is not what I want.
I am new to programming so I apologise for the most probably simple issue or stupid mistake. Any help or tips are welcome. If you need any more information please don't hesitate to ask.
Many thanks in advance
Here is the full code:
import java.util.*;
import java.io.*;
public class simpleAI2
{
public static void main (String [] args)
{
int count = 0;
String[][] array = new String [20][4];
simpleAI2.getArrayData(array);
String leaveQ;
int rep = 1;
do
{
int countTwo = 0;
boolean flag = false;
Scanner scanName = new Scanner (System.in);
Scanner scanSport = new Scanner (System.in);
Scanner leave = new Scanner (System.in);
System.out.println("My name is A.I.S.C.M.B.T. What is your name?");
array[count][1] = scanName.nextLine ();
System.out.println("Hi "+array[count][1]+"! What's your favourite sport?");
array[count][2] = scanSport.nextLine ();
String sport = array[count][2];
for(int x = 1;x<rep;x++)
{
if(!array[countTwo][2].equals(null) && array[countTwo][2].equals(array[count][2]))
{
flag = true;
x = 28;
}
else
{
flag = false;
}
countTwo ++;
}
countTwo --;
if(flag == true)
{
System.out.println("I know "+array[countTwo][2]+". It is "+array[countTwo][3]+". My friend "+array[countTwo][1]+" knows it");
}
if(flag == false)
{
System.out.println("I don't know "+array[count][2]+". I only know robot boxing. Robots hit each other until one malfunctions. What is this alien sport you speak of?");
array[count][3] = scanSport.nextLine ();
}
System.out.println("Go again? Type no to leave me :(");
leaveQ = leave.nextLine ();
rep ++;
count ++;
if(leaveQ.equals("no"));
{
simpleAI2.Save(array);
}
}while (!leaveQ.equals("no"));
}
public static void Save(String [][] array){
try {
PrintWriter writer = new PrintWriter(new File("arrayData.txt"));
for(int x=0; x<array.length; x++){
for(int y=0; y<array[x].length; y++){
writer.write(String.valueOf(array[x][y]));
}
writer.println();
}
writer.flush();
writer.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
public static void getArrayData(String [][] array){
try {
Scanner scan2 = new Scanner(new File("arrayData.txt"));
System.out.println(array.length);
for(int i=0; i<array.length; i++)
{
for(int j=0; j<array[i].length; j++)
{
System.out.println("Test 1");
System.out.println(array[i][j]);
if ( ! scan2.hasNext() ) //if there's nothing left to read
return;
array[i][j]=scan2.next();
}
}
}
catch (FileNotFoundException e)
{
System.out.println("Test 2");
e.printStackTrace();
}
}
}

Related

How do i change my array from being on 1 line to being a 20x20 square? (Java)

I need to change how my array is formatted to where it shows as a 20x20 square. Any ideas on best way to do this?
public class MyGrid {
public static void main(String[] args) throws IOException
{
FileReader file = new FileReader("list.txt");
int[] integers = new int [400];
int i=0;
try {
Scanner input = new Scanner(file);
while(input.hasNext())
{
integers[i] = input.nextInt();
i++;
}
input.close();
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println(Arrays.toString(integers));
}
}
The try-with-resources statement is nice; I suggest taking advantage of it to clean-up safely. I don't see any need for a FileReader with your Scanner (File is good enough). Then every 20 values you print a newline - otherwise print a space; then print the value. Like,
int[] integers = new int[400];
try (Scanner input = new Scanner(new File("list.txt"))) {
int i = 0;
while (input.hasNextInt()) {
integers[i] = input.nextInt();
if (i != 0) {
if (i % 20 == 0) {
System.out.println();
} else {
System.out.print(" ");
}
}
System.out.printf("%03d", integers[i]);
i++;
}
} catch (Exception e) {
e.printStackTrace();
}
The simplest and fastest way to do this (for me) would be that:
public class MyGrid {
public static void main(String[] args) throws IOException {
FileReader file = new FileReader("list.txt");
int[] integers = new int[400];
int[][] table = new int[20][20];
int m, n, i = 0;
int tableWidth = table[0].length; // 20 in that case
try {
Scanner input = new Scanner(file);
while(input.hasNext()) {
int value = input.nextInt();
integers[i] = value;
m = i / tableWidth; // Row index
n = i % tableWidth; // Column index
table[m][n] = value;
i++;
}
input.close();
} catch(Exception e) {
e.printStackTrace();
}
System.out.println(Arrays.toString(integers));
}
}
Moreover, this code will adapt to any other table size (e.g. 500, 600 or 4237 elements).
CAUTION: this code will store data in a 2D array but it will not display it in the console. If you want to display data while reading file, I suggest you to look at #Elliott Frisch answer which is more adapted.

Error: ; expected (Compile error in Java)

When isLetter() method is deleted everything is working fine but when I add it it gives an error. I removed private as it is in the main method. Please help. Thanks in advance.
import java.io.*;
class WordCounter{
public static void main(String args[]){
File file_in_obj = new File("E:/Problems","notes.txt");
File file_out_obj = new File("E:/Problems","notes_sorted.txt");
boolean isLetter(char let){
return ( let>= 'a'&& let <= 'z') || ( let >= 'A' && let <='Z');
}
try(BufferedReader fin = new BufferedReader(new FileReader(file_in_obj));
BufferedWriter fout = new BufferedWriter(new FileWriter(file_out_obj));){
String array[]=new String[500];
char ch[]=new char[25];
int rd,k=0;
String line=null;
/*do{
rd=fin.read();
if(Character.isWhitespace((char)rd))
fout.write(" ");
else if(Character.isLetter((char)rd)){
fout.write((char)rd);
}
}while(rd!=-1); */
while((line=fin.readLine())!=null){
// System.out.println(j++);
String[] tokens = line.split ("\\s+");
for(int i = 0; i < tokens.length; i++){
array[k]=tokens[i];
fout.write(array[k]+" ");
k++;
//System.out.println(tokens.length);
}
}
for(int p=0;p<k;p++){
for(int i=0;i<array[p].length();i++){
if(Character.isLetter(array[p].charAt(i)))
System.out.print(array[p].charAt(i));
}
System.out.println(p);
}
/*for(int j=tokens.length;j>1;j--)
for(int i=0;i<j-1;i++){
if(tokens[i].compareTo(tokens[i+1])>0){
String temp=tokens[i+1];
tokens[i+1]=tokens[i];
tokens[i]=temp;
}
}*/
} catch(IOException e){
System.out.println("I/O Exception occured");
}
}
}
You can't have a method inside another method. Try this:
boolean isLetter(char let){
return ( let>= 'a'&& let <= 'z') || ( let >= 'A' && let <='Z');
}
public static void main(String args[]){
File file_in_obj = new File("E:/Problems","notes.txt");
File file_out_obj = new File("E:/Problems","notes_sorted.txt");
...
}

Why does this program terminate when I enter user input?

The program is supposed to compare a user-inputted string to a text document. If the program finds a match in the file and in part of the string, it should highlight or change the font color of the matching string in what the user inputted. The thing is, once I enter something for user input, the program terminates. Examples of inputs that could have a match in the file are MALEKRQ, MALE, MMALEKR, MMMM, and MALEK. How do I fix this problem? I'm using Eclipse Neon on Mac OS X El Capitan.
import java.util.*;
import java.io.*;
public class ScienceFair
{
public static void main(String[] args) throws FileNotFoundException
{
java.io.File file = new java.io.File("/Users/Kids/Desktop/ScienceFair/src/MALEKRQsample.txt");
try
{
Scanner fileInput = new Scanner(file);
Scanner userInput = new Scanner(System.in);
System.out.println("Enter Protein Sequence");
String userProteinSequence = userInput.nextLine().toUpperCase();
int len = userProteinSequence.length();
int size = 4;
int start = 0;
int indexEnd = size;
while (indexEnd < len - size)
{
for (int index = start; index <= len - size; index++)
{
String search = userProteinSequence.substring(index, indexEnd);
System.out.println(search);
while (fileInput.hasNext())
{
String MALEKRQ = fileInput.nextLine();
// System.out.println(MALEKRQ);
int found = MALEKRQ.indexOf(search);
if (found >= 0)
{
System.out.println("Yay.");
}
else
{
System.out.println("Fail.");
}
}
indexEnd++;
}
size++;
if (size > 8) {
size = 8;
start++;
}
}
}
catch (FileNotFoundException e)
{
System.err.format("File does not exist.\n");
}
}
}
import java.util.*;
import java.io.*;
public class ScienceFair
{
public static void main(String[] args) throws FileNotFoundException
{
java.io.File file = new java.io.File("/Users/Kids/Desktop/ScienceFair/src/MALEKRQsample.txt");
try
{
Scanner userInput = new Scanner(System.in);
System.out.println("Enter Protein Sequence");
String userProteinSequence = userInput.nextLine().toUpperCase();
for (int size = userProteinSequence.length(); size >= 4; size--) {
for (int start = 0; start <= userProteinSequence.length()-size; start++) {
boolean found = false;
String search = userProteinSequence.substring(start, size);
System.out.println(search);
Scanner fileInput = new Scanner(file);
while (fileInput.hasNext()) {
String MALEKRQ = fileInput.nextLine();
int found = MALEKRQ.indexOf(search);
if (found >= 0) {
found = true;
}
}
if (found) {
System.out.println(search+" found (index "+start+")");
fileInput = new Scanner(file);
while (fileInput.hasNext()) {
String MALEKRQ = fileInput.nextLine();
MALEKRQ = MALEKRQ.replaceAll(search, "[["+search+"]]");
System.out.println(MALEKRQ);
}
return;
}
}
}
System.out.println(search+" not found");
Scanner fileInput = new Scanner(file);
while (fileInput.hasNext()) {
String MALEKRQ = fileInput.nextLine();
System.out.println(MALEKRQ);
}
} catch (FileNotFoundException e) {
System.err.format("File does not exist.\n");
}
}
}

Array Index out of bounds for Java using terminal

I am having trouble with a ticketing system that I am trying to create using java. I am trying to utilize two files to read and write my inputs. I am testing with just salesSell method at the moment. I am passing the args using terminal. The problem that I am having is an arrayoutofbounds exception that gets thrown.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at cisc_327_frontend.Frontend_try1.main(Frontend_try1.java:763)
the two array parameters that I am passing are parsed from the same line in my current events file. an example of a line in the file is : "testevent1__________0003". I cannot seem to figure out where I am having this problem. Any type of guidance would be much appreciated.
package cisc_327_frontend;
import java.io.*;
import java.util.*;
public class Frontend_try1 {
private static File fileOutput;
private static List<StringBuilder> eventTrans = new ArrayList<>();
public static void consoleInput(String[] namesArray, int[] ticketArray,File fileCurrentEvents){
System.out.println("Enter command:");
Scanner input = new Scanner(System.in);
String inputString = input.nextLine();
boolean correct = true;
do{
if(inputString.toUpperCase().equals( "LOGIN")) {
//enter login mode
login(namesArray, ticketArray,fileCurrentEvents);
correct = true;
}
if(inputString.toUpperCase().equals("LOGOUT")){
logout(namesArray, ticketArray,fileCurrentEvents);
correct=true;
}
if (!"LOGIN".toUpperCase().equals(inputString) || !"LOGOUT".toUpperCase().equals(inputString)){
System.out.println("Incorrect command, please enter command:");
input = new Scanner(System.in);
inputString = input.nextLine();
correct = false;
}
}while(!correct);
}
public static void login(String[] namesArray, int[] ticketArray,File fileCurrentEvents) {
System.out.println("Sales or Admin?");
Scanner input = new Scanner(System.in);
String inputString = input.nextLine();
boolean correct = true ;
do {
if(inputString.toUpperCase().equals("LOGOUT")){
logout(null, null, null);
}
else if(inputString.toUpperCase().equals("SALES")) {
//enter sales mode
sales(namesArray, ticketArray,fileCurrentEvents);
correct = true;
} else if (inputString.toUpperCase().equals("ADMIN")) {
//enter admin mode
admin(namesArray, ticketArray,fileCurrentEvents);
correct = true;
} else if (inputString.toUpperCase().equals("LOGOUT")) {
//enter logout mode
logout( namesArray, ticketArray, fileCurrentEvents);
correct = true;
} else {
//ask again
System.out.println("Invalid Input");
System.out.println("Sales or Admin?");
input = new Scanner(System.in);
inputString = input.nextLine();
correct = false;
}
}while(!correct);
}
public static void sales(String[] namesArray, int[] ticketArray,File fileCurrentEvents) {
//System.out.println("SALES");
System.out.println("Sales Mode");
System.out.println("Enter Command:");
Scanner input = new Scanner(System.in);
String inputString = input.nextLine();
boolean correct = true ;
do {
if(inputString.toUpperCase().equals("LOGOUT")){
logout( namesArray, ticketArray, fileCurrentEvents);
}
else if(inputString.toUpperCase().equals("SELL")) {
//enter sales Sell mode
salesSell(namesArray, ticketArray,fileCurrentEvents);
correct = true;
} else if (inputString.toUpperCase().equals("RETURN")) {
//enter sales Return mode
salesReturn(namesArray, ticketArray,fileCurrentEvents);
correct = true;
} else if (inputString.toUpperCase().equals("LOGOUT")) {
//enter Logout mode
logout( namesArray, ticketArray, fileCurrentEvents);
correct = true;
} else {
//ask again
System.out.println("Invalid Input");
System.out.println("Enter Command:");
input = new Scanner(System.in);
inputString = input.nextLine();
correct = false;
}
}while(!correct);
}
public static void salesSell(String[] namesArray, int[] ticketArray,File fileCurrentEvents) {
int index = 0;
String eventName = null;
int numberTickets = 0;
System.out.println("Sales Sell Mode");
System.out.println("What is the name of your event?");
Scanner input = new Scanner(System.in);
String inputString = input.nextLine();
if(inputString.toUpperCase().equals("LOGOUT")){
logout( namesArray, ticketArray, fileCurrentEvents);
}
try{
for(int i = 0; i < namesArray.length; i++) {
if(namesArray[i].equals(inputString)){
index = i;
}
}
eventName= namesArray[index];
numberTickets=ticketArray[index] ;
} catch (Exception e) {
System.out.println("Error: Event not found within file");
System.exit(1);
}
int event = inputString.length();
boolean charnumber = true;
do{
if(inputString.toUpperCase().equals("LOGOUT")){
logout( namesArray, ticketArray, fileCurrentEvents);
}
if(event< 0 || event >20){
System.out.println("No more than 20 characters allowed for name!");
System.out.println("Enter name:");
input = new Scanner(System.in);
inputString = input.nextLine();
event=inputString.length();
charnumber = false;
}
else{
charnumber = true;
}
} while(!charnumber);
System.out.println("How many tickets?");
input = new Scanner(System.in);
inputString = input.nextLine();
int digit;
while(true){
try {
digit = Integer.parseInt(inputString);
break;
}
catch(NumberFormatException e){
}
System.out.println("Please type a number!");
inputString = input.nextLine();
}
if( numberTickets - digit <0){
System.out.println("Illegal amount of tickets! Buy less ticket please.");
}
else{
int tickets = numberTickets - digit;
ticketArray[index]=tickets;
}
boolean dignumber = true;
do{
if(inputString.toUpperCase().equals("LOGOUT")){
logout( namesArray, ticketArray, fileCurrentEvents);
}
if(digit<0 || digit>8){
System.out.println("Only 8 tickets allowed to be sold!");
inputString = input.nextLine();
event=inputString.length();
dignumber = false;
digit= Integer.parseInt(inputString);
}
else{
dignumber= true;
}
}while(!dignumber);
}
public static boolean logout(String[] namesArray, int[] ticketArray,File fileCurrentEvents) {
FileWriter logoutFileWriter;
FileWriter currEventsFileWriter;
int numSpaces = 0;
try{
currEventsFileWriter = new FileWriter(fileCurrentEvents, true);
for(int i = 0; i < namesArray.length; i++ ) {
currEventsFileWriter.write(namesArray[i]);
numSpaces = 20 - (namesArray[i].length() + 4);
for(int j = 0; j < numSpaces; j++) {
currEventsFileWriter.write("_");
}
currEventsFileWriter.write(ticketArray[i]);
currEventsFileWriter.write(String.format("%n"));
}
} catch(IOException e) {
System.out.println("Rewriting Current Events File Error");
System.exit(1);
}
try {
logoutFileWriter = new FileWriter(fileOutput, true);
//Cycle through event trans file and write via filewriter
for(int i = 0; i < eventTrans.size(); i++ ) {
String transact = eventTrans.get(i).toString();
logoutFileWriter.write(transact);
logoutFileWriter.write(String.format("%n"));
}
// Signify end of file
logoutFileWriter.write("00 000000 00000");
logoutFileWriter.write(String.format("%n"));
logoutFileWriter.close();
fileOutput.createNewFile();
} catch(IOException e) {
System.out.println("Output File Error");
System.exit(1);
}
return true;
/*
for( int i = 0; i < 20; i++ ) {
System.out.println("");
}
System.out.println("Logged Out");
consoleInput();
*/
}
public static void main(String[] args){
try {
File fileCurrentEvents = new File(args[0]);
fileOutput = new File(args[1]);
// Read current events file for events & dates
FileReader fileRead = new FileReader(fileCurrentEvents);
BufferedReader buffRead = new BufferedReader(fileRead);
// Create strings for data in current events file
String currentLine;
String eventName;
Integer numberTickets;
List<Integer> numticket = new ArrayList<Integer>();
List<String> list = new ArrayList<String>();
int[] numarray= new int[numticket.size()];
String[] linesArray = list.toArray(new String[list.size()]);
// Cycle through current events file line by line
while((currentLine = buffRead.readLine()) != null) {
if (currentLine.equals("END_________________00000")){
break; // End of file
}
//Parse for event name & number of tickets
eventName = currentLine.substring(0, currentLine.lastIndexOf("_")).trim();
numberTickets = Integer.parseInt(currentLine.substring(currentLine.lastIndexOf
("_") + 1));
// Place event name and # tickets into data structure
// Add event name to event array list with same index as # tickets
// Parse int to get # tickets & add to arraylist for tickets with same index
while((eventName = buffRead.readLine()) != null){
list.add(eventName);
}
for (int i =0 ; i< list.size();i++){
linesArray[i]= list.get(i);
}
while((eventName = buffRead.readLine()) != null){
numticket.add(numberTickets);
}
for (int i =0 ; i< numticket.size();i++){
numarray[i]= numticket.get(i);
}
}
while(true) {
consoleInput(linesArray, numarray, fileCurrentEvents);
}
} catch (IOException e) {
System.out.println("File I/O Error"); //Print to console to signify error
e.printStackTrace();
System.exit(1);
}
}
}
If you are getting an ArrayOutOfBoundsIndexException at this line
File fileCurrentEvents = new File(args[0]);
Then it probably means the array (args) index (0) you are using is out of bounds in that it is higher than the size of the array.
If you have an array that looks like
[] //Zero entries
You can't get element 0 (the first item), because there are none.
So you must be passing in zero parameters when you run the code. Either when you run it at the command line, add the filename after it or change the build settings in your IDE (Eclipse, IntelliJ, Sublime) to add it to the build steps.
the error is being thrown on this line in the main method. File fileCurrentEvents = new File(args[0]);
Then your args is empty (e.g. you haven't run your program with any command line arguments, like a file). You could add a default, something like
File fileCurrentEvents = new File(args.length > 0 ? args[0] : "default.txt");
In your original code, line 763 is actually:
for (int i = 0 ; i< list.size(); i++){
linesArray[i] = list.get(i); //<--------------THIS ONE!
}
which can cause an ArrayIndexOutOfBoundsException when linesArray is shorter that list. This is happening because you instantiated linesArray earlier via
String[] linesArray = list.toArray(new String[list.size()]);
when list was empty, then added to list making it longer than your array.
Since the outer while-loop doesn't appear to use the linesArray in any other capacity, you can probably remove the above for-loop and, and place
linesArray = list.toArray(new String[list.size()]);
after the first while loop to create the appropriate array with all the elements.

I am working on a program that checks the spelling of a txt file using a given dictionary in java. I am not getting the right outputs

I am having issues with this program. I cannot get it to read more than the first line of code in the dictionary file. The dictionary file has around 22000 words. If someone could figure this out that would be great. I then could move along with the rest of my code.
public class Program2 {
private String[] array;
private String[] array2;
public void readFile(){
File f = new File ("dictionary.txt");
try {
Scanner input = new Scanner (f);
int i = 0;
array = new String [10];
while (i<array.length && input.hasNext()){
String word = input.nextLine();
String[] wordarray = word.split(" ");
array[i] = wordarray[i];
i++;
for (i = 0 ; i<array.length; i++)
System.out.println(array[i]);
}
input.close();
}//try
catch (IOException e) {
e.printStackTrace();
}
}
public void readFile2(){
File f = new File ("oliver.txt");
try {
Scanner input = new Scanner (f);
int i = 0;
array = new String [10];
while (i<array.length && input.hasNext()){
String book = input.nextLine();
String[] bookarray = book.split(" ");
array2[i] = bookarray[i];
i++;
for (i = 0 ; i<array2.length; i++)
System.out.println(array2[i]);
}
input.close();
}//try
catch (IOException e) {
e.printStackTrace();
}
}
public int binarysearchrecursive(double key, int first, int last) {
int mid;
if (first > last) {
return -1;
}
mid = (first + last) / 2;
if (key == wordArray[mid]) {
return mid;
} else if (key < wordArray[mid]) {
return binarysearchrecursive(key, first, mid - 1);
} else {
return binarysearchrecursive(key, mid + 1, last);
}
}
}
Ok, as someone commented, I think the problem is in the loops :P
This is what we want to do when we read all the words:
Create an ArrayList (better than Array, because you don't know exactly how many words you have in the text file).
Then create a double loop (1 while + 1 for) which goes through the file and stores strings in that ArrayList
The loops will go through all the lines, and then add every word in the line to the ArrayList (using the split on " " like you are trying).
So:
public ArrayList<String> readFile(){
File f = new File ("dictionary.txt");
ArrayList<String> array = new ArrayList<String>();
try {
Scanner input = new Scanner (f);
while (input.hasNext()){
//Goes through all lines
String line = input.nextLine();
//Array of all words:
String[] wordArray = line.split(" ");
//Goes through all words:
for(String str : wordArray){
array.add(str);
}
}
input.close();
}//try
catch (IOException e) {
e.printStackTrace();
}
return array;
}

Categories

Resources