I want to read and print the numbers from the Textfile (WLTP.txt) in the assets folder as an array, but the output of my code is everytime null. I wonder why it is skipping the try part and jumping to the catch part.
public class WLTPc {
public static void main(String[] args) {
int [] data = readFiles("WLTP.txt");
System.out.println(Arrays.toString(data));
}
public static int [] readFiles(String file) {
try {
File f = new File(file);
Scanner s = new Scanner (f);
int ctr = 0;
while (s.hasNextInt()) {
ctr ++;
s.nextInt();
}
int[] arr = new int[ctr];
Scanner s1= new Scanner(f);
for (int i=0; i< arr.length; i++){
arr[i] = s1.nextInt();
}
System.out.println(Arrays.toString(arr));
return arr;
}
catch (Exception e){
return null;
}
}
}
You are passing file name directly and accessing it in File() object.
As you are accessing file from asset you need to use getAssets().open(file))
It will return InputStream. Pass that InputStream to Scanner() and read you file as you want.
import android.content.Context;
import java.io.IOException;
import java.util.Scanner;
public class WLTPc {
private Context context;
public WLTPc(Context context) {
this.context = context;
}
public int[] readAssetFiles(String file) {
try {
Scanner s = new Scanner(context.getAssets().open(file));
int ctr = 0;
while (s.hasNextInt()) {
ctr++;
s.nextInt();
}
s.close();
int[] arr = new int[ctr];
Scanner s1 = new Scanner(context.getAssets().open(file));
for (int i = 0; i < arr.length; i++) {
arr[i] = s1.nextInt();
}
s1.close();
return arr;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Related
This is for an online judge (Codeforces). Input file is like this
input.txt
6
4 3 2 1 5 6
First line is the array size and second line contains the array elements.
I've tried it by using this
public static int readFiles(String file){
try{
File f = new File(file);
Scanner Sc = new Scanner(f);
int n = Sc.nextInt();
return n;
}
catch(Exception e){
return 0;
}
}
public static int[] readFiles(String file,int n){
try{
File f = new File(file);
Scanner Sc = new Scanner(f);
Sc.nextInt();
int arr [] = new int [n];
for(int count = 0;count < n; count++){
arr[count] = Sc.nextInt();
}
return arr;
}
catch(Exception e){
return null;
}
}
public static void main (String args [] ){
int n = readFiles("input.txt");
int arr [] = readFiles("input.txt",n);
You could call the method that builds the array without provide n:
public static void main (String args [] ){
int arr [] = readFiles("input.txt");
System.out.println(Arrays.toString(arr));
int n = arr.length;
System.out.println("n is: " + n);
}
public static int[] readFiles(String file){
try{
File f = new File(file);
Scanner Sc = new Scanner(f);
int n= Sc.nextInt();
int arr [] = new int [n];
for(int count = 0;count < n; count++){
arr[count] = Sc.nextInt();
}
return arr;
}
catch(Exception e){
System.out.println("The exception is: " + e);
e.printStackTrace();
return null;
}
}
if you need n, you can get it by this line arr.length.
your code will never work because is not even compiling
if this method readFiles(String file) return an int then it makes no sense doing this
int arr [] = readFiles("input.txt",n);
hint:
read the file line by line,
check if spaces are there
get the numbers as string
parse those into integers
put them in the array
return at the end that array.
You could add a bufferedreader to read the lines one at a time, like this.
public static void main(String[] args) {
int[] numberArray = readFile();
}
public static int[] readFile(){
try(BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
int arraySize = Integer.parseInt(br.readLine());
String[] arrayContent = br.readLine().split(" ");
int[] newArray = new int[arraySize];
for(int i = 0; i<arraySize; i++){
newArray[i] = Integer.parseInt(arrayContent[i]);
}
return newArray;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Why don't you try this on your for loop to split the numbers between empty spaces and store it in an array :
int temp[] = Scanner.readLine().split(" ");
I am trying to write a program that merges two arrays from numbers that are in two different text files into a third array.
I have the method done to merge the two arrays into the third array.
But I don't know how to get the numbers from the second file.
Here is my current code :
public static void main(String[] args) {
int[] mergedArray = {};
Scanner input = new Scanner(System.in);
System.out.println("Enter the name of your first file (including file extension): ");
String filename = input.next();
int[] firstArray;
try (Scanner in = new Scanner(new File(filename)))
{
int count = in.nextInt();
firstArray = new int[count];
firstArray[0] = count;
for (int i = 0; in.hasNextInt() && count != -1 && i < count; i++) {
firstArray[i] = in.nextInt();
}
} catch (final FileNotFoundException e) {
System.out.println("That file was not found. Program terminating...");
e.printStackTrace();
}
}
Any help would be appreciated thanks.
If i understood correctly, you just have to create a new Scanner, one for each file.
Like that:
public static void main(String[] args) {
int[] mergedArray = {};
Scanner input = new Scanner(System.in);
System.out.println("Enter the name of your first file (including file extension): ");
String filename1 = input.next();
System.out.println("Enter the name of your second file (including file extension): ");
String filename2 = input.next();
int[] firstArray = null;
int[] secondArray = null;
try {
Scanner in = new Scanner(new File(filename1));
int count = in.nextInt();
firstArray = new int[count];
firstArray[0] = count;
for (int i = 0; in.hasNextInt() && count != -1 && i < count; i++) {
firstArray[i] = in.nextInt();
}
} catch (final FileNotFoundException e) {
System.out.println("That file was not found. Program terminating...");
e.printStackTrace();
}
try {
Scanner in2 = new Scanner(new File(filename2));
int count = in2.nextInt();
secondArray = new int[count];
secondArray[0] = count;
for (int i = 0; in2.hasNextInt() && count != -1 && i < count; i++) {
secondArray[i] = in2.nextInt();
}
} catch (final FileNotFoundException e) {
System.out.println("That file was not found. Program terminating...");
e.printStackTrace();
}
// do the merge operation with the 2 arrays
}
Try this
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.util.Scanner;
import static java.lang.System.*;
import java.util.Collection;
import java.util.Collections;
import java.util.ArrayList;
import java.util.Arrays;
public final class TwoSourceMergeOne{
public static void main(String[] args) {
Integer [] mergedArray = null;
try(Scanner console = new Scanner(in)){
out.println("Enter the Source file names (including file extensions) : ");
out.print(">> ");
String sourceX = console.next();
out.print("\n>> ");
String sourceY = console.next();
Path sourceXPath = Paths.get(sourceX);
Path sourceYPath = Paths.get(sourceY);
if(!Files.exists(sourceXPath,LinkOption.NOFOLLOW_LINKS) || !Files.exists(sourceXPath,LinkOption.NOFOLLOW_LINKS)){
out.println("Sorry. Some source files are missing. Please make sure that they are available !");
return;
}
Scanner xInput = new Scanner(new FileInputStream(sourceXPath.toFile()));
Scanner yInput = new Scanner(new FileInputStream(sourceYPath.toFile()));
Collection<Integer> sourceXData = new ArrayList<>();
Collection<Integer> sourceYData = new ArrayList<>();
while(xInput.hasNextInt()) sourceXData.add(xInput.nextInt());
while(yInput.hasNextInt()) sourceYData.add(yInput.nextInt());
if(!sourceXData.isEmpty() && !sourceYData.isEmpty()){
Integer [] soure_x_array = sourceXData.toArray(new Integer[sourceXData.size()]);
Integer [] source_y_array = sourceYData.toArray(new Integer[sourceYData.size()]);
mergedArray = new Integer[soure_x_array.length+source_y_array.length];
int index = 0;
for(int x : soure_x_array) mergedArray[index ++] = x;
for(int y : source_y_array) mergedArray[index ++] = y;
out.printf("The merged array is = %s",Arrays.toString(mergedArray));
}else{
out.println("Sorry. No input data !!!");
}
}catch(IOException cause){ cause.printStackTrace();}
}
}
The two source files should be in the same folder as the program.
Hi there I have been having trouble appending entered data to the end of a binary file, having looked up how to do so I found a solution here on stack overflow:
try {
ObjectOutputStream out = new ObjectOutputStream (new FileOutputStream ("BinaryWrite.hagl", true));
out.writeObject(allTowns);
out.flush ();
}
catch (Exception e){
System.out.println("IMPOSSSIBLE");
}
In this piece of code allTowns is my array in which the data I wish to add is held. The problem I am getting is that when I run my program and it displays what is in the file at the end this piece of code never writes to the file at all, I was wondering if anyone could help me understand why this does not work or even just recommend a different method if necessary.
My full code (this part is currently commented out so one can easily create the file):
import java.util.*;
import java.io.*;
public class CoastaslTowns implements Serializable
{
public static Scanner input = new Scanner(System.in);
String name, county;
int population, area;
public static int count = 0;
public static int continuation = 0;
public static CoastaslTowns[] allTowns = new CoastaslTowns[50];
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int loop1 = 0;
for (int i=0; i < 50; i++) {
allTowns[i] = new CoastaslTowns();
}
while (loop1 == 0) {
System.out.println("Please enter the name of the town.");
String nameEntered = input.nextLine();
System.out.println("Please enter the county in which the town resides.");
String countyEntered = input.nextLine();
System.out.println("Please enter the population of the town.");
int populationEntered = input.nextInt();
System.out.println("Please enter the area of the town.");
int areaEntered = input.nextInt();
input.nextLine();
System.out.println("Are you satisfied with your entries?");
String satisfaction = input.nextLine();
if (satisfaction.equals("yes")) {
loop1 = 5;
System.out.println("Thank you for entering your details");
continuation = 1;
}
else if (satisfaction.equals("no")) {
System.out.println("Would you like to continue and enter more towns?");
String countychecker = input.nextLine();
if (countychecker.equals("yes")) {
}
else {
break;
}
}
writeToFile(nameEntered, countyEntered, populationEntered, areaEntered);
}
ReturnTowns();
}
public static void inputVariations(){
}
public static void writeToFile(String nameEntered, String countyEntered, int populationEntered, int areaEntered) {
int loop2 = 0;
while (loop2 == 0){
allTowns[count].population = populationEntered;
allTowns[count].name = nameEntered;
allTowns[count].county = countyEntered;
allTowns[count].area = areaEntered;
if (continuation == 1) {
loop2 = 1;
}
else {
loop2 = 1;
}
count = count + 1;
}
try {
FileOutputStream fileOut = new FileOutputStream("BinaryWrite.hgal");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(allTowns);
out.close();
fileOut.close();
} catch (IOException i) {}
/*
try {
ObjectOutputStream out = new ObjectOutputStream (new FileOutputStream ("BinaryWrite.hagl", true));
out.writeObject(allTowns);
out.flush ();
}
catch (Exception e){
System.out.println("IMPOSSSIBLE");
}
*/
}
public static void ReturnTowns(){
{
int x = 0;
CoastaslTowns[] bw = null;
try {
FileInputStream fileIn =
new FileInputStream("BinaryWrite.hgal");
ObjectInputStream in = new ObjectInputStream(fileIn);
bw = (CoastaslTowns[]) in.readObject();
while (bw[x].population != 0) {
System.out.println(bw[x].name);
System.out.println(bw[x].county);
System.out.println(bw[x].population);
System.out.println(bw[x].area);
System.out.println();
x++;
}
in.close();
fileIn.close();
} catch (IOException i) {
} catch (ClassNotFoundException c) {
}
}
}
}
Any help would be greatly appreciated.
I am trying to read and process several languages' dictionaries in Java. So how can I arrange my code according to that? Thanks.
To turn them uppercase, I used this:
String str_uc=str.toUpperCase(Locale.ENGLISH);
But it's not supported for other languages, I am trying to read.
However, the main issue is that I can't read files in other languages properly before I turned them into uppercase.
Here's what I have done so far. Works perfect for English dictionary.
import java.util.ArrayList;
import java.util.Locale;
import java.io.*;
public class XmlCreating {
static ArrayList<Character> keywordletters = new ArrayList<Character>();
static ArrayList<Character> wordletters = new ArrayList<Character>();
static ArrayList<String> threeletter = new ArrayList<String>();
static ArrayList<String> fourletter = new ArrayList<String>();
static ArrayList<String> fiveletter = new ArrayList<String>();
static ArrayList<String> sixletter = new ArrayList<String>();
static ArrayList<String> sevenletter = new ArrayList<String>();
static ArrayList<String> words = new ArrayList<String>();
static ArrayList<String> allletters = new ArrayList<String>();
public static boolean hasApostrophe(String line){
for(int i=0; i<line.length();i++) {
if(line.charAt(i)=='\'' || line.charAt(i)=='-' )
return false;
}
return true;
}
public static void findLetters(String word, ArrayList<Character> ary) {
for(int i=0; i<word.length(); i++) {
ary.add(word.charAt(i));
}
}
public static boolean consistLetters(String keyword,String word) {
keywordletters.clear();
wordletters.clear();
findLetters(keyword,keywordletters);
findLetters(word,wordletters);
boolean found = false;
for(int i=0; i<wordletters.size(); i++) {
found=false;
for(int j=0; j<keywordletters.size(); j++) {
if(keywordletters.get(j)!='\''){
if(wordletters.get(i)==keywordletters.get(j)) {
keywordletters.set(j,'\'');
found=true;
break;
}
}
}
if(found!=true)
return false;
}
return found;
}
public static void findWords(String keyword){
words.clear();
for(int i=0; i<threeletter.size(); i++)
{
if(consistLetters(keyword,threeletter.get(i))==true)
words.add(threeletter.get(i));
}
for(int i=0; i<fourletter.size(); i++){
if(consistLetters(keyword,fourletter.get(i))==true)
words.add(fourletter.get(i));
}
for(int i=0; i<fiveletter.size(); i++){
if(consistLetters(keyword,fiveletter.get(i))==true)
words.add(fiveletter.get(i));
}
for(int i=0; i<sixletter.size(); i++){
if(consistLetters(keyword,sixletter.get(i))==true)
words.add(sixletter.get(i));
}
for(int i=0; i<sevenletter.size(); i++){
if(consistLetters(keyword,sevenletter.get(i))==true)
words.add(sevenletter.get(i));
}
}
public static void main(String args[]) {
//Locale.setDefault(new Locale("tr","TR"));
try {
FileInputStream fstream1 = new FileInputStream("en-GB.dic");
DataInputStream in = new DataInputStream(fstream1);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String str;
while ((str = br.readLine()) != null) {
String str_uc=str.toUpperCase(Locale.ENGLISH);
if(hasApostrophe(str_uc)){
allletters.add(str_uc);
if(str.length()==3)
threeletter.add(str_uc);
else if(str.length()==4)
fourletter.add(str_uc);
else if(str.length()==5)
fiveletter.add(str_uc);
else if(str.length()==6)
sixletter.add(str_uc);
else if(str.length()==7)
sevenletter.add(str_uc);
}
}
in.close();
}
catch (Exception e) {
System.err.println(e);
}
System.out.println(sevenletter.size());
System.out.println(sixletter.size());
System.out.println(fiveletter.size());
System.out.println(allletters.size());
int noOfXml=(int)(sevenletter.size()/10);
int lastXml=(int)(sevenletter.size()%10);
try{
int a=0;
int b=10;
for(int x=1;x<noOfXml+1;x++) {
FileWriter fstream2 = new FileWriter(x+".xml");
BufferedWriter out = new BufferedWriter(fstream2);
out.write("<?xml version='1.0' encoding='utf-8' ?><dictionary>");
for(int i=a;i<b;i++) {
findWords(sevenletter.get(i));
out.write("<ltr s='"+sevenletter.get(i)+"' w=");
for(int j=0; j<words.size();j++) {
out.write("'"+words.get(j)+"'");
if(j<words.size()-1)
out.write(";");
}
out.write("/>");
}
a=b;
b=b+10;
out.write("</dictionary>");
//Close the output stream
out.close();
}}catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
//for last five keywords
if(lastXml!=0) {
try{
FileWriter fstream3 = new FileWriter((noOfXml+1)+".xml");
BufferedWriter out1 = new BufferedWriter(fstream3);
out1.write("<?xml version='1.0' encoding='utf-8' ?><dictionary>");
for(int i=sevenletter.size()-lastXml;i<sevenletter.size();i++) {
findWords(sevenletter.get(i));
out1.write("<ltr s='"+sevenletter.get(i)+"' w=");
for(int j=0; j<words.size();j++) {
out1.write("'"+words.get(j)+"'");
if(j<words.size()-1)
out1.write(";");
}
out1.write("/>");
}
out1.write("</dictionary>");
//Close the output stream
out1.close();
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}//main
}//class
I encode each file as UTF-8
I would read each dictionary into a Set<String> possibly a NavigableSet<String> for each langage and I would place these is a Map keyed by the language.
Another way is to use words as key in a Map:
HashMap<(String) word ,Set<(String) codeLanguage>>
and, as Peter Lawrey sed, in this same Map
<(String) codeLanguage, Set(String) allLanguageWorld>>
If you use oriental language, you have to use Unicode.
I am creating a search engine that reads in a text file, and prints out a word that a user can search for. I'm currently creating an index of arrays to be searched for. More information can be found here: http://cis-linux1.temple.edu/~yates/cis1068/sp12/homeworks/concordance/concordance.html
When I run this program right now, I get an "Array Index Out of Bounds Exception"
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 43
at SearchEngine.main(SearchEngine.java:128)
Can anyone help debug?
import java.util.*;
import java.io.*;
public class SearchEngine {
public static int getNumberOfWords (File f) throws FileNotFoundException {
int numWords = 0;
Scanner scan = new Scanner(f);
while (scan.hasNext()) {
numWords++;
scan.next();
}
scan.close();
return numWords;
}
public static void readInWords (File input, String [] x) throws FileNotFoundException {
Scanner scan = new Scanner(input);
int i = 0;
while (scan.hasNext() && i<x.length) {
x[i] = scan.next();
i++;
}
scan.close();
}
public static int getNumOfDistinctWords (File input, String [] x) throws FileNotFoundException {
Scanner scan = new Scanner(input);
int count = 0;
int i = 1;
while (scan.hasNext() && i<x.length) {
if (!x[i].equals(x[i-1])) {
count++;
}
i++;
}
scan.close();
return count;
}
public static void readInDistinctWords (String [] x, String [] y) {
int i = 1;
int k = 0;
while (i<x.length) {
if (!x[i].equals(x[i-1])) {
y[k] = x[i];
k++;
}
i++;
}
}
public static int getNumberOfLines (File input) throws FileNotFoundException {
int numLines = 0;
Scanner scan = new Scanner(input);
while (scan.hasNextLine()) {
numLines++;
scan.nextLine();
}
scan.close();
return numLines;
}
public static void readInLines (File input, String [] x) throws FileNotFoundException {
Scanner scan = new Scanner(input);
int i = 0;
while (scan.hasNextLine() && i<x.length) {
x[i] = scan.nextLine();
i++;
}
scan.close();
}
Main
public static void main(String [] args) {
try {
//gets file name
System.out.println("Enter the name of the text file you wish to search");
Scanner kb = new Scanner(System.in);
String fileName = kb.nextLine();
String TXT = ".txt";
if (!fileName.endsWith(TXT)) {
fileName = fileName.concat(TXT);
}
File input = new File(fileName);
//First part of creating index
System.out.println("Creating vocabArray");
int NUM_WORDS = getNumberOfWords(input);
//System.out.println(NUM_WORDS);
String [] wordArray = new String[NUM_WORDS];
readInWords(input, wordArray);
Arrays.sort(wordArray);
int NUM_DISTINCT_WORDS = getNumOfDistinctWords(input, wordArray);
String [] vocabArray = new String[NUM_DISTINCT_WORDS];
readInDistinctWords(wordArray, vocabArray);
System.out.println("Finished creating vocabArray");
System.out.println("Creating concordanceArray");
int NUM_LINES = getNumberOfLines(input);
String [] concordanceArray = new String[NUM_LINES];
readInLines(input, concordanceArray);
System.out.println("Finished creating concordanceArray");
System.out.println("Creating invertedIndex");
int [][] invertedIndex = new int[NUM_DISTINCT_WORDS][10];
int [] wordCountArray = new int[NUM_DISTINCT_WORDS];
int lineNum = 0;
while (lineNum<concordanceArray.length) {
Scanner scan = new Scanner(concordanceArray[lineNum]);
while (scan.hasNext()) {
int wordPos = Arrays.binarySearch(vocabArray, scan.next());
wordCountArray[wordPos]+=1;
for(int i = 0; i < invertedIndex.length; i++) {
for(int j = 0; j < invertedIndex[i].length; i++) {
if (invertedIndex[i][j] == 0) {
invertedIndex[i][j] = lineNum;
break;
} } }
}
lineNum++;
}
System.out.println("Finished creating invertedIndex");
}
catch (FileNotFoundException exception) {
System.out.println("File Not Found");
}
} //main
} //class
for(int j = 0; j < invertedIndex[i].length; i++) {
should probably be
j++
not
i++
Update after your fix.
That means that Arrays.binarySearch(vocabArray, scan.next()) is not finding the item being searched for. You cannot assume that the vocabArray has the item you are searching for. You will need to add an if(... < 0) for the binarySearch call.