How to use scanner class in java [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I want to convert my names.rtf file which contains (the names of people(String) names.rtf = ("ABHISHEK","ANKIT",........"ASHISH") ) into single String[] name such that name={"ABHISHEK","ANKIT",......"ASHISH"}
Following is my code suggest please.
import java.io.*;
import java.util.Scanner;
public class FileScan {
public static void main(String[] args) throws IOException {
Scanner s = null;
String thestring ="";
try {
s = new Scanner(new BufferedReader(new FileReader("/Users/abhishekkumar/Desktop/names1.rtf")));
while (s.hasNextLine()) {
thestring+=(s.nextLine());
thestring+="\n";
}
} finally {
if (s != null) {
s.close();
}
}
System.out.println(thestring);
}
}

First of all, why are you using the scanner class in this way to read file ,with bufferedReader,fileReader etc ? Use :-
File file = new File("filename.fileformat");
Scanner scanner = new Scanner(file);
A possible solution looking at your file in the comments would be:-
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
// Location of file to read
File file = new File("data.rtf");
String line="";
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
line = scanner.nextLine();
//System.out.println(line);
}
String[] nameArray=line.split(",");
for(String s:nameArray){
System.out.print(s+" "); //parse the array to verify entries
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

Related

I am trying to read the first line in my .txt document in to my program?

I have this written so far, I am just doing a few practice codes from my text book. I cant seem to get this to read the first line in my .txt .
/**
*
*/
import java.util.Scanner; //needed for scanner class
import java.io.*; //needed for File I/O classes
/**
* #author Megan
*
*/
public class Pres {
/**
* #param args
*/
public static void main(String[] args) throws IOException
{
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter name of file: C:/User/Frances/Documents/USPres.txt");
String filename = keyboard.nextLine();
File file = new File("C:/User/Frances/Documents/USPres.txt");
Scanner inputFile = new Scanner(file);
String line = inputFile.nextLine();
System.out.println("The first line in the file is: ");
System.out.println(line);
inputFile.close();
}
}
I believe it has to do with this portion of the code:
String line = inputFile.nextLine();
I am not quite sure what to type into the (), if I should type anything at all. I could be wrong. My textbook isn't to clear about the proper format. If you could help, please and thank you. :)
To read txt file do this:
String line = "";
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(fileName));
while ((line = in.readLine()) != null) {
// do something here
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
It will read all lines in the text but since it's practice go ahead and try to figure out how to read just one line.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Pres {
public static void main(String[] args) throws FileNotFoundException, IOException {
// BufferedReader is best for read line from file or else
BufferedReader Bfr = new BufferedReader(new FileReader("your_filename_or_path.txt"));
// get first line from file
String firstLinetext = Bfr .readLine();
System.out.println(firstLinetext ); // print first line
}
}

Once it has taken input(words) from a file, how to terminate at a specific word?

How would I go about making my program terminate once it reaches a specific word from a file. So far, I have it printing out all the words from the file which I want. "input" contains the words "one two three four galumph" just like that.
import java.util.Scanner;
import java.io.*;
class EchoWords {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc2 = null;
try {
sc2 = new Scanner(new File("input"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (sc2.hasNextLine()) {
Scanner s2 = new Scanner(sc2.nextLine());
while (sc2.hasNext()) {
String s = s2.next();
System.out.println(s);
}
}
}
}

Java program keep running, no compiler's error [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm trying to write a code for selecting features from a txt file.
i.e. size = 1.4356474
species = fw, wevb, wrg , gwe
....
this is the code I wrote so far:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.util.concurrent.ExecutionException;
public class Metodi {
public static void main (String[] args) {
String volume = findVolume();
System.out.println(volume);
}
public static String readSpecification() {
String spec = "";
// trying to read from file the specification...
try {
BufferedReader reader = new BufferedReader(new FileReader("Gemcitabine.txt"));
String line = reader.readLine();
while(line!=null) {
spec += line + "\n";
line = reader.readLine();
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return spec;
}
public static String findVolume () {
String res = "";
String vol = "volume";
try {
BufferedReader reader1 = new BufferedReader(new FileReader("Sample.txt"));
String line1 = reader1.readLine();
while(line1!=null) {
if(line1.toLowerCase().indexOf(vol) != -1) {
String[] str = line1.split("=");
res = str[1].split(" ")[0];
}
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return res;
}
}
It doesn't give me any compiler's error, but when I launch it, it keeps running and doesn't end.
Any help?
Your loop is not reading line after line, it needs to call read line on each iteration, it should be :
String line1 =;
while((line1 = reader1.readLine()) != null) {
if(line1.toLowerCase().indexOf(vol) != -1) {
String[] str = line1.split("=");
res = str[1].split(" ")[0];
}
}
In findVolume(), you check line1 != null in your while-condition.
You never change line1 within the loop. Thus, it will never be equal to null and the loop won't terminate.

Java error Syntax error on token "(", ; expected ub Java function [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Hi I am getting this error on my Java code
Syntax error on token "(", ; expected
I am trying to make a function, maybe my syntax is not correct.
this is my code:(I point where the error is)
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
String ruta = "C:\\Users\\HernanEi\\Desktop\\contadoresInternet.txt";
File archivo = new File(ruta);
String linea = null;
try {
FileReader lector = new FileReader(archivo);
BufferedReader buff = new BufferedReader(lector);
while( ( linea = buff.readLine() ) != null ) {
System.out.println(linea);
}
buff.close();
lector.close();
} catch(FileNotFoundException ex) {
} catch(IOException ex) {
}
final int countWord(String codigo, File archivo)<-------Error Here
{
int count = 0;
Scanner scanner = new Scanner("C:\\Users\\HernanEi\\Desktop\\contadoresInternet.txt");
while (scanner.hasNextLine()) {
String nextToken = scanner.next();
if (nextToken.equalsIgnoreCase(codigo))
count++;
}
return count;
}
}
}
Sorry if it is something really simple, this is all in my main class.
Move the } from the bottom of your code to the end of the main method.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
String ruta = "C:\\Users\\HernanEi\\Desktop\\contadoresInternet.txt";
File archivo = new File(ruta);
String linea = null;
try {
FileReader lector = new FileReader(archivo);
BufferedReader buff = new BufferedReader(lector);
while( ( linea = buff.readLine() ) != null ) {
System.out.println(linea);
}
buff.close();
lector.close();
} catch(FileNotFoundException ex) {
} catch(IOException ex) {
}
}
final int countWord(String codigo, File archivo){
int count = 0;
Scanner scanner = new Scanner("C:\\Users\\HernanEi\\Desktop\\contadoresInternet.txt");
while (scanner.hasNextLine()) {
String nextToken = scanner.next();
if (nextToken.equalsIgnoreCase(codigo))
count++;
}
return count;
}
}
You're missing a closing brace on your main method, just before the line that's giving you the error message. Unfortunately, sometimes syntax errors that are not obvious at the point they occur end up making something later appear wrong, and so the compiler's error message can be misleading.
What can help is using a good editor that understands the language. You might already be doing that. If so, the fact that your editor placed the first line of your countWord definition at the same level as your main method body is a hint that you didn't properly close out the latter.
I re-formated your code, so the error gets more obvious
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class HelloWorld {
public static void main(String... args) {
String ruta = "C:\\Users\\HernanEi\\Desktop\\contadoresInternet.txt";
File archivo = new File(ruta);
String linea = null;
try {
FileReader lector = new FileReader(archivo);
BufferedReader buff = new BufferedReader(lector);
while ((linea = buff.readLine()) != null) {
System.out.println(linea);
}
buff.close();
lector.close();
} catch (FileNotFoundException ex) {
} catch (IOException ex) {
}
} // Moved this parenthesis up
final int countWord(String codigo, File archivo) { // <-------Error Here
int count = 0;
Scanner scanner
= new Scanner("C:\\Users\\HernanEi\\Desktop\\contadoresInternet.txt");
while (scanner.hasNextLine()) {
String nextToken = scanner.next();
if (nextToken.equalsIgnoreCase(codigo)) {
count++;
}
}
return (count);
}
}
Some remarks on your code:
you should take a look at the try-with-resources.
you should definitely write your code with english variable-/attribute names
even if you can neglect some parenthesis (i.e. ifs with only a single line of code), you should write them for clarity

Reading a .txt file that results in a stackoverflow error

Can someone please help me determine what I am doing wrong with my code. I am getting a stackoverflow error. At the end of my code I am using recursion and I don't have a base case to stop the program. It keeps looping and displaying my text file until I get a stackoverflow error.
public class Reader
{
public static String readFinalQuestionBank() throws Exception
{
File textFile = new File("C:\\Users\\Joseph\\Documents\\School Files - NHCC\\CSci 2002\\FinalQuestionBank_JosephKraemer.txt"); //file location
try
{
Scanner scan = new Scanner(textFile); //Scanner to import file
while(scan.hasNextLine()) //Iterator - while file has next line
{
String qBank = scan.nextLine(); //Iterator next line
String[] tempArray = qBank.split("::"); //split data via double colon
System.out.println(qBank); //print data line
}
scan.close(); //close scanner
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
return readFinalQuestionBank(); //use of Recursion
}//end method readFinalQuestionBank
}//end class Reader
if your main objective is to read the whole input file by implementing recursivity take a look at the following example, it replaces the while statement with a recursive method call.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Reader
{
public static String readFinalQuestionBank() throws Exception
{
File textFile = new File("C:\\Users\\Diego\\Documents\\sandbox\\input.txt");
String output = "";
try
{
Scanner scan = new Scanner(textFile);
output = readLineRecursively(scan);
scan.close();
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
return output;
}
private static String readLineRecursively(Scanner scan){
if(!scan.hasNextLine()){
return "";
}
String qBank = scan.nextLine();
return qBank + "\n" + readLineRecursively(scan);
}
public static void main(String[] args){
try {
System.out.println(readFinalQuestionBank());
} catch (Exception e) {
e.printStackTrace();
}
}
}

Categories

Resources