In my program, it reads a file called datafile.txt... inside the datafile.txt is a random 3 lines of words. What my program does is reads the file the user types in and then they can type in a Line # and Word # and it will tell them the word that is in that location.. for example..
What is the file to read from?
datafile.txt
Please enter the line number and word number (the first line is 1).
2 2
The word is: the
My problem is that my program reads the 3 lines in the txt doc as 0, 1 ,2 and the words start from 0. So to read the first word in the first line they would have to type 0,0 instead of 1,1. What I am trying to do is make it work so they can type 1,1 instead of 0,0. Not sure what my problem is right now, here is my code....
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class readingFile {
/**
* #param args
* #throws IOException
* #throws validException
*/
public static void main(String[] args) throws IOException, checkException
{
System.out.println("Enter file name: " );
Scanner keyboard = new Scanner(System.in);
BufferedReader inputStream = null;
ArrayList<String> file = new ArrayList<String>();
String fileName = keyboard.next();
System.out.println ("The file " + fileName +
" has the following lines below: ");
System.out.println();
try
{
inputStream = new BufferedReader(new FileReader(fileName));
ArrayList<String> lines = new ArrayList<String>();
while(true)
{
String line = inputStream.readLine();
if(line ==null)
{
break;
}
Scanner itemnize = new Scanner(line);
while(itemnize.hasNext())
{
lines.add(itemnize.next());
}
lines.addAll(lines);
System.out.println(lines+"\n");
}
System.out.println("Please enter the line number and word number");
int index1 = keyboard.nextInt();
int index = keyboard.nextInt();
System.out.println("The word is: "+ lines.get(index));
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file " + fileName);
}
inputStream.close();
}
private static void checkValid(ArrayList<String> items, int index) throws checkException
{
throw new checkException("Not Found");
}
}
The obvious solution to adapt 1-based user input to 0-based internal representation is to subtract one at some point. Seeing that you don't even use index1, writing
lines.get(index - 1)
isn't going to solve your problem completely. But I guess you can take it from there, and do something similar for the word index.
As I assume you are just learning to program I will point out 3 areas of improvement
Much like how mathematics has BIDMAS which determines the order of evaluation of an expression Java and other program languages evaluate statements in a particulate way. This means within the Parentheses of a function you may include a statment instead of a variable or constant. This will be evaluated with the result (or return) been passed into the called function. This is why MvG says you can do lines.get(index - 1)
Not all exceptions you should consider and plan around will the compiler inform you about. For example in your code an invalid input for line number or word number is entered you will get a Runtime Exception (array index out of bound)
Naming of variables should be useful, you have index and index1. What's the difference? I assume from reading your code one should be the user selected index of the line number and the second should be the index of the word on said line. May I suggest requestedLineIndex and requestedWordIndex.
On a final note this is not a usual StackOverflow question hence why your question has been 'voted down'. If you are learning as part of a course is there a course forum or Virtual Learning Environment (VLE) you can post questions on? The support of your peers at the same level of learning tends to help with exploring the basics of a language.
Related
Task is to read an article of text from outside file and put each word (no signs) into and Array List as a separate String.
Although I´m sure my path is correct and readable(I can for example perform character count), no matter what I do my Array List of words from that article comes out as empty. I may be struggling with a way how to separate words from each other and other signs. Also with storing the result of reading.
I´ve been googling for the last 2 hours and reading similar answers here but no success. So decided for the first time to ask a question.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import org.w3c.dom.Text;
public class PlaceForErrors {
public static void main(String[] args) {
Scanner scan = null;
try {
scan = new Scanner(new File("\\Users\\marga\\Desktop\\objekt program\\oo2021\\w05_kontrolltoo1\\textHere.txt")).useDelimiter(" \\$ |[\\r\\n]+");
String token1 = "";
ArrayList<String> text = new ArrayList<String>();
while (scan.hasNext()) {
token1 = scan.next();
text.add(token1);
}
String[] textArray = text.toArray(new String[0]);
for(String element : textArray){
System.out.println(element);
}
//Controlling if the ArrayList is empty and it is
boolean tellme = text.isEmpty();
System.out.println(tellme);
} catch (FileNotFoundException exception) {
System.out.println(exception);
}
finally{
scan.close();
}
}
}
String[] textArray = text.toArray(new String[0]);
This line is your problem. You're trying to allocate the ArrayList into a String array of size 0, resulting in it appearing empty.
I would modify the array declaration to initialize using the ArrayList size, like so:
String[] textArray = text.toArray(new String[text.size()]);
Then you can see if your token delimiter works.
Quick recap of your steps
Your program does a lot. I counted 9 steps:
opens a (text) file as (text) input-stream to read from
create a scanner for tokens from this input-stream using a regular-expression as delimiter (= tokenizer)
scan for and iterate over each subsequent token (if any found) using a while-loop
each of this iteration adds the token to a list
if no more tokens, then iteration ends (or never started!): converts the list to array
loop over each array element using a for-each-loop and print it
check if originally collected list is empty and print true or false
catch the exception if file was not found and print the it
finally close any opened resources: the file that was read from
Now let's start to look for the step where something potentially could go wrong: the places for errors 😏️
Analysis: What can go wrong?
Look at the listed steps above and think of each from a what-could-go-wrong perspective, a quick check list (not correlated to the step-numbers above!):
Can your text-file be found, does it exist and is readable? Yes, otherwise any IOException like FileNotFoundException would have been thrown and printed.
Is the opened file empty with a size of 0 bytes? You can check using:
File textFile = new File("\\Users\\marga\\Desktop\\objekt program\\oo2021\\w05_kontrolltoo1\\textHere.txt");
System.out.println( "File size: " + textFile.length() );
// before passing the extracted file-variable to scanner
scan = new Scanner( textFile ).useDelimiter(" \\$ |[\\r\\n]+");
Does the delimiter/regex properly split/tokenize an example input string? Try:
// Just a separate test: same delimiter, with test-input
String delimiterRegex = " \\$ |[\\r\\n]+";
String testInput = " $ Hello\r\nWorld !\n\nBye.";
// so we create a new scanner
Scanner testScanner = new Scanner( testInput ).useDelimiter(delimiterRegex);
int tokenCount = 0;
while( testScanner.hasNext() ) {
tokenCount++;
System.out.println("Token " + tokenCount + ": " + testScanner.next() );
}
testScanner.close();
Should print 3 tokens (Hello, World !, Bye.) on 3 lines in console. The special sequence $ (space-dollar-space), any \n or \r (newline or carriage-return) are omitted and have split the tokens.
We should check the list directly after the while-loop:
// Not only checking if the ArrayList is empty, but its size (is 0 if empty)
System.out.println("Scanned tokens in list: " + text.size());
If it is empty, then we neither need to fill the array, nor loop to print will start (because nothing to loop).
Hope these explanations help you to perform the analysis (debugging/testing) yourself.
Let me know if it helped you to catch the issue.
Takeaway: Divide and conquer!
Why did I count the steps, above? Because all are potential places for errors.
In developer jargon we also say this main method of class PlaceForErrors has many responsibilities: counted 9.
And there is a golden principle called Single Responsibility Principle (SRP).
Put simply: It is always good to split a large problem or program (here: your large main method) into smaller pieces. These smaller pieces are easier to work with (mentally), easier to test, easier to debug if errors or unexpected happens. Divide & conquer!
If it works, start improving
You can split up this long method doing 9 steps into smaller methods.
Benefit: each method can be tested in isolation, like the testScanner.
If your program finally works as expected and your manual test went green.
Then you should post the working code to the sister-site: CodeReview.
Be curious and ask again, e.g. how to split up the methods, how to make testable, etc.
You'll get lot's of experienced advise on how to improve it even more.
Thank you for your input everyone!
Regarding the code, I went and checked everything step by step and on the way learned more about delimiters and scanner. I fixed my delimiter and everything worked just fine now.
Beside the fact that I made a newbie mistake and didn´t show the full code, as I though it would take away the attention from the main problem. I had two conflicting scanners in my main function(one I showed you and the other one was scanning again and counting letters A). And they both worked great separately(when one or the other is commented out), but refused to work together. So I found a way to combine them and use scanner only once. I will share my full code for reference now.
I learned my mistake, and will provide the my full code always in the future.
If someone is curious the full task was the following:
Read the text from a separate file using scanner and store it in an Array List.
Count how many letters "A" (small or big) there were and how big of % they made out of all the letters in the text.
Count how many words had one letter A, two letters A in them, etc.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Trying {
public static void main(String[] args) {
Scanner scan = null;
try {
//SCANNING FILE AND CREATING AN ARRAYLIST
scan = new Scanner(new File("\\Users\\marga\\Desktop\\objekt program\\oo2021\\w05_kontrolltoo1\\textHere.txt")).useDelimiter("[.,:;()?!\"\\s]+");
int aCount = 0;
int letterCount =0;
String token1 = "";
int wordWithAtLeastOneA = 0;
int wordWithA = 0;
int word1A = 0;
int word2A = 0;
int word3A = 0;
int word4OrMoreA = 0;
ArrayList<String> text = new ArrayList<String>();
// SCANNING EVERY WORD INTO AN ARRAY LIST
while(scan.hasNext()){
token1 = scan.next();
text.add(token1);
}
System.out.println("Amount of words in the scanned list is : " + text.size());
//COUNTING HOW MANY LETTERS 'A' TEXT HAS
for(String element : text){
for (int i=0;i<=element.length()-1;i++){
if (element.charAt(i) == 'A' || element.charAt(i) == 'a') {
aCount++;
}
}
}
System.out.println("There are "+aCount+" letters 'A'. ");
//HOW MANY LETTERS IN TOTAL TEXT HAS
for(String element : text){
for (int i=0;i<=element.length()-1;i++){
letterCount++;
}
}
//COUNTING HOW MANY WORDS HAVE 'A' LETTER IN THEM
for(String element : text){
for (int i=0;i<=element.length()-1;i++){
if (element.charAt(i) == 'A' || element.charAt(i) == 'a') {
wordWithAtLeastOneA++;;
break;
}
}
}
System.out.println("There are "+wordWithAtLeastOneA+" words that have at least one letter 'A' in them.");
System.out.println();
//COUNTING NUMBER OF WORDS THAT HAVE 1/2/3 or more 'A' LETTER IN THEM
for(String element : text){
wordWithA = 0;
for (int i=0;i<=element.length()-1;i++){
if (element.charAt(i) == 'A' || element.charAt(i) == 'a') {
wordWithA++;
if(wordWithA == 1){
word1A++;
}else if (wordWithA == 2){
word2A++;
}else if (wordWithA == 3){
word3A++;
}else if (wordWithA >= 4){
word4OrMoreA++;
}
}
}
}
System.out.println("There were "+ word1A+ " words, that had one letter 'A' in them." );
System.out.println("There were "+ word2A+ " words, that had two letters 'A' in them." );
System.out.println("There were "+ word3A+ " words, that had three letters 'A' in them." );
System.out.println("There were "+ word4OrMoreA+ " words, that had 4 or more letters 'A' in them." );
//COUNTING HOW MANY LETTERS THERE ARE IN TOTAL, COMPARE TO NUMBER OF "A" LETTERS
int percentOfA = aCount*100/letterCount;
System.out.println();
System.out.println("The entire number of letters is "+ letterCount+" and letter 'A' makes " + percentOfA+ "% out of them or " +aCount+ " letters.");
// for(String element : textArray){
// System.out.println(element);
// }
} catch (FileNotFoundException exception) {
System.out.println(exception);
}
finally{
scan.close();
}
}
}
And the text is:
Computer programming is an enormously flexible tool that you can use to do amazing things that are otherwise either manual and laborsome or are just impossible.
If you are using a smartphone, a chat app or if you are unlocking your car with the push of a button,
then you must know that all these things are using some kind of programming.
You are already immersed in the programs of different types.
In fact, software is running your life. What if you learn and start running these programs according to your will?
And the output is:
There are 35 words that have at least one letter 'A' in them.
There were 35 words, that had one letter 'A' in them.
There were 3 words, that had two letters 'A' in them.
There were 0 words, that had three letters 'A' in them.
There were 0 words, that had 4 or more letters 'A' in them.
The entire number of letters is 416 and letter 'A' makes 9% out of them or 38 letters.
My goal is to have the program run a count on the number of times the word 'secret' appears in the text document while ignoring words such as 'secretive' and 'secsecret'. I was able to get it to count, but it is only returning an occurrence of the word 2 times instead of the 4 times the word appears in the document and is including the 'secsecret' I added. Is there some kind of exception statement that can be added to keep it from picking up the 'secsecret' in the document? And I'm not sure what I did incorrectly for it to only pick up 2 occurrences of the word 'secret'. This is a lab assignment for my object-oriented programming class.
Here is what I have so far:
package lab4;
import java.util.Scanner;
import java.io.File;
import java.util.NoSuchElementException;
import java.io.FileNotFoundException;
public class Lab4 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception{
String keyword = "secret";
int c = 0;
try
{
Scanner file = new Scanner(new File("/Users/Taba/Desktop/Lab4textdoc.txt"));
while (file.hasNext())
{
keyword = file.nextLine();
if (! file.hasNextLine())
{
System.out.println("Invalid file format");
String invalidData = file.nextLine();
}
else
{
keyword = file.nextLine();
String newLine = file.nextLine();
c++;
System.out.println("The keyword " + keyword + " appears " + c + " times." );
}
}
file.close();
}
catch(FileNotFoundException fnfe)
{
System.out.println("Unable to find Lab4textdoc.txt, exiting");
}
catch(NoSuchElementException nsee)
{
System.out.println("Attempt to read past the end of the file");
}
}
}
Here is what I have in the text document:
secret
secsecret
secretive
secret
Secret
secret
And this is the output it is giving me:
run:
The keyword secsecret appears 1 times.
The keyword Secret appears 2 times.
BUILD SUCCESSFUL (total time: 0 seconds)
You 1st problem is that you are overwriting the word you suppose to find here:
keyword = file.nextLine();
you need instead to declare another string object and compare that against the keyword.
On the other hand, you didn't specify if words must match sensitiveness, because in java a string "Secret" is not the same as "SECRET" or "secret"
for both options you will need equals or equalsIgnoreCase
Basically:
every time you call nextLine, you read the next line of the file. So you should call it just once per iteration (only in the beggining of the while loop). As you're calling more than once inside the loop, you're skipping lots of lines without taking a look at them
you're not really counting what you want. You should include an if (is the string I want) c++. But you're incrementing c without testing anything, leading to wrong results
Your code should be something like:
while (file.hasNext()) {
keyword = file.nextLine();
if ("secret".equals(keyword)) {
c++;
}
}
System.out.println("The keyword " + keyword + " appears " + c + " times." );
If you want to count more words (like "Secret"), you should create a different counter for each one, and do a respective if for each case as well.
So I have an assignment from an online course to create a program that can scan a massive document. What this document contains is hundreds of pairs of letters that include GB GG BB BG and each set of two letters has its own line. What I have to do is figure out how many lines there are and then figure out how many of the different sets of two letters there are. I've attempted the code but I am currently stuck. The code that I have compiles but when I run it in BlueJ an output window doesn't even pop up. This is what I have so far:
/**
* This program sorts through a file and
* determines the composition of various families.
* Timothy Pierce
* 1/2/2016
*/
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class Family
{
public static void main(String [ ] args) throws IOException
{
boolean isTwoBoys;
boolean isTwoGirls;
boolean isBoyGirl;
int twoBoysCounter = 1;
int twoGirlsCounter = 1;
int boyGirlCounter = 1;
String line = "";
Scanner inFile = new Scanner(new File ("C:\\Users\\TEM\\Desktop\\Projects\\Family\\Document\\test1.txt"));
while (inFile.hasNextLine ())
{
isTwoBoys = (line.equals("BB"));
isTwoGirls = (line.equals("GG"));
isBoyGirl = (line.equals("BG")||line.equals("GB"));
if(isTwoBoys)
{
twoBoysCounter++;
}
else if(isTwoGirls)
{
twoGirlsCounter++;
}
else if(isBoyGirl)
{
boyGirlCounter++;
}
}
System.out.println();
System.out.println("Two Boys: " + twoBoysCounter);
System.out.println("One Boy One Girl: " + boyGirlCounter);
System.out.println("Two Girls: " + twoGirlsCounter);
inFile.close();
}
}
I've tried for several hours but I cant seem to get it to work. I haven't even been able to count how many line there are. Any help would be very appreciated! Thanks!
You never read the next line, so you're stuck in an infinite while loop
I suggest that you look into Files.readAllLines function for this case.
It loads all the lines in a List over which you can easily iterate and do what you need.
Example: Files.readAllLines(Paths.get("C:\\Users\\TEM\\Desktop\\Projects\\Family\\Document\\test1.txt", Charsets.default()) will load what you need
your while loop is inifinite as stated above since inFile.hasNextLine () is a boolean statement that returns true or false but it doesnt advance the scanner to the next line, you need to add to each of the if statements a :
inFile.nextLine() //advance the inputstream
Skipping over the "no readNextLine" issue pointed out by others, your basic technique is terrible.
Use a Map<String, Integer>.
Store the character pair as the key.
Every time you read a new pair,
attempt to retrieve it from the map.
If you get null, then the pair does not already have a counter,
so store 1 as the value.
If you get a non-null value, add 1 and store the new count.
When finished reading,
you have a map of character pairs to number of times encountered.
Hi I'm in a programming class over the summer and am required to create a program that reads input from a file. The input file includes DNA sequences ATCGAGG etc and the first line in the file states how many pairs of sequences need to be compared. The rest are pairs of sequences. In class we use the Scanner method to input lines from a file, (I read about bufferedReader but we have not covered it in class so not to familiar with it) but am lost on how to write the code on how to compare two lines from the Scanner method simultaneously.
My attempt:
public static void main (String [] args) throws IOException
{
File inFile = new File ("dna.txt");
Scanner sc = new Scanner (inFile);
while (sc.hasNextLine())
{
int pairs = sc.nextLine();
String DNA1 = sc.nextLine();
String DNA2 = sc.nextLine();
comparison(DNA1,DNA2);
}
sc.close();
}
Where the comparison method would take a pair of sequences and output if they had common any common characters. Also how would I proceed to input the next pair, any insight would be helpful.. Just stumped and google confused me even further. Thanks!
EDIT:
Here's the sample input
7
atgcatgcatgc
AtgcgAtgc
GGcaAtt
ggcaatt
GcT
gatt
aaaaaGTCAcccctccccc
GTCAaaaaccccgccccc
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
gctagtacACCT
gctattacGcct
First why you are doing:
while (sc.hasNextLine())
{
int pairs = sc.nextLine();
While you have pairs only in one line not pairs and two lines of input, but number of lines once? Move reading pairs from that while looop and parse it to int, then it does not matter but you could use it to stop reading lines if you know how many lines are there.
Second:
throws IOException
Might be irrelevant but, really you don't know how to do try catch and let's say skip if you do not care about exceptions?
Comparision, if you read strings then string has method "equals" with which you can compare two strings.
Google will not help you with those problems, you just don't know it all, but if you want to know then search for basic stuff like type in google "string comparision java" and do not think that you can find solution typing "Reading two lines from an input file using Scanner" into google, you have to go step by step and cut problem into smaller pieces, that is the way software devs are doing it.
Ok I have progz that somehow wokrked for me, just finds the lines that have something and then prints them out even if I have part, so it is brute force which is ok for such thing:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class program
{
public static void main (String [] args) throws IOException
{
File inFile = new File ("c:\\dna.txt");
Scanner sc = new Scanner (inFile);
int pairs = Integer.parseInt(sc.nextLine());
for (int i = 0; i< pairs-1; i++)
{
//ok we have 7 pairs so we do not compare everything that is one under another
String DNA1 = sc.nextLine();
String DNA2 = sc.nextLine();
Boolean compareResult = comparison(DNA1,DNA2);
if (compareResult){
System.out.println("found the match in:" + DNA1 + " and " + DNA2) ;
}
}
sc.close();
}
public static Boolean comparison(String dna1, String dna2){
Boolean contains = false;
for (int i = 0; i< dna1.length(); i++)
{
if (dna2.contains(dna1.subSequence(0, i)))
{
contains = true;
break;
}
if (dna2.contains(dna1.subSequence(dna1.length()-i,dna1.length()-1 )))
{
contains = true;
break;
}
}
return contains;
}
}
When there is an error in an input file is it possible to find out in which line of the input file the scanner failed?
The following code always prints out the total lines in reader instead of line number where the error happened:
import java.io.LineNumberReader;
import java.io.StringReader;
import java.util.NoSuchElementException;
import java.util.Scanner;
import org.junit.Test;
public class ScannerTests {
static private final String text = "FUNCTION_BLOCK Unnamed_project\n\tVAR_INPUT\n\t\tUnnamed_variable1::REAL;\n\tEND_VAR\nEND_FUNCTION_BLOCK";
#Test
public void scannerLineNumberFailedTest() {
LineNumberReader reader = new LineNumberReader(new StringReader(text));
int lineNumber = -1;
try {
Scanner sc = new Scanner(reader);
sc.useDelimiter("\\s*\\b\\s*");
sc.next("(?i)FUNCTION_BLOCK");
String blockName = sc.next();
assert sc.hasNext("(?i)VAR_INPUT");
sc.next("(?i)VAR_INPUT");
String variableName = sc.next();
sc.next(":"); // line of failure - got a unexpected '::'
String type = sc.next("\\w+");
sc.next(";");
sc.next("(?i)END_VAR");
sc.next("(?i)END_FUNCTION_BLOCK");
assert "Unnamed_project".equals(blockName);
assert "Unnamed_variable1".equals(variableName);
assert "REAL".equals(type);
sc.close();
} catch (NoSuchElementException ex) {
lineNumber = reader.getLineNumber() + 1;
System.err.println("Error in line: " + lineNumber);
}
assert lineNumber == 3;
}
}
A Scanner does not track line numbers or character numbers.
You could try to implement this using a custom FilterReader that counts lines and characters, but I think that won't be accurate in all cases. It will tell you how far you how far the scanner got through the stream, but it cannot take account of the fact that the scanner can read ahead a number of characters in a hasNext method and then wind back and read the input using a different next method. For example:
if (sc.hasNext("[A-Z ]+")) {
sc.nextInteger();
If the nextInteger() method call fails, the "current position" as reported by the FilterReader could be many characters past the stream position where the bad integer is detected.
In the worst case, this winding back can take you back past line boundaries ... depending on how you have configured the delimiters. So (in theory) even the line numbers cannot be tracked with certainty.
The only way to track line and character numbers 100% accurately in all cases is to implement your own input parsing system that tracks these things itself ... through all of the forward and backward movement of its input stream cursor.