so basically I only know how to read integers and store them in an array, but what about both Integers and words? Here is my code for doing just the integers from an array from an earlier time, the method is readFileAndReturnWords. How could I change it to read both integers and words as well?
import java.util.Scanner;
import java.util.InputMismatchException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class WordsNsuch {
public static void main(String [ ] commandlineArguments){
//Error message when arg is blank
if(commandlineArguments.length == 0) {
System.err.println("You did not enter anything");
System.exit(0);
}
String[] array = readFileAndReturnWords(commandlineArguments[0]);
sortAndPrintTheArray(array, commandlineArguments[0]);
}
//RIGHT HERE GUYS
public static String readFileAndReturnWords(String filename){
String[] temp = new String[10000];
int i = 0;
//connects file
File file = new File(filename);
Scanner inputFile = null;
try{
inputFile = new Scanner(file);
}
//When arg is mistyped
catch(FileNotFoundException Exception1) {
System.out.println("File not found!");
System.exit(0);
}
//counts the amount of strings
if (inputFile != null) {
try {
while (inputFile.hasNext()) {
try {
temp[i] = inputFile.nextInt();//This is a problem
i++;
} catch (InputMismatchException Exception2) {
inputFile.next();
}
}
}
finally {
inputFile.close();
}
String[] array = new String[i];
System.arraycopy(temp, 0, array, 0, i);
return array;
}
return new String[] {};
}
public static void sortAndPrintTheArray(String [] array, String filename){
Sorting.display = false;
Sorting.insertionSort(array, 0, array.length-1);//figure out how to get the last word later
System.out.println("ASCII listing of words in file:\"" + filename + "\" = " + array.length);
for (int i = 0; i < array.length; i++) {
System.out.println("index = " + i + "," + " element = " + array[i]);
}
}
}
I'm not going into your code but here is an example of how to read both numbers and words :
//while there's anything including numbers and words
while(textfile.hasNext())
{
//if there's a number, read it!
if(textfile.hasNextInt())
{
int number = textfile.nextInt(); //it can be double, float..
}
else
textfile.next()
String word1 = textfile.hasNext();
String word2 = textfile.hastNext();
f(textfile.hasNextInt())
{
int number2 = textfile.nextInt(); //it can be double, float..
}
else
textfile.next()
.......
}
Anytime if there's a number, try if-else statement ("else" statement depends on how big and how full your textfile is with numbers and letters) but when after a number there follows a String use else statement similar to the else statement in the code that I've mentioned; when there's a String, just read that with textfileName.hasNext() w/o any conditionals. Any question, do not hesitate to ask!
Here is a little code snippet to help you out, I have based it on your code.
I would handle the arrays slightly differently but I just want to point you in the right direction, not do the work for you.
This will create two arrays: ints and strs one staininging the integers and one containing the strings.
int[] ints = new int[10000];
String[] strs = new String[10000];
int i = 0;
int j = 0;
File file = new File(filename);
Scanner inputFile = null;
try {
inputFile = new Scanner(file);
} catch(FileNotFoundException Exception1) {
System.out.println("File not found!");
System.exit(0);
}
try {
while (inputFile.hasNext()) {
if (inputFile.hasNextInt()) {
ints[i++] = inputFile.nextInt();
} else {
strs[j++] = inputFile.next();
}
}
}
Hope this helps!
Related
Below is my code...
The code below is taking a .txt file of some radiation read outs. My job is to find the max number of counts per minute in the file within 5 counts.
I'e got it working, but I need to omit the part of the line, so I thought I could make this piece of the code:
/* String temp = new String(data)
* temp=list.get(i);
* System.outprintln(temp.substring(0,16) +" ");
*/
and integrate it in. I keep trying several cases, and am not thinking. Any advice?
`import java.util.*;
//Import utility pack, *look at all classes in package.
import java.io.*;
//Good within directory.
public class counterRadiation {
private static String infile = "4_22_18.txt";
//Input
private static String outfile = "4_22_18_stripped.txt";
private static Scanner reader;
//Output
public static void main(String[] args) throws Exception{
//throw exception and then using a try block
try {
//Use scanner to obtain our string and input.
Scanner play = new Scanner(new File(infile));
/* String temp = new String(data)
* temp=list.get(i);
* System.outprintln(temp.substring(0,16) +" ");
*/
Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outfile), "utf-8"));
String lineSeparator = System.getProperty("line.separator");
play.useDelimiter(lineSeparator);
while (play.hasNext()) {
String line = play.next();
if (line.matches(dataList)) {
writer.write(line + "\r\n");
}
}
writer.close();
play.close();
try {
reader = new Scanner(new File(infile));
ArrayList<String> list = new ArrayList<String>();
while (reader.hasNextLine()) {
list.add(reader.nextLine());
}
int[] radiCount = new int[list.size()];
for (int i = 0; i < list.size();i++) {
String[] temp = list.get(i).split(",");
radiCount[i] = (Integer.parseInt(temp[2]));
}
int maxCount = 0;
for (int i = 0; i < radiCount.length; i++) {
if (radiCount[i] > maxCount) {
maxCount = radiCount[i];
}
}
for (int i = 0;i < list.size() ;i++) {
if(radiCount[i] >= maxCount - 4) {
System.out.println(list.get(i)+" "+ radiCount[i]);
}
}
}catch(FileNotFoundException e){
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}`
Although it is not quite clear what you want to get rid of you could use .indexOf(String str) to define the first occurrence of the sub-string you want to exclude. For example in your code:
String data = "useful bit get rid of this";
int index = data.indexOf("get rid of this");
System.out.println(data.substring(0,index) + "are cool");
//Expected result:
//"useful bits are cool"
from Java doc
Background: This program reads in a text file and replaces a word in the file with user input.
Problem: I am trying to read in a line of text from a text file and store the words into an array.
Right now the array size is hard-coded with an number of indexes for test purposes, but I want to make the array capable of reading in a text file of any size instead.
Here is my code.
public class FTR {
public static Scanner input = new Scanner(System.in);
public static Scanner input2 = new Scanner(System.in);
public static String fileName = "C:\\Users\\...";
public static String userInput, userInput2;
public static StringTokenizer line;
public static String array_of_words[] = new String[19]; //hard-coded
/* main */
public static void main(String[] args) {
readFile(fileName);
wordSearch(fileName);
replace(fileName);
}//main
/*
* method: readFile
*/
public static void readFile(String fileName) {
try {
FileReader file = new FileReader(fileName);
BufferedReader read = new BufferedReader(file);
String line_of_text = read.readLine();
while (line_of_text != null) {
System.out.println(line_of_text);
line_of_text = read.readLine();
}
} catch (Exception e) {
System.out.println("Unable to read file: " + fileName);
System.exit(0);
}
System.out.println("**************************************************");
}
/*
* method: wordSearch
*/
public static void wordSearch(String fileName) {
int amount = 0;
System.out.println("What word do you want to find?");
userInput = input.nextLine();
try {
FileReader file = new FileReader(fileName);
BufferedReader read = new BufferedReader(file);
String line_of_text = read.readLine();
while (line_of_text != null) { //there is a line to read
System.out.println(line_of_text);
line = new StringTokenizer(line_of_text); //tokenize the line into words
while (line.hasMoreTokens()) { //check if line has more words
String word = line.nextToken(); //get the word
if (userInput.equalsIgnoreCase(word)) {
amount += 1; //count the word
}
}
line_of_text = read.readLine(); //read the next line
}
} catch (Exception e) {
System.out.println("Unable to read file: " + fileName);
System.exit(0);
}
if (amount == 0) { //if userInput was not found in the file
System.out.println("'" + userInput + "'" + " was not found.");
System.exit(0);
}
System.out.println("Search for word: " + userInput);
System.out.println("Found: " + amount);
}//wordSearch
/*
* method: replace
*/
public static void replace(String fileName) {
int amount = 0;
int i = 0;
System.out.println("What word do you want to replace?");
userInput2 = input2.nextLine();
System.out.println("Replace all " + "'" + userInput2 + "'" + " with " + "'" + userInput + "'");
try {
FileReader file = new FileReader(fileName);
BufferedReader read = new BufferedReader(file);
String line_of_text = read.readLine();
while (line_of_text != null) { //there is a line to read
line = new StringTokenizer(line_of_text); //tokenize the line into words
while (line.hasMoreTokens()) { //check if line has more words
String word = line.nextToken(); //get the word
if (userInput2.equalsIgnoreCase(word)) {
amount += 1; //count the word
word = userInput;
}
array_of_words[i] = word; //add word to index in array
System.out.println("WORD: " + word + " was stored in array[" + i + "]");
i++; //increment array index
}
//THIS IS WHERE THE PRINTING HAPPENS
System.out.println("ARRAY ELEMENTS: " + Arrays.toString(array_of_words));
line_of_text = read.readLine(); //read the next line
}
BufferedWriter outputWriter = null;
outputWriter = new BufferedWriter(new FileWriter("C:\\Users\\..."));
for (i = 0; i < array_of_words.length; i++) { //go through the array
outputWriter.write(array_of_words[i] + " "); //write word from array to file
}
outputWriter.flush();
outputWriter.close();
} catch (Exception e) {
System.out.println("Unable to read file: " + fileName);
System.exit(0);
}
if (amount == 0) { //if userInput was not found in the file
System.out.println("'" + userInput2 + "'" + " was not found.");
System.exit(0);
}
}//replace
}//FTR
You can use java.util.ArrayList (which dynamically grows unlike an array with fixed size) to store the string objects (test file lines) by replacing your array with the below code:
public static List<String> array_of_words = new java.util.ArrayList<>();
You need to use add(string) to add a line (string) and get(index) to retrieve the line (string)
Please refer the below link for more details:
http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html
You may want to give a try to ArrayList.
In Java normal arrays cannot be initialized without giving initial size and they cannot be expanded during run time. Whereas ArrayLists have resizable-array implementation of the List interface.ArrayList also comes with number of useful builtin functions such as
Size()
isEmpty()
contains()
clone()
and others. On top of these you can always convert your ArrayList to simple array using ArrayList function toArray(). Hope this answers your question. I'll prepare some code and share with you to further explain things you can achieve using List interface.
Use not native [] arrays but any kind of java collections
List<String> fileContent = Files.readAllLines(Paths.get(fileName));
fileContent.stream().forEach(System.out::println);
long amount = fileContent.stream()
.flatMap(line -> Arrays.stream(line.split(" +")))
.filter(word -> word.equalsIgnoreCase(userInput))
.count();
List<String> words = fileContent.stream()
.flatMap(line -> Arrays.stream(line.split(" +")))
.filter(word -> word.length() > 0)
.map(word -> word.equalsIgnoreCase(userInput) ? userInput2 : word)
.collect(Collectors.toList());
Files.write(Paths.get(fileName), String.join(" ", words).getBytes());
of course you can works with such lists more traditionally, with loops
for(String line: fileContent) {
...
}
or even
for (int i = 0; i < fileContent.size(); ++i) {
String line = fileContent.get(i);
...
}
i just like streams :)
I have written a spellchecker program that checks the spelling of all words in a file. It should read each word of a file and check whether it is contained in a word list. The program should write the incorrect words to a file and I have received an error message on lines 57-58, saying "type mismatch between void to String" and when I ran it on eclipse, I got an unresolved compilation problem" error. What am I doing wrong so it can run smoothly on both Eclipse & on the command line? Here's the code:
import java.util.*;
import java.io.*;
public class SpellChecker {
public static void readDict(){
File file = new File ("words.txt");
ArrayList <String> array = new ArrayList <String> ();
try{
Scanner input = new Scanner (file).useDelimiter("[A-Za-z]");
while (input.hasNext()){
String line = input.nextLine();
String [] wordArray = line.split(" ");
for(String str : wordArray){
array.add(str);
}
}
input.close();
}
catch(FileNotFoundException e){
System.out.println("File is not found.");
System.exit(1);
}
return;
}
public static void readFile(){
File file = new File ("mary.txt");
String [] array;
String [] array2 = null;
try{
Scanner input = new Scanner (file);
int i = 0;
array = new String [10];
while(i < array.length && input.hasNext()){
String story = input.nextLine();
String[] storyarray = story.split(" ");
array2[i] = storyarray[i];
i++;
for(i = 0; i < array2.length; i++){
System.out.println(array2[i]);
}
input.close();
}
}
catch(FileNotFoundException e){
System.out.println("File cannot be found.");
System.exit(1);
}
}
public static void main(String[] args) {
args[0] = readDict();
args[1] = readFile();
if(args == 4){
System.out.println(args[0]);
System.out.println(args[1]);
}
}
public static Scanner input = new Scanner(System.in);
}
so here is ALL of my code, which, in summary, standardises two text files then prints out the result.
import java.io.*;
import java.util.*;
public class Plagiarism {
public static void main(String[] args) {
Plagiarism myPlag = new Plagiarism();
if (args.length == 0) {
System.out.println("Error: No files input");
}
else if (args.length > 0) {
try {
for (int i = 0; i < args.length; i++) {
BufferedReader reader = new BufferedReader (new FileReader (args[i]));
List<String> foo = simplify(reader);
for (int j = 0; j < foo.size(); j++) {
System.out.print(foo.get(j));
}
}
}
catch (Exception e) {
System.err.println ("Error reading from file");
}
}
}
public static List<String> simplify(BufferedReader input) throws IOException {
String line = null;
List<String> myList = new ArrayList<String>();
while ((line = input.readLine()) != null) {
myList.add(line.replaceAll("[^a-zA-Z0-9]","").toLowerCase().trim());
}
return myList;
}
}
The next bit I want to implement is this: Using the command line, the 3rd argument will be any integer(size of blocks) which the user enters. I have to use this then to store the elements of that array into separate blocks which overlap. EG: The cat sat on the mat, block size 4. Block 1 would be: Thec Block 2: heca Block 3: ecat, and so on, until it reaches the end of the array.
Any ideas?
Thanks in advance guys.
To get the block size use this :
if(args.length != 4)
return;
int blockSize = Integer.valueOf(args[3]);
This an example that could help you
import java.util.*;
public class Test {
public static void main(String[] args) {
String line = "The dog is in the house";
line = line.replace(" ", "");
List<String> list = new ArrayList<String>();
for (int i = 0; i <= line.length() - 4; i++)
list.add(line.substring(i, i + 4));
System.out.println(list);
}
output :
[Thed, hedo, edog, dogi, ogis, gisi, isin, sint, inth, nthe, theh, heho, ehou, hous, ouse]
Is that what you want to do
WE can code it in mulitple ways, here is one example.
Input 3 arguments first 2 are files and 3rd one is the block size:
File1 contain: this is a boy
File2 contain: this is a girl
block size: 4
Expected Output:
this hisi isis sisa isab sabo aboy boyt oyth ythi this hisi isis sisa isag sagi agir girl
Program:
import java.io.;
import java.util.;
public class Plagiarism {
public static void main(String[] args) {
//Plagiarism myPlag = new Plagiarism();
/*args = new String[3];
Scanner s = new Scanner(System.in);
System.out.println("Enter the 1st file path");
args[0] = s.next();
System.out.println("Enter the 2nd file path");
args[1] = s.next();
System.out.println("Enter size of block");
args[2] = s.next();*/
int blockSize = Integer.valueOf(args[2]);
StringBuilder wholeContent = new StringBuilder("");
if (args.length == 0) {
System.out.println("Error: No files input");
}
else if (args.length > 0) {
try {
for (int i = 0; i < args.length-1; i++) {
BufferedReader reader = new BufferedReader (new FileReader (args[i]));
List<String> foo = simplify(reader);
for (int j = 0; j < foo.size(); j++) {
//System.out.print(foo.get(j));
wholeContent.append(foo.get(j));
}
}
System.out.println("The content of Line is = "+ wholeContent);
System.out.println("The content of line based on the block size = "+ blockSize + " is:");
for(int j=0; j<=(wholeContent.length()-blockSize); j++){
System.out.print(wholeContent.substring(j, j+4));
System.out.print(" ");
}
}
catch (Exception e) {
e.printStackTrace();
System.err.println ("Error reading from file");
}
}
}
public static List<String> simplify(BufferedReader input) throws IOException {
String line = null;
List<String> myList = new ArrayList<String>();
while ((line = input.readLine()) != null) {
if(!" ".equals(line))
myList.add(line.replaceAll("[^a-zA-Z0-9]","").toLowerCase().trim());
}
return myList;
}
}
All you are asking to do can be done with string manipulation. First use replaceAll() to remove your spaces, then use a for loop and substring() to create your blocks.
for your for loop you need to modify it so that it reads the two texts, then uses the 3rd argument as the block size so you would change your for loop from:
for(int i = 0; i<args.length;i++)
to:
for(int i = 1; i<3; i++)
this reads the first two arguments but not the third
I've been having stressful issues all day on this program to read a text file for integers and storing the integers into an array. I thought I finally got the solution with the code below.
But unfortunately.. I have to loop through the file with the method hasNextLine().
Then using nextInt() to read integers from the file and store them into an array.
So using scanner constructor, hasNextLine(), next(), and nextInt() methods.
Then use try and catch to determine which words are integers and which are not by using the InputMismatchException. Also a exception for blank lines in the file?
Problem is I did not use a try and catch and exceptions, as I just skipped over none-ints.
Also, I'm using a int array so I want to do this without list.
public static void main(String[] commandlineArgument) {
Integer[] array = ReadFile4.readFileReturnIntegers(commandlineArgument[0]);
ReadFile4.printArrayAndIntegerCount(array, commandlineArgument[0]);
}
public static Integer[] readFileReturnIntegers(String filename) {
Integer[] array = new Integer[1000];
int i = 0;
//connect to the file
File file = new File(filename);
Scanner inputFile = null;
try {
inputFile = new Scanner(file);
}
//If file not found-error message
catch (FileNotFoundException Exception) {
System.out.println("File not found!");
}
//if connected, read file
if (inputFile != null) {
// loop through file for integers and store in array
try {
while (inputFile.hasNext()) {
if (inputFile.hasNextInt()) {
array[i] = inputFile.nextInt();
i++;
}
else {
inputFile.next();
}
}
}
finally {
inputFile.close();
}
System.out.println(i);
for (int v = 0; v < i; v++) {
System.out.println(array[v]);
}
}
return array;
}
public static void printArrayAndIntegerCount(Integer[] array, String filename) {
//print number of integers
//print all integers that are stored in array
}
}
Then I'll be printing everything in my 2nd method, but that I can worry about later. :o
Example Content of Text File:
Name, Number
natto, 3
eggs, 12
shiitake, 1
negi, 1
garlic, 5
umeboshi, 1
Sample Output Goal:
number of integers in file "groceries.csv" = 6
index = 0, element = 3
index = 1, element = 12
index = 2, element = 1
index = 3, element = 1
index = 4, element = 5
index = 5, element = 1
Sorry for the similar question. I'm very stressed out, and even more that I was doing it all wrong... I'm completely stuck at this point :(
You can read Your file in this way.
/* using Scanner */
public static Integer[] getIntsFromFileUsingScanner(String file) throws IOException {
List<Integer> l = new ArrayList<Integer>();
InputStream in = new FileInputStream(file);
Scanner s = new Scanner(in);
while(s.hasNext()) {
try {
Integer i = s.nextInt();
l.add(i);
} catch (InputMismatchException e) {
s.next();
}
}
in.close();
return l.toArray(new Integer[l.size()]);
}
/* using BufferedReader */
public static Integer[] getIntsFromFile(String file) throws IOException {
List<Integer> l = new ArrayList<Integer>();
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
try {
l.add(Integer.parseInt(line.split(",")[1]));
} catch (NumberFormatException e) {
}
}
return l.toArray(new Integer[l.size()]);
}
And with Your code:
public static void main(String[] commandlineArgument) {
Integer[] array = getIntsFromFileUsingScanner(commandlineArgument[0]);
ReadFile4.printArrayAndIntegerCount(array, commandlineArgument[0]);
}
Here is one way to meet your new requirements,
public static Integer[] readFileReturnIntegers(
String filename) {
Integer[] temp = new Integer[1000];
int i = 0;
// connect to the file
File file = new File(filename);
Scanner inputFile = null;
try {
inputFile = new Scanner(file);
}
// If file not found-error message
catch (FileNotFoundException Exception) {
System.out.println("File not found!");
}
// if connected, read file
if (inputFile != null) {
// loop through file for integers and store in array
try {
while (inputFile.hasNext()) {
try {
temp[i] = inputFile.nextInt();
i++;
} catch (InputMismatchException e) {
inputFile.next();
}
}
} finally {
inputFile.close();
}
Integer[] array = new Integer[i];
System.arraycopy(temp, 0, array, 0, i);
return array;
}
return new Integer[] {};
}
public static void printArrayAndIntegerCount(
Integer[] array, String filename) {
System.out.printf(
"number of integers in file \"%s\" = %d\n",
filename, array.length);
for (int i = 0; i < array.length; i++) {
System.out.printf(
"\tindex = %d, element = %d\n", i, array[i]);
}
}
Outputs
number of integers in file "/home/efrisch/groceries.csv" = 6
index = 0, element = 3
index = 1, element = 12
index = 2, element = 1
index = 3, element = 1
index = 4, element = 5
index = 5, element = 1
Maybe you can resolve this issue by brief code as I post below.
public static List<Integer> readInteger(String path) throws IOException {
List<Integer> result = new ArrayList<Integer>();
BufferedReader reader = new BufferedReader(new FileReader(path));
String line = null;
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = null;
line = reader.readLine();
String input = null;
while(line != null) {
input = line.split(",")[1].trim();
matcher = pattern.matcher(input);
if(matcher.matches()) {
result.add(Integer.valueOf(input));
}
line = reader.readLine();
}
reader.close();
return result;
}
Enclose try catch for below code:
try
{
if (inputFile.hasNextInt()) {
array[i] = inputFile.nextInt();
i++;
}
else {
inputFile.next();
}
}catch(Exception e)
{
// handle the exception
}