im making a word search program, the grid is 10 x 10 and all the letters are in a Char[][] array.
There is a words list too.
public static void find(){
Scanner input = null;
try {
input = new Scanner(new File(WORD_FILE));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
List<String> words = new ArrayList<>();
while (input.hasNextLine()){
words.add( input.nextLine());
}
input.close();
initgrid();
for (char[] a : grid){
String c =String.valueOf(a);
for (String s : words){
if (s.contains(c)){
// what can i do now?
}
}
}
Does anyone have any suggestions to how i can make the program iterate through each letter of the grid, and look for the words from the word list...it should be able to read words horizontally, vertically and diagonally.
here is my InitGrid() method which opens the grid file and assigns each character to a char[][] array.
public static char[][] initGrid(){
Scanner input = null;
try {
input = new Scanner(new File(GRID_FILE));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String[] tmp = new String[10];
int c = 0;
while (input.hasNextLine()){
tmp[c++]=input.nextLine();
}
input.close();
for (int b = 0; b<tmp.length;b++){
for (int j= 0; j<tmp[b].length();j++){
grid[b][j] = tmp[b].charAt(j);
}
}
return grid;
Related
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.
Working on an assignement where I have to read a .txt file and place it into a 2D array as is. Note ts HAS TO BE A 2D ARRAY.
I then have to print it like it is again.
The .txt input looks like this:
WWWSWWWW\n
WWW_WWWW\n
W___WWWW\n
__WWWWWW\n
W______W\n
WWWWWWEW\n
Here's the code I have currently, I have an error that says that it cannot resolve method 'add'. Probably has to do with the array initializer
public static void main(String[] args) throws FileNotFoundException {
Scanner s = new Scanner(new File("D:/trabalho/maze.txt"));
String[][] list = new list[][];
while (s.hasNextLine()){
list.add(s.nextLine());
}
s.close();
System.out.println(list);
}
Then the print output has to be
WWWSWWWW
WWW_WWWW
W___WWWW
__WWWWWW
W______W
WWWWWWEW
Any help? Thanks!
Assuming the reason for using 2D array is that each character is saved in a separate String object.
In case we know absolutely nothing regarding the text file, I would implement like this:
public static void main(String[] args) throws FileNotFoundException {
File textFile = new File("D:/trabalho/maze.txt");
Scanner rowsCounter = new Scanner(textFile));
int rows=0;
while (rowsCounter.hasNextLine()) {
rowsCounter.nextLine();
rows++;
}
String[][] data = new String[rows][];
Scanner reader = new Scanner(textFile);
for (int i = 0; i < rows; i++) {
String line = reader.nextLine();
data[i] = new String[line.length()];
for (int j = 0; j < line.length(); j++) {
data[i][j] = line.substring(j, j+1);
}
}
reader.close();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < data[i].length; j++) {
System.out.print(data[i][j]);
}
System.out.println();
}
}
This implementation can handle unknown number of lines and unknown length of each line.
If you wanna stick with your Array a possible solution would be
public static void main(String[] args) throws FileNotFoundException {
Scanner s = new Scanner(new File("D:/trabalho/maze.txt"));
String[][] list = new String[10][5];
for(int x = x; s.hasNextLine();x++ ){
for(int i = 0; i < 5 ; i++){
list[x][i] = s.nextLine();
}
}
s.close();
System.out.println(list);
}
So you don't even need a 2D array Here because the String Class acts like an char Array in C++.
Another solution would be to use ArrayLists
public static void main(String[] args) throws FileNotFoundException {
Scanner s = new Scanner(new File("D:/trabalho/maze.txt"));
ArrayList<String> list = new ArrayList<String>;
while (s.hasNextLine()){
list.add(s.nextLine());
}
s.close();
System.out.println(list);
}
So now you have a list that grows with your amount of Data and also you can just use add Method.
the line ArrayList<String> means that your arrayList just can store data from class String
Here you go!
public static void main(String[] str){
Scanner s = null;
try {
s = new Scanner(new File("path\\text.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
List<String> list = new ArrayList<String>();
while (s.hasNextLine()){
list.add(s.nextLine());
}
s.close();
Iterator<String> itr= list.listIterator();
while(itr.hasNext()){
System.out.println(itr.next().toString());
}
}
I'm trying to load a CSV file into a 2d array, but when I go to call it in main I receive the error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
In my code while the file has a next line, it splits up the line, stores it in a string array which will in turn be moved to the 2D array. I don't understand how there can be an error. Anyone willing to explain or am I just very dense?
public int rows = 0;
public int cols = 0;
public String[][] filetable = new String[rows][cols];
public void set_Array(File example)
{
try
{
FileReader file = new FileReader(example);
Scanner sc = new Scanner(file);
if(sc.hasNextLine())
{
String[] tokens = sc.nextLine().split(",");
cols = tokens.length;
rows++;
}
while(sc.hasNextLine())
{
rows++;
sc.nextLine();
}
}
catch (FileNotFoundException e)
{
System.out.println(e);
}
}
public void to_Array(File example)
{
try
{
FileReader file = new FileReader(example);
Scanner sc = new Scanner(file);
int r = 0;
while(sc.hasNextLine())
{
String[] tokens = sc.nextLine().split(",");
for(int c = 0; c < cols; c++)
{filetable[r][c] = tokens[c];}
r++;
}
}
catch (FileNotFoundException e)
{
System.out.println(e);
}
}
I don't know in which order you are calling set_Array and to_Array methods. But I guess, the problem is that you are essentially creating a 2D array of 0 rows and 0 sizes as public String[][] filetable = new String[rows][cols]; is called when rows=0 and cols=0. To rectify, call your set_Array method to assign proper values to rows and cols and then instantiate your 2D array inside your to_Array method.
public void to_Array(File example)
{// Now rows and cols will have proper values assigned
String[][] filetable = new String[rows][cols];
try
{
FileReader file = new FileReader(example);
Scanner sc = new Scanner(file);
int r = 0;
while(sc.hasNextLine())
{
String[] tokens = sc.nextLine().split(",");
for(int c = 0; c < cols; c++)
{filetable[r][c] = tokens[c];}
r++;
}
}
catch (FileNotFoundException e)
{
System.out.println(e);
}
}
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;
}
Does anybody know how to properly read from a file an input that looks like this:
0.12,4.56 2,5 0,0.234
I want to read into 2 arrays in Java like this:
a[0]=0.12
a[1]=2
a[2]=0;
b[0]=4.56
b[1]=5
b[2]=0.234
I tried using scanner and it works for input like 0 4 5 3.45 6.7898 etc but I want it for the input at the top with the commas.
This is the code I tried:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class IFFTI {
public static int size=0;
public static double[] IFFTInputREAL= new double[100];
public static double[] IFFTInputIMAG= new double[100];
static int real=0;
static int k=0;
public static void printarrays(){
for(int k=0;k<size;k++){
System.out.print(IFFTInputREAL[k]);
System.out.print(",");
System.out.print(IFFTInputIMAG[k]);
System.out.print("\n");
}
}
public static void readIFFT(String fileName){
try {
Scanner IFFTI = new Scanner(new File(fileName));
while (IFFTI.hasNextDouble()) {
if(real%2==0){
IFFTInputREAL[k] = IFFTI.nextDouble();
real++;
}
else{
IFFTInputIMAG[k] = IFFTI.nextDouble();
real++;
k++;}
}
try{
size=k;
}catch(NegativeArraySizeException e){}
} catch (FileNotFoundException e) {
System.out.println("Unable to read file");
}
}
}
I think this will do what you want:
String source = "0.12,4.56 2,5 0,0.234";
List<Double> a = new ArrayList<Double>();
List<Double> b = new ArrayList<Double>();
Scanner parser = new Scanner( source ).useDelimiter( Pattern.compile("[ ,]") );
while ( parser.hasNext() ) {
List use = a.size() <= b.size() ? a : b;
use.add( parser.nextDouble() );
}
System.out.println("A: "+ a);
System.out.println("B: "+ b);
That outputs this for me:
A: [0.12, 2.0, 0.0]
B: [4.56, 5.0, 0.234]
You'll obviously want to use a File as a source. You can use a.toArray() if you want to get it into a double[].
You will have to read the complete line.
String line = "0.12,4.56 2,5 0,0.234"; //line variable will recieve the line read
Then.. you split the line on the commas or the spaces
String[] values = line.split(" |,");
This will result in an array like this: [0.12, 4.56, 2, 5, 0, 0.234]
Now, just reorganize the contents between the two order arrays.
Reading from a file in Java is easy:
http://www.exampledepot.com/taxonomy/term/164
Figuring out what to do with the values once you have them in memory is something that you need to figure out.
You can read it one line at a time and turn it into separate values using the java.lang.String split() function. Just give it ",|\\s+" as the delimiter and off you go:
public class SplitTest {
public static void main(String[] args) {
String raw = "0.12,4.56 2,5 0,0.234";
String [] tokens = raw.split(",|\\s+");
for (String token : tokens) {
System.out.println(token);
}
}
}
EDIT Oops, this is not what you want. I don't see the logic in the way of constructing the arrays you want.
Read the content from the file
Split the string on spaces. Create for each element of the splitted array an array.
String input = "0.12,4.56 2,5 0,0.234";
String parts[] = input.split(" ");
double[][] data = new double[parts.length][];
Split each string on commas.
Parse to a double.
for (int i = 0; i < parts.length; ++i)
{
String part = parts[i];
String doubles[] = part.split(",");
data[i] = new double[doubles.length];
for (int j = 0; j < doubles.length; ++j)
{
data[i][j] = Double.parseDouble(doubles[j]);
}
}
File file = new File("numbers.txt");
BufferedReader reader = null;
double[] a = new double[3];
double[] b = new double[3];
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
if ((text = reader.readLine()) != null) {
String [] nos = text.split("[ ,]");
for(int i=0;i<nos.length/2;i++){
a[i]=Double.valueOf(nos[2*i]).doubleValue();
b[i]=Double.valueOf(nos[2*i+1]).doubleValue();
}
}
for(int i=0;i<3;i++){
System.out.println(a[i]);
System.out.println(b[i]);
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
}
}