I am trying to search the File for characters in Java language. For that I am using Scanner to scan the file.
Well to check the Heirarchy work, I am using System.out.print("Worked till here!"); so that I can check whether it is executed or not. I was able to execute the code till the last stage, but then I found that the essential boolean variable wasn't altered, which was under the condition to check whether there is a character match or not.
The file contents are as
Ok, here is some text!
Actually this file is created to test the validity of the java application
Java is my favourite programming language.
And I think I can score even more :)
Wish me luck!
However, no matter what I search it always prompts me to be false.
Here is the code I am using
public static void main (String[] args) throws IOException {
// Only write the output here!!!
System.out.print("Write the character to be found in the File: ");
Scanner sc = new Scanner(System.in);
String character = sc.next();
// Find the character
System.out.println("Searching now...");
getCharacterLocation(character);
// Close the resource!
sc.close();
}
The method call executed and the method is as
public static void getCharacterLocation (String character) throws IOException {
System.out.println("File found...");
File file = new File("res/File.txt");
Scanner sc = new Scanner(file);
int lineNumber = 0;
int totalLines = 0;
boolean found = false;
// First get the total number of lines
while(sc.hasNextLine()) {
totalLines++;
sc.nextLine();
System.out.println("Line looping! For Total Lines variable.");
}
int[] lineNumbers = new int[totalLines];
int lineIndex = 0;
System.out.println("Searching in each line...");
while(sc.hasNextLine()) {
// Until the end
/* Get each of the character, I mean string from
* each of the line... */
while(sc.hasNext()) {
// Until the end of line
String characterInLine = sc.next();
if(sc.findInLine(character) != null) {
found = true;
}
}
System.out.print(sc.nextLine() + "\n");
lineNumber++;
sc.nextLine();
}
System.out.println("Searching complete, showing results...");
// All done! Now post that.
if(found) {
// Something found! :D
System.out.print("Something was found!");
} else {
// Nope didn't found a fuck!
System.out.println("Sorry, '" + character +
"' didn't match any character in file.");
}
sc.close();
}
Never mind the extra usage of variables, and arrays. I would use it in further coding if I can get the character and set the value to true.
Here is the output of this program.
Initial Stage
This is the initial stage for that. I wrote Ok in the input field, you can see Ok is the very first character in the File too.
Final Stage
This is the result after the execution.
Any help in this?
You count lines and don't restart the scanner.
boolean found = false;
// First get the total number of lines
while(sc.hasNextLine()) {
totalLines++;
sc.nextLine();
System.out.println("Line looping! For Total Lines variable.");
}
int[] lineNumbers = new int[totalLines];
int lineIndex = 0;
System.out.println("Searching in each line..."); // <------
while(sc.hasNextLine()) {
add e.g.
UPDATED from the comment
sc.close();
sc = new Scanner(file);
before the next while(sc.hasNextLine())
You need to implement a way to string your characters together and check them against your input. It appears that you don't currently have a way to do this in your code.
Try building an array of characters with your scanner, and moving through and doing a check of your input vs the indexes. Or maybe there is a way to implement the tonkenizer class achieve this.
Put remember, what you are looking for is not a character, it is a string, and you need to keep this in mind when writing your code.
When you count your lines you use while(sc.hasNextLine()).
After this loop, your scanner is behind the last line, so when you go to your next loop while(sc.hasNextLine()) { it is never executed.
There are multiple problems with your code:
You Iterated through your scanner here:
while(sc.hasNextLine()) {
totalLines++;
sc.nextLine();
System.out.println("Line looping! For Total Lines variable.");
}
So after this you have to reset it again to read for further processing.
While searching for character you are having two loops:
while(sc.hasNextLine()) {
// Until the end
/* Get each of the character, I mean string from
* each of the line... */
while(sc.hasNext()) {
// Until the end of line
String characterInLine = sc.next();
if(sc.findInLine(character) != null) {
found = true;
}
}
Here you just need a single loop like:
while(sc.hasNextLine()) {
String characterInLine = sc.nextLine();
if(characterInLine.indexOf(character) != -1) {
found = true;
break;
}
}
Related
I have the below code that is not reading or infinitely looping when a user inputs text using System.in. If I hard code the text into the Scanner variable it works fine so I am not sure what is wrong with the System.in portion of this code. Any help is appreciated.
import java.util.Scanner; // needed to use the Scanner class
public class HW2 {
static Scanner in = new Scanner(System.in);
public static void main(String [] args) {
System.out.println("Enter your line here");
int the =0;
int and =0;
int is = 0;
int was =0;
int noword =0;
while (in.hasNext()){
String word = in.next();
if (word.equals("the")){
the++;
}
else if( word.equals("and")){
and ++;
}
else if (word.equals("is")){
is++;
}
else if (word.equals("was")){
was++;
}
else noword++;
}
System.out.println("The number of occurrences of the was"+ the);
System.out.println("The number of occurrences of and was"+ and);
System.out.println("The number of occurrences of is was"+ is);
System.out.println("The number of occurrences of was was"+ was);
}
}
As has been mentioned, a Scanner attached to System.in will block while looking for more input. One way to approach this would be to read a single line in from the scanner, tokenize it, and then loop through the words that way. That would look something like this:
//...
String line = in.nextLine(); // Scanner will block waiting for user to hit enter
for (String word : line.split(" ")){
if (word.equals("the")) {
the++;
}
//...
You can always substitute one loop structure (for, while, do-while) for another. They all do the same thing, just with different syntax to make one a bit simpler to use than others depending on the circumstances. So if you want to use a while loop, you can do something like this:
// ...
String line = in.nextLine();
String[] tokens = line.split(" ");
int i = 0;
while (i < tokens.length){
String word = tokens[i];
if (word.equals("the")) {
the++;
}
// ...
i++;
} // end of the while loop
However, I'm of the opinion that a for loop is cleaner in the case of looping over a known set of data. While loops are better when you have an unknown dataset, but a known exit condition.
As System.in is always available while the program is running unless you close it. It will never exit the while loop. So you could add else if (word.equals("exit")) { break; }. This way, whenever you type 'exit' it will close the while loop and execute the code AFTER the while loop.
Depends, do you want to just read 1 line of text and then count the words individually?
Because is you want only one line you could take the input string using the Scanner library and split the string into individual words and apply the if-statement then. Something like:
public static void main(String [] args) {
System.out.println("Enter your line here");
int the =0;
int and =0;
int is = 0;
int was =0;
int noword =0;
String input = in.nextLine();
String words[] = input.split(" ");
for (String s : words) {
if (s.equals("the")){
the++;
} else if( s.equals("and")){
and++;
} else if (s.equals("is")){
is++;
} else if (s.equals("was")){
was++;
} else {
noword++;
}
}
System.out.println("The number of occurrences of the was: "+ the);
System.out.println("The number of occurrences of and was: "+ and);
System.out.println("The number of occurrences of is was: "+ is);
System.out.println("The number of occurrences of was was: "+ was);
}
This way you won't need a while loop at all. So it's more processor and memory efficient.
So I am trying to read a file using a scanner. This file contains data where there are two towns, and the distance between them follows them on each line. So like this:
Ebor,Guyra,90
I am trying to get each town individual, allowing for duplicates. This is what I have so far:
// Create scanner for file for data
Scanner scanner = new Scanner(new File(file)).useDelimiter("(\\p{javaWhitespace}|\\.|,)+");
// First, count total number of elements in data set
int dataCount = 0;
while(scanner.hasNext())
{
System.out.print(scanner.next());
System.out.println();
dataCount++;
}
Right now, the program prints out each piece of information, whether it is a town name, or an integer value. Like so:
Ebor
Guyra
90
How can I make it so I have an output like this for each line:
Ebor
Guyra
Thank you!
Assuming well-formed input, just modify the loop as:
while(scanner.hasNext())
{
System.out.print(scanner.next());
System.out.print(scanner.next());
System.out.println();
scanner.next();
dataCount += 3;
}
Otherwise, if the input is not well-formed, check with hasNext() before each next() call if you need to break the loop there.
Try it that way:
Scanner scanner = new Scanner(new File(file));
int dataCount = 0;
while(scanner.hasNext())
{
String[] line = scanner.nextLine().split(",");
for(String e : line) {
if (!e.matches("-?\\d+")) System.out.println(e);;
}
System.out.println();
dataCount++;
}
}
We will go line by line, split it to array and check with regular expression if it is integer.
-? stays for negative sign, could have none or one
\\d+ stays for one or more digits
Example input:
Ebor,Guyra,90
Warsaw,Paris,1000
Output:
Ebor
Guyra
Warsaw
Paris
I wrote a method called intParsable:
public static boolean intParsable(String str)
{
int n = -1;
try
{
n = Integer.parseInt(str);
}
catch(Exception e) {}
return n != -1;
}
Then in your while loop I would have:
String input = scanner.next();
if(!intParsable(input))
{
System.out.print(input);
System.out.println();
dataCount++;
}
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
When I use scan.nextLine(), input boxes don't work properly. If it's scan.next() ,works perfectly.But Why? Ain't I supposed to use scan.nextLine() for string?
import java.util.Scanner;
public class Test{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
System.out.println("p");
String p = scan.nextLine();
System.out.println("q");
String q = scan.next();
System.out.println("m");
String m = scan.next();
}
}
Before using them, try to check the doc's.
Reason :
Scanner.nextLine : The java.util.Scanner.nextLine() method advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.
While, this is not Applicable to Scanner.nextInt
Hence, the Scanner.nextInt method does not consume the last newline character of your input, and thus that newline is consumed in the next call to Scanner.nextLine.
Basic Solution would be to use blank Scanner.nextLine after Scanner.nextInt just to consume rest of that line including newline.
For Example
int myVal1 = input.nextInt();
input.nextLine();
String myStr1 = input.nextLine();
This is the solution to the problem I'd use. The above comment by Tahir Hussain Mirwould likely be the cause of the problem
import java.util.ArrayList;
import java.util.Scanner;
public class app {
public static void main(String[] args) {
// declare scanner
Scanner scan = new Scanner(System.in);
// what ever number you need, it could be calculated
int numberOfInputLines = 3;
// the list of the lines entered
ArrayList<String[]> list = new<String[]> ArrayList();
// add each line to the list
for (int i = 0; i < numberOfInputLines; i++) {
// get entire line as a single string
String input = scan.nextLine();
// split the line into tokens, and store the array in the array list
String[] result = input.split("\\s");
list.add(result);
}
// iterate through each line
for (int i = 0; i < list.size(); i++) {
// iterate through the line
for (int j = 0; j < list.get(i).length; j++) {
if (isInteger(list.get(i)[j]) == true) {
// do what you want if the input is an int
//to show it works
System.out.println("int: " + list.get(i)[j]);
} else {
// do what you want if a the token inputed is a string
//to show it works
System.out.println("String: " + list.get(i)[j]);
}
}
}
}
// greasy way to check if is an int
private static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
return false;
} catch (NullPointerException e) {
return false;
}
// only got here if we didn't return false
return true;
}
}
You should use nextLine and then convert it to your expected types.
In above scenario read the line then cast it to an integer, because next and nextInt just read the input before a whitespace occurred. So when you are calling nextInt it will just consume the number and leave the newLine character which will be consumed in nextLine.
From the question, it looks like this is how you are going to read inputs input.
First integer.
Second a string line.
Third line will have two words separated by space.
This is what your code should be.
Scanner scan = new Scanner(System.in);
int x = Integer.parseInt(scan.nextLine()); //read line and then cast to integer
System.out.println("p");
String p = scan.nextLine();
System.out.println("q m");
String[] linesParts = scan.nextLine().split(" "); // read the whole line and then split it.
String q = linesParts[0];
String m = linesParts[1];
What I am trying to do is read from a file (in this case the file contains over 100,000+ lines) and store the values in an array, then print out the first 10 lines. However when I run the program I get the first line, and then followed by 9 lines of "null" which is obviously not what I want! This is the code and any tips would be appreciated.
import java.io.*;
import java.util.Scanner;
public class DawsonZachA5Q2{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a size for the number of letters for words: ");
int size = keyboard.nextInt();//prompts user for input
String[] array = new String[27000];
try {
File file = new File("big-word-list.txt");
Scanner scanner = new Scanner(file);
// Start a line count and declare a string to hold our current line.
int linecount=0;
// Tells user what we're doing
System.out.println("Searching for words with " + size + " letters in file...");
int wordCount=0;
while (scanner.hasNext()){
int i = 0;
String word = scanner.next();
if(size == word.length()){
wordCount++;
array[i]=word;
i++;
//add word to array
// increase the count and find the place of the word
}
}
linecount++;
System.out.println(wordCount);
System.out.println(wordCount+" words were found that have "+size+ " letters.");//final output
for(int o = 0; o<10; o++){
System.out.println(array[o]);
}
scanner.close();
}// our catch just in case of error
catch (IOException e) {
System.out.println("Sorry! File not found!");
}
} // main
} // class
Define int i = 0; outside of the while loop. It gets set to zero each time the loop runs. That is the problem here.
You have mistaken in the while loop. You must define 'int i = 0' before the while loop. In your case, what happen is that whenever the while loop execute, i is initialized to 0. i.e. every time, the word with required length found, that word will be stored in array[0] (Since i is initialized to 0 every iteration of while loop) replacing the previous stored value. As a result, you only get the first value and remaining displayed as null since nothing is stored after array[1].
Therefore, the actual flow should be like this.
// i is initialized outside of loop.
int i = 0;
while (scanner.hasNext()){
//int i = 0; this is your error
String word = scanner.next();
if(size == word.length()){
wordCount++;
array[i]=word;
i++;
//add word to array
// increase the count and find the place of the word
}
}
I'm trying to alternate a file but keeping some lines intact based on a user input. (Details below code)
public class RemoveLines {
public static void main(String[] args)
throws FileNotFoundException {
// prompt for input file name
Scanner console = new Scanner(System.in);
System.out.print("Type first file name to use: ");
String filename1 = console.nextLine();
System.out.print("Type second file name to use: ");
String filename2 = console.nextLine();
System.out.println("enter an integer: ");
int n = console.nextInt();
Scanner input = new Scanner(new File(filename1)); //put the first file as input
PrintStream output = new PrintStream(new File(filename2)); //put the second file as output
int count =0;
while(input.hasNextLine()){
count ++;
while(n<=count){
output.println(); // this is where i don't know what to place
}
}
}
}
the program should prompt the user to enter 2 file names and an integer n.
it should create a second file that contains the first n lines of the first file, while keeping it intact. If the first file contains less than n lines then the second file will contain all the lines of the first file.
i've started writing the while loop, but i am not sure what command i should include in order to have the desired output.
thank you.
Have a try with the following code:
int count = 0;
while (count < n) {
if (input.hasNextLine()) {
output.println(input.nextLine()); // this is where i don't know what to place
count++;
}else
{
break;
}
}
/**
* Close scanner
*/
input.close();
console.close();
output.close();
while(input.hasNextLine()){
count ++;
while(n<=count){
output.println(input.nextLine());
} else {
break;
}
}
You should also check the the input file exists.
And also you should close your input and output. I will not matter in this trivial case but it's something you should do in more complex applications.
You should open PrintStream with the append option set to true (which is false by default) -
PrintStream output = new PrintStream(new File(filename2, **true**));
Then you can do something like below -
String inputLine = scanner.readLine();
output.append(inputLine);