Scanner input new Scaner(doc); <---------- Error ; expected - java

I am trying to compile but I seem to be getting an error stating I am missing a ; on a line that has the ;. I have also looked around the code and can't see an error myself. I hope that you can point me in the right direction :)
import java.io.*;
import java.util.*;
public class marks
{
private String asses;
private int mark;
public marks()
{
}
public void createFile() throws Exception
{
File doc;
doc = new File ("marks.txt");
if(!doc.exists()){
doc.createNewFile();
System.out.println("A New File Has been Created");
}
else {
System.out.println ("File Already Exists");
}
}
public void enterMarks()
{
Scanner input new Scaner(doc); <---------- Error ; expected
while (input.hasNext()){
String asses = input.next();
int mark = input.nextInt();
System.out.println( asses +" "+ mark);
}
}
}

You're missing an =:
Scanner input = new Scanner(doc);

Scanner input = new Scanner(doc); "=" is missing and Scanner spells wrong; change visibility doc to global

Related

How to parse int or double values from text file in java application

i want to copy specific value from text file to Arraylist in Java Application. This is my text file( which is stored in my desktop as test.text)
String name = carrot;
double unit_price = 200;
int unit = 10;
This value i want to store in Arraylist, which is present in my main application as follow:
package com.main;
import com.collection.Ingridient;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class FileReaderApp {
public static void main(String[] args) throws FileNotFoundException, IOException {
Ingridient i_one = new Ingridient();
ArrayList<Ingridient> db = new ArrayList<Ingridient>();
FileReader fin = new FileReader("/home/yati/Desktop/test");
Scanner src = new Scanner(fin);
// Read the ingridient from text file.
while (src.hasNext()) {
if (src.hasNext()) {
i_one.setName(src.next());
System.out.println("Name: " +src.next());
} else
if(src.hasNextDouble()) {
i_one.setUnit_price(src.nextDouble());
System.out.println("Unit Price: " +src.nextDouble());
}
else if (src.hasNextInt()) {
i_one.setUnit(src.nextInt());
System.out.println("Unit: " +src.nextInt());
} else {
System.out.println("File format error.");
return;
}
db.add(i_one);
}
fin.close();
}
}
Her, Ingridient class has following code:
package com.collection;
public class Ingridient {
String name;
Double unit_price;
int unit;
public Ingridient() {
name = null;
unit_price = null;
unit = 0;
}
public void setName(String name) {
this.name = name;
}
public void setUnit_price(Double unit_price) {
this.unit_price = unit_price;
}
public void setUnit(int unit) {
this.unit = unit;
}
}
My problem is that my application can store only name in Ingridient object and it cannot store any value in unit and unit_price. Obtained output is:
I know i am mistaking somewhere but i cannot solve this issue. Any Suggestion?
This should do it:
public static void main(String[] args) throws IOException {
String content = "String name = carrot;\ndouble unit_price = 200;\nint unit = 10;";
try (Scanner sc = new Scanner(content)) {
sc.useDelimiter("(;*\n*.+ .+ = )|;");
List<Incredient> incredients = new ArrayList<>();
while (true) {
Incrediend incredient = new Incredient();
if (sc.hasNext()) {
String name = sc.next();
incredient.setName(name);
System.out.println("Name: " + name);
} else {
break;
}
if (sc.hasNextDouble()) {
double unitPrice = sc.nextDouble();
incredient.setUnit_price(unitPrice);
System.out.println("Unit Price: " + unitPrice);
} else {
break;
}
if (sc.hasNextInt()) {
int unit = sc.nextInt();
incredient.setUnit(unit);
System.out.println("Unit: " + unit);
} else {
break;
}
incredients.add(incredient);
}
} catch (Exception e) {
e.printStackTrace();
}
}
This works because of the delimiter I've used (;*\n*.+ .+ = )|;.
This pice of regex just removes all the parts of the text file that you're not interested in saving.
There are a couple of problems with your approach, for example this:
i_one.setName(src.next());
System.out.println("Name: " +src.next());
Here, you're reading 2 tokens from the scanner because there are 2 calls to next(), if you want to use the same token for multiple things you should create a new variable to store it in (ex: String name = sc.next()).
The default delimiter that the Scanner is using is a single space and because of that, in your code, hasNextDouble() and hasNextInt() will never be true, all the numbers in the text file end with ;.
I'm not sure what you're trying to do here, it is kind of unusual to parse java code from a text file. If you can change the format of the text file, you should chose one that is easier to parse (CSV for example).
src.hasNext() selects every line you've got in your file, so it will never jump into one of the if/else conditions
I would also recommend using json as an input format ;)
while (src.hasNext()) {
if (src.hasNext()) {
it always true and another else {} sections inacessible
The structure of your text file is not very good for parsing the desired values.
If you're able to you should change it to something like
carrot,200,10
thus having all values of your desired ingredient at one line. Splitting this line at "," will give you all the values you need to instantiate your objects.
If you're not able to change the text format (because it's part of the task), you should read whole lines of the text file and interpret triples of them to get your objects. So you also can be sure that all the values you need are there.
your first if condition is wrong to get the output you need...
if (src.hasNext())
this condition will always satisfy as there will be a next object and your following else if conditions never execute. this can be seen in the output always printing the data from the sysout in the first if condition.
i have changed the code to work with startsWith method given by the string class. Hope it helps...
NOTE: before you parse it make sure you remove out those special characters if any. (Semi -colons etc.)
while (src.hasNext()) {
String input = src.next();
if (input.startsWith("name")) {
i_one.setName(input);
System.out.println("Name: " + input);
} else if (input.startsWith("unit_price")) {
i_one.setUnit_price(Double.parseDouble(input));
System.out.println("Unit Price: " + input);
} else if (input.startsWith("unit")) {
i_one.setUnit(Integer.parseInt(input));
System.out.println("Unit : " + input);
} else {
System.out.println("File format error.");
return;
}
db.add(i_one);
}
If the structure of the text file is always the same you can use the contains method of the string class. Example:
public class FileReaderApp {
public static void main(String[] args) throws FileNotFoundException, IOException {
Ingridient i_one = new Ingridient();
ArrayList<Ingridient> db = new ArrayList<Ingridient>();
try(BufferedReader br = new BufferedReader(new FileReader("/home/yati/Desktop/test.txt"))) {
String line ;
while ((line = br.readLine())!=null) {
String [] splited;
if(line.contains("String name")){
splited= line.split(" ");
i_one.setName(splited[splited.length-1].replace(";", ""));
System.out.println(i_one.name);
}
else if(line.contains("double unit_price")){
splited= line.split(" ");
i_one.setUnit_price(Double.parseDouble(splited[splited.length-1].replace(";", "")));
System.out.println(i_one.unit_price);
}
else if(line.contains("int unit")){
splited= line.split(" ");
i_one.setUnit(Integer.parseInt(splited[splited.length-1].replace(";", "")));
System.out.println(i_one.unit);
}
}
}
db.add(i_one);
}
}

How do I resolve these exceptions?

To be fair, I'm not getting these exceptions but merely trying to find a away to cover these exceptions. The exceptions are NosuchElementException and NumberFormatException.
Note: This programs works perfectly because the txt file is fine. However, introduce anything that is not a number and it will fail.
Here is the main class where the problem could occur:
BankReader.java
package bankreader;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class BankReader
{
public static void main(String[] args)
{
BankReader reader = new BankReader();
Scanner scan = new Scanner(System.in);
String fileName = "";
boolean finished = false;
while(!finished)
{
try
{
System.out.print("Enter the name of the file: ");
fileName = scan.nextLine();
scan = reader.checkFile(fileName, scan);
reader.readFile(scan);
finished = true;
}
catch(IOException ex)
{
System.out.print("\nThis file does not exist or had");
System.out.println(" characters that were not numbers. Please enter a different file.\n");
}
}
scan.close();
}
public Scanner checkFile(String fileName, Scanner scan) throws IOException
{
File file = new File(fileName);
scan = new Scanner(file);
return scan;
}
public void readFile(Scanner scan)
{
String accountNumber = "";
double accountBalance = -1;
Bank bank = new Bank();
while(scan.hasNext())
{
accountNumber = scan.next();
accountBalance = Double.parseDouble(scan.next());
BankAccount bankAccount = new BankAccount(accountNumber, accountBalance);
bank.addAccount(bankAccount);
}
if (bank.numberOfAccounts() > 0)
{
BankAccount maxBalance = bank.getHighestBalance();
System.out.println(maxBalance.getAccountNumber() + ": " + "$" + maxBalance.getBalance());
}
else
System.out.println("\nThe file had no accounts to compare.");
}
}
Here is the txt file I'm working with:
346583155444415 10000.50
379611594300656 5000.37
378237817391487 7500.15
378188243444731 2500.89
374722872163487 25000.10
374479622218034 15000.59
342947150643707 100000.77
So even though this is my own txt file, what if I was accessing a text file that a character that wasn't a number or had an account number but no balance and vice versa. I would like to know how I can deal with these exceptions.
What I've tried:
I've tried to do scan.nextLine() to move away from the exception but it just introduces another exception.
I've also tried to use a method that uses regex to check if the string is a number. The problem is I'm using a variable that is not a string and I would rather not create more checks.
It seems to me that no more what I do, I can't recover my scanner after an exception has occurred.
before parsing you can test if it is a double with scan.hasNextDouble and parse or read the number only then else you set default value and move next by reading the incorrect value and dont do anything with it

How to search a word in file in java

I am trying to search a string in a file in java and this is what, I tried . In the below program I am getting output as No Data Found and I am sure that the file has the word which I am searching
import java.io.*;
import java.util.Scanner;
public class readfile {
static String[] list;
static String sear = "CREATE";
public void search() {
Scanner scannedFile = new Scanner("file.txt");
while (scannedFile.hasNext()) {
String search = scannedFile.next();
System.out.println("SEARCH CONTENT:"+search);
if (search.equalsIgnoreCase(sear)) {
System.out.println("Found: " +search);
}
else {
System.out.println("No data found.");
}
}
}
public static void main (String [] args) throws IOException {
readfile read = new readfile();
read.search();
}
}
Don't do:
search.equalsIgnoreCase(sear)
Try:
search.toUpperCase().contains(sear)
I think the search is the whole String of the File, so you never would become true with equals.
Use nextLine() instead of next() and then use split. Like this :
What's the difference between next() and nextLine() methods from Scanner class?
Difference :
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.
Use following code :
String search = scannedFile.nextLine();
String[] pieces = data.split("\\s+");
for(int i=0; i<pieces.length(); i++)
{
if(pieces[i].equalsIgnoreCase(sear))
{
System.out.println("Found: " +search);
}
else
{
System.out.println("No data found.");
}
}
Ok, here is my understanding of your program.
You search in the file file.txt the word CREATE.
To do so, you read each word in the file and if it is CREATE you print Found create.
The issue here is that for every word in the file, if it isn't CREATE you print No data found.
Instead you should wait for the end of the file and then if you haven't found it you will print the error message.
Try this :
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class readfile {
static String[] list;
static String sear = "CREATE";
public void search() throws IOException {
List<String> saveAllLinesForRewriting = new ArrayList<String>();
// Need to read file line by line
BufferedReader bufferedReader = new BufferedReader(new FileReader("file.txt"));
String saveLine;
while ((saveLine = bufferedReader.readLine()) != null) {
saveAllLinesForRewriting.add(saveLine);
}
bufferedReader.close();
// Check if your word exists
if (saveAllLinesForRewriting.toString().contains(sear)) {
System.out.println("Found: " + sear);
} else {
System.out.println("No data found.");
}
}
public static void main(String[] args) throws IOException {
readfile read = new readfile();
read.search();
}
}
Instead of reading file using scanner, first create a file resource to read by adding the below line
File file = new File("Full Path of file location");
before
Scannner scannedfile = new Scanner("file.txt");
and change the above line to
Scanner scannedfile = new Scanner(file);
rest your code is working fine.
The problem is that the scanner is scanning the String "file.txt" and not the file.
To fix this you have to do what amit28 says. Your finally code is as follows
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class readfile {
static String[] list;
static String sear = "CREATE";
public void search() {
File f = new File("file.txt");
Scanner scannedFile;
try {
scannedFile = new Scanner(f);
while (scannedFile.hasNext()) {
String search = scannedFile.next();
System.out.println("SEARCH CONTENT:"+search);
if (search.equalsIgnoreCase(sear)) {
System.out.println("Found: " +search);
}
else {
System.out.println("No data found.");
}
}
} catch (FileNotFoundException e) {
// FIXME Auto-generated catch block
e.printStackTrace();
}
}
public static void main (String [] args) throws IOException {
readfile read = new readfile();
read.search();
}
}

Searching through a text file java

So I am trying to search through a text file and if the user input is found, it returns the entire sentence including white spaces.But apparently I only get the first string and nothing pass the first string in the sentence. For example if i have a text file called "data.txt" and the contents in the first line is " I am a legend". after user enters "I am a legend" the output after the file is searched is "I". Any help would be appreciated.
public static void Findstr() { // This function searches the text for the string
File file = new File("data.txt");
Scanner kb = new Scanner(System.in);
System.out.println(" enter the content you looking for");
String name = kb.next();
Scanner scanner;
try {
scanner = new Scanner(file).useDelimiter( ",");
while (scanner.hasNext()) {
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(name)) {
// a match!
System.out.println("I found " + name);
break;
}
}
} catch (IOException e) {
System.out.println(" cannot write to file " + file.toString());
}
package com.example;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileSearch {
public void parseFile(String fileName,String searchStr) throws FileNotFoundException{
Scanner scan = new Scanner(new File(fileName));
while(scan.hasNext()){
String line = scan.nextLine().toLowerCase().toString();
if(line.contains(searchStr)){
System.out.println(line);
}
}
}
public static void main(String[] args) throws FileNotFoundException{
FileSearch fileSearch = new FileSearch();
fileSearch.parseFile("src/main/resources/test.txt", "am");
}
}
test.txt contains:
I am a legend
Hello World
I am Ironman
Output:
i am a legend
i am ironman
The above code does case insensitive search. You should use nextLine() to get the complete line. next() breaks on whitespaces.
Reference:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next()
Scanner.next(); returns the next caracter instead use Scanner.readLine();
Edit:
Belive Scanners use .nextLine(); not .readLine();
When you are scanning your input..
Scanner kb = new Scanner(System.in);
System.out.println(" enter the content you looking for");
String name = kb.next();
You are accepting only one token. You should accept whole line to be searched as your token using kb.nextLine()

while loop won't read file, or print out line java

I have a with the hentAntall method in my code below. It's supposed to find the search word inside a txt file. I don't get any sort of error. It just won't print out any of the two possible lines.
This method has to access a constructor first to get the search word, and then it has to find that search word in the txt file and add to count. The constructor gets the search word from another class. Like this new lolz("searchword").hentAntall();
(I apologize for the stupid naming in this program, but it's just a copy of one of my programs, and I'm just trying to correct it without screwing up the original.)
import java.io.File;
import java.util.Scanner;
public class lolz {
private String sokeord=null;
private int antall = 0;
// Constructor
lolz(String searchword) throws Exception{
this.sokeord = searchword;
}
//toString method, to print in the same format.
#Override
public String toString(){
return "\nSokeordet er: " + sokeord+ "\n";
}
// Gets the ammount of the searchword
public int hentAntall() throws Exception{
File file = new File("Hvorfor.txt");
Scanner readfile = new Scanner(file);
while (readfile.hasNextLine()){
String nextline = readfile.nextLine();
if (nextline.equalsIgnoreCase(sokeord)) {
antall ++;
System.out.println("Antallet av:" + sokeord + "er " + antall);
}
else {System.out.println("Error no such search word in the given text");}
}
return antall;
}
// void methode to increase the count of a searcheword.
void oekAntall() {
antall++;
}
}
This is the other class that calls on this method, and also give information to the constructor.
public class Main {
public static void main(String[] args) throws Exception {
new lolz("fungerer").hentAntall();
}}
Also tried some of the suggestions and they did not work, I only get a the message Process finished with exit code 0.
Your Issue:
You are trying to compare a Scanner variable with a String Variable?!!!
Explanation:
you try to compare content of Scanner which is
java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match
valid=true][need input=false][source
closed=false][skipped=false][group separator=\,][decimal
separator=.][positive prefix=][negative prefix=\Q-\E][positive
suffix=][negative suffix=][NaN string=\Q�\E][infinity string=\Q∞\E]
with content of a String variable.
You do not read the each line with following
if (readfile.equals(sokeord)) {
You Should have
if (readfile.nextLine().equals(sokeord)) {
Instead of:
readfile.equals(sokeord)
Which is comparing an instance of type Scanner with a String (never going to be true). You need to read a line and compare that.
String line = readfile.nextLine();
if(line.equals(sokeord)){
Add a main method to your class:
public static void main(String[] args)
{
hentAntall();
}
You will have to make hentAntall() static or create an instance of lolz class and call it that way.
Also change:
while (readfile.hasNext()){
if (readfile.nextLine().contains(sokeord)) {
You need to actually read the input and then check if sokeord exists in the line or not.
Your hentAntall method should be like this:
public int hentAntall() throws Exception {
File file = new File("Hvorfor.txt");
Scanner readfile = new Scanner(file);
while (readfile.hasNextLine()) {
String word = readfile.next();
if (word.contains(sokeord)) {
antall++;
System.out.println("Antallet av:" + sokeord + "er " + antall);
} else {
System.out
.println("Error no such search word in the given text: ");
}
}
readfile.close();
return antall;
}
Don't forget to close the Scanner resource to avoid leaks.

Categories

Resources