reading .txt file and making an array(java) - java

Im trying to read in a .txt file and make a multi dimensional array out of it. I dont understand why the i and j loops arent populating my array. Any pointers much appreciated....
import java.util.*;
import java.io.*;
public class arrayChallenge {
public static void main(String[] args) throws FileNotFoundException{
File input = new File("input.txt");
Scanner scan1 = new Scanner(input);
int width=10, height=10;
char [][] arrayMulti = new char[width][height];
for(int i=0; i<height; i++){
String x = scan1.next();
char[] chars = x.toCharArray();
for(int j=0; j<width; j++){
arrayMulti[i][j]= chars[j];
}
}
for(char [] xy: arrayMulti){
System.out.println(Arrays.toString(xy));
}
}
}

There is nothing wrong with your i and j loops as far as I can see. As long as the provided path to your file is correct and the file has the needed number of lines (>= your width variable) and each line has the needed number of characters (>= your height variable), it should work fine.

Related

How to create a 2d array from values provided in specific lines of a text file

I'm working a project that requires me to create 2d arrays from an image data file and then sort said arrays into different formats based on values.
The sorting will come easy enough, but I'm running into an issue determining the size of an array from scanning the file.
The data of the file is formatted like so:
5 5
201 159 87 63 240
231 32 222 76 5
10 5 248 139 47
167 76 138 177 107
188 122 154 165 205
I need to use the first line to set the rows and columns of the array, but I can't figure out how to do so without scanning the rest of the data. Another thing, I need to be able to loop my code so that a file with multiple data sets in the displayed format can be read an placed into arrays.
Here's what I've come up with so far:
public static void main(String[] args) throws IOException {
File file = new File("imagedata.txt");
Scanner sc = new Scanner(file);
int i = 0;
int j = 0;
int[][] array = new int[i][j];
while (sc.hasNextInt()) {
i = sc.nextInt();
j = sc.nextInt();
array = array[i][j];
sc.nextline();
}
}
It's not much, but I've scrapped a lot of other drafts that got me nowhere. Any helpful advice is welcome.
Okay. So the problem here results from a certain index of the 2D array being replaced over and over again by a new value. What I mean by that is: you have a while loop. You have set variables j and i to 0. But every iteration of the while loop, you are changing the same position in the 2D array; therefore, nothing gets changed. To fix this, we can make use of the first 2 numbers which detail the dimensions of the 2D array (in this case 5x5). We can then use those dimensions in a nested for-loop, and loop through the file and store each value into the 2D array.
The code could look something like this:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(new File("imagedata.txt"));
int r = scanner.nextInt();
int c = scanner.nextInt();
int [][] array = new int[r][c];
for(int row=0; row<array.length; row++) {
for(int col=0; col<array[row].length; col++) {
array[row][col] = scanner.nextInt();
}
}
for(int[] row : array) {
for(int num : row) {
System.out.print(num+" ");
}
System.out.println();
}
}
}
Alternatively, if you don't mind using a 2d String array:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(new File("imagedata.txt"));
int r = scanner.nextInt();
int c = scanner.nextInt();
scanner.nextLine();
String [][] array = new String[r][c];
for(int row=0; row<array.length; row++) {
array[row] = scanner.nextLine().split(" ");
}
for(String[] row : array) {
for(String str : row) {
System.out.print(str+" ");
}
System.out.println();
}
}
}

How to load text file into string array with only import java.io.* and no other library

Basically i added "import java.util.Scanner". but I wanted my code to work without that library and only "import java.io*" . However i want all my words (english word in the dictionary with the total of 109562 words in this case) in my text file to be inside the string array. Hence, in this case, without the scanner. how to do that?
import java.io.*;
import java.util.Scanner;
public class tester{
public static void main (String [] args) throws IOException{
File f = new File("C:/Users/alienware14/Documents/words.txt");
String [] words = new String [109562];
readWords(f , words);
/*
System.out.println("----ALL WORDS IN WORDS.TXT----");
for(int i=0; i<words.length; i++){
System.out.println("");
System.out.print(words[i]);
} */
}
public static String [] readWords(File f , String [] words) throws FileNotFoundException {
Scanner s;
s = new Scanner(f);
for(int i = 0; i < words.length; i++){
while (words[i] == null) {
words[i] = s.next();
}
}
s.close();
return words;
}
}
You could use a java.io.FileReader instead of a Scanner. Just google 'Java read file' to find an example for it (Using a Scanner for reading files is quite exotic). Though I don't really understand why you have a problem with importing a Scanner. Sounds like homework..
Try split method
String[] words = yourtext.split(" "); //user space in split method for words

Arrays with printwriter and displaying them

What im trying to do is make this txt file into an array, then with the numbers that are incorrect(not numbers) put them into the pw wrong.txt and display them
import java.util.*;
import java.io.*;
public class MorenoJonathonTranslator
{
public static void main(String[] args) throws IOException
{
Scanner file = new Scanner(new File("numbers.txt"));
ArrayList<String> alphabeticPhoneNumbers = new ArrayList<String>();
int i = 0;
System.out.println("Original: ");
System.out.println("Numberical: ");
while(file.hasNextLine() ){
alphabeticPhoneNumbers.add(file.next());
alphabeticPhoneNumbers.add(file.next());
file.nextLine();
System.out.println(alphabeticPhoneNumbers.get(i));
i+=2;
}
PrintWriter pw = new PrintWriter("wrong.txt");
for( i = 0; i < 8; i++){
pw.print(alphabeticPhoneNumbers.get(i));
pw.print(alphabeticPhoneNumbers.get(i+1));
pw.println();
i++;
}
pw.close();
}
}
What is it that you're trying to achieve? I'd think that your program is broken and doesn't print anything because you're somehow incrementing i to a value that's already greater than 7 so your second loop doesn't do anything. Just a guess though as I don't know how your data looks like. Try not reusing index variables like i.
I'm not exactly sure what you are trying to achieve. If you only want to display them while the program's execution, you could use a System.out.println within the last for loop.

Bubble Sort numbers from file in java

I am trying to bubble sort numbers from a text file, I understand how to bubble sort and how to use a text file. But have never used both of them at the same time. I tried bubble sorting an array and just trying to figure out how to replace that array with a text file. If someone can explain to me how to get the bubble sort to read a text file it would be greatly appreciated. I am new to java and it is sometimes confusing to combine 2 different things I have learned into 1 program.
Here is my bubble sort that solves the array:
public static void main(String[] args)
{
int number[]={7,13,4,5,62,3,1,3,45};
int temp;
boolean fixed=false;
while(fixed==false){
fixed = true;
for (int i=0; i <number.length-1;i++){
if (number[i]>number[i+1]){
temp = number [i+1];
number[i+1]=number[i];
number[i]=temp;
fixed=false;
}
}
}
for (int i=0; i<number.length;i++){
System.out.println(number[i]);
}
}
}
Use Scanner class !
File file=new File("file.txt");
Scanner sc=new Scanner(file);
int arr[]=new int[100];
int i=0;
while(sc.hasNextLine()){
arr[i]=sc.nextInt();
i++;
}
Don't just hard code the array..!
Suppose the content of your file is a list of number separated by some delimiter say single space " "
Use:
File file=new File("file.txt");
Scanner sc=new Scanner(file);
String arr[] = sc.nextLine().split(" ");
That is it.
Once you have got the array u can play around with it..!
Reading a file has nothing to do with bubble sort. You can read the file to create an array of integers and then use the usual bubble sort algorithm to sort it
You can do like this:
package test;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class Test {
public static void bubbleSort(int[] num ) {
int j;
boolean flag = true; // set flag to true to begin first pass
int temp; //holding variable
while ( flag ) {
flag= false; //set flag to false awaiting a possible swap
for( j=0; j < num.length -1; j++ ) {
if ( num[ j ] < num[j+1] ) {
temp = num[ j ]; //swap elements
num[ j ] = num[ j+1 ];
num[ j+1 ] = temp;
flag = true; //shows a swap occurred
}
}
}
}
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("numbers.txt"));
int [] numbers = new int [256];
int i = 0;
while(scanner.hasNextInt()){
numbers[i++] = scanner.nextInt();
}
bubbleSort(numbers);
System.out.println(Arrays.toString(numbers));
}
}

Parsing a text file into strings (JAVA)

I am trying to write a coded that reads in a text file into an array list. However, I am unsure how to parse my text file into strings to correctly be put into an array list. Here is a sample text file that I need to use.
This should be the sample question.
2
one
two
three
four
0
4
6
My Java code below:
package javaapplication8;
import java.util.*;
import java.io.*;
public class JavaApplication8 {
public static void main(String[] args) throws IOException{
Scanner inScan = new Scanner(System.in);
String file_name;
System.out.print("What is the full file path name?\n>>");
file_name = inScan.next();
Scanner fScan = new Scanner(new File(file_name));
int numItems = Integer.parseInt(fScan.nextLine());
ArrayList<String> Questions = new ArrayList<String>();
for(int i=0; i < numItems; i++)
{
Questions.add(fScan.nextLine());
}
System.out.print("The array is: " + Questions);
}
From your comment about the variable numLines below, you don't need to parse integers from the content so you can remove the line:
int numItems = Integer.parseInt(fScan.nextLine());
Then to output every line to the array, you can use Scanner.hasNextLine():
while (fScan.hasNextLine()) {
questions.add(fScan.nextLine());
}

Categories