I have written code of dictionary in java in which i read data from file named newFile.txt .In file world is placed on one line and its meaning is placed on nextline. User enters a world. If word is found in file it shows its meaning placed on next line and if word is not found it shows similar words (substrings).
"While searching word it should not search meaning."
import java.io.*;
import java.util.*;
public class Notepad {
public static void main(String []args) throws IOException{
BufferedReader in = null;
Scanner input = new Scanner(System.in);
String str;
boolean notfound = false;
char again = 'a';
try{
do{
notfound = false;
System.out.println("Enter word :");
str = input.next();
File f = new File("D:\\newFile.txt");
in = new BufferedReader(new FileReader(f));
String s;
while((s = in.readLine()) != null){
int x = s.indexOf(str);
if(x != -1){
int lens = s.length();
String sub = s.substring(x);
int lensub = str.length();
if(lens == lensub){
System.out.println((in.readLine()));
break;
}
else{
System.out.println(sub) ;
notfound = true;
}
}
s = in.readLine();
}
if(!notfound){
System.out.println("Try another world?(y/n):");
again = input.next().trim().charAt(0);
again = Character.toLowerCase(again);
}
}
while(notfound || again == 'y');
System.out.println("terminated!");
}
finally{
if(in != null){
in.close();
}
}
}
}
when i enters a substring of a word it searches meaning as well and then if a enter right word it does not show meaning
//This code is reading a file that is situated like this:
Hello - to greet
Circle - a round shape
//Then the code can be done like so, is this ok?
public static void main(String []args) throws IOException{
BufferedReader in = null;
Scanner input = new Scanner(System.in);
String str;
boolean notfound = false;
char again = 'a';
try{
do{
notfound = false;
System.out.println("Enter word :");
str = input.next();
File f = new File("/Folder/demo1.txt");
in = new BufferedReader(new FileReader(f));
String s;
while((s = in.readLine()) != null){
int x = s.indexOf(str);
// System.out.println("Index of dash:" + s.indexOf("-"));
// System.out.println("Index of Hello:" + x);
if(x != -1 && x<s.indexOf("-")){
String sub = s.substring(0,s.indexOf("-"));
System.out.println("Sub:" + sub);
System.out.println("Str:" + str);
if(sub.trim().equals(str.trim())){
System.out.println("Success:" +sub);
notfound = true;
break;
}
else{
System.out.println("Word is not present") ;
notfound = false;
break;
}
}
}
if(!notfound){
System.out.println("Try another word?(y/n):");
again = input.next().trim().charAt(0);
again = Character.toLowerCase(again);
}
}
while(notfound || again == 'y');
System.out.println("terminated!");
}
finally{
if(in != null){
in.close();
}
}
}
}
Related
The method is to return an array counting the number of lines, words and characters in a document. After running it through a test file I am still receiving some errors.
public static int[] wc(Reader in) throws IOException {
int data = in.read();
int charcounter = 0;
int linecounter = 0;
int wordcounter = 0;
boolean previouswhitespace = false;
while (data != -1){
if (((char) data == '\n')){
linecounter++;
}
if (!(Character.isWhitespace((char) data))){
charcounter++;
if ((previouswhitespace == true) || (wordcounter == 0)){
previouswhitespace = false;
wordcounter++;
}
}
else if ((Character.isWhitespace((char) data))){
previouswhitespace = true;
}
data = in.read();
}
int[] array = {linecounter, wordcounter, charcounter};
return array;
}
//To choose the file
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File file = chooser.getSelectedFile();
String file_path = file.getAbsolutePath();
char[] c;
String [] words;
int charCounter = 0 ,wordsCounter = 0, lineCounter = 0;
//try and catch for the BufferedReader
try{
String line;
BufferedReader reader = new BufferedReader(new FileReader(file_path));
while( (line = reader.readLine()) !=null){
c = line.replace(" ","").toCharArray();
charCounter+=c.length;
words = line.split(" ");
wordsCounter+=words.length;
lineCounter++;
}
}catch(Exception e){
// Handle the Exception
}
int array[] = {charCounter , wordsCounter, lineCounter};
Hope this is helping you!
I created a java file called Product.java. I also created a text file called Items.txt. Basically when the user enter the word using sequential search to search the data what they are looking from Items.txt. My main problem is when I enter 3 to display all the records or enter x to exit the program, it keeps on looping. But I don't how to resolve this problem. Can anyone solved this for me?
Items.txt
1000|Cream of Wheat|Normal Size|Breakfast|NTUC|5|3.00
1001|Ayam Brand|Small Size|Canned|NTUC|4|4.00
Product.java
import java.io.*;
import java.util.*;
public class Product {
public static void main(String[] args) {
ArrayList<Item> prdct = new ArrayList<Item>();
String inFile = "items.txt";
String line = "";
FileReader fr = null;
BufferedReader br = null;
StringTokenizer tokenizer;
int quantity;
String id, brandname, desc, category, supplier;
float price;
try{
fr = new FileReader(inFile);
br = new BufferedReader(fr);
line = br.readLine();
while(line!=null)
{
tokenizer = new StringTokenizer(line,"|");
id = tokenizer.nextToken();
brandname = tokenizer.nextToken();
desc = tokenizer.nextToken();
category = tokenizer.nextToken();
supplier = tokenizer.nextToken();
quantity = Integer.parseInt(tokenizer.nextToken());
price = Float.parseFloat(tokenizer.nextToken());
Item itm = new Item(id,brandname,desc,category,supplier,quantity,price);
prdct.add(itm);
line = br.readLine();
}
br.close();
}
catch(FileNotFoundException e){
System.out.println("The file " + inFile + " was not found.");
}
catch(IOException e){
System.out.println("Reading error!");
}
finally
{
if (fr!=null){
try
{
fr.close();
}
catch(IOException e)
{
System.out.println("Error closing file!");
}
}
}
String INPUT_PROMPT = "\nPlease enter 3 to display all records, 4 to insert record, 5 to remove old records " + "or enter 'x' to quit.";
System.out.println(INPUT_PROMPT);
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader (System.in));
line = reader.readLine();
while(reader != null)
{
for(int i=0; i<prdct.size(); i++)
{
if(prdct.get(i).id.contains(line) || prdct.get(i).brandname.contains(line) || prdct.get(i).desc.contains(line)
|| prdct.get(i).category.contains(line) || prdct.get(i).supplier.contains(line))
{
System.out.println(prdct.get(i));
}
System.out.println(INPUT_PROMPT);
line = reader.readLine();
}
}
while("3".equals(line))
{
for(int i=0; i<prdct.size(); i++)
{
System.out.println(prdct.get(i));
}
System.out.println(INPUT_PROMPT);
line = reader.readLine();
}
while(!line.equals("x"))
{
System.out.println(INPUT_PROMPT);
line=reader.readLine();
}
}
catch(Exception e){
System.out.println("Input Error!");
}
}
}
The problem is with this loop:
while(reader != null)
{
for(int i=0; i<prdct.size(); i++)
{
if(prdct.get(i).id.contains(line) || prdct.get(i).brandname.contains(line) || prdct.get(i).desc.contains(line)
|| prdct.get(i).category.contains(line) || prdct.get(i).supplier.contains(line))
{
System.out.println(prdct.get(i));
}
System.out.println(INPUT_PROMPT);
line = reader.readLine();
}
}
It keeps on looping while reader is not null and it will never be. You might want to try checking something else that suits your problem better, maybe:
While(!line.equals("3"))
While(!line.equals("x"))
While(line != null)
Otherwise, even if there is an 'x', '3' or simply nothing, still (reader != null) and therefore the loop is infinite.
I suspect that the newline character is what causes the comparison to fail.
Instead of checking if:
"3".equals(line)
Try:
"3".equals(line.trim())
Same applies to the following comparison.
Try changing this..
line = reader.readLine();
while(reader != null)
{
to this..
line = reader.readLine();
while(line != null)
{
You are looping on the reader being not null, which it always will be.
you have to define these functions:
public void showAllRecords() {
// show all record here
}
public void insertRecord() {
// insert record here
}
public void removeRecord() {
// insert record here
}
public void exit() {
// insert record here
}
then
do{
System.out.println(INPUT_PROMPT);
switch(line)
{
case "3":
showAllRecords();
break;
case "4":
insertRecord();
break;
case "5":
removeRecord();
}
}while(!line.equals('x'));
I'm using two BufferedReaders, one to read a document, and another one to get the input of the String to search from user, heeding the advice here. Here's the code so far:
import java.io.*;
import java.util.*;
public class Ejercicio6 {
public static void main(String[] args) {
Character answer = 'S';
boolean exit = false;
String name;
String line;
Scanner sc = new Scanner (System.in);
boolean found = false;
File file = new File ("/test/Ejercicio6/nombres.txt");
try {
do{
exit = false;
FileInputStream fis = new FileInputStream(file);
BufferedReader readFile = new BufferedReader(new FileReader(file));
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Search a name, I'll tell you if it's found:");
name = userInput.readLine();
while ((line = readFile.readLine()) != null && found == false){
if(line.equals(name)) {
found = true;
}else
found = false;
}
if (found == true)
System.out.println("I have found the name " +name+ " in the file " +file.getName());
if (found == false)
System.out.println("Can't find the name");
fis.getChannel().position(0);
fileRead = new BufferedReader(new InputStreamReader(fis));
System.out.println("Do you want to try again? (Y/N)");
answer = sc.nextLine().toUpperCase().charAt(0);
if (answer =='S'){
exit = false;
}else
exit = true;
fileRead.close();
}while (exit == false);
// }catch (FileNotFoundException e) {
// e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
}
There are 3 names on the document, but I always get the "name found" print, regardless of the input matching or not. I'm trying to figure out how does the getChannel() and the buffer clearing, as told here, but I'm having lots of trouble. What I'm missing?
You need to unset your flag found to false again after you're printing for matched or unmatched name.
Just add
found = false;
before
fis.getChannel().position(0);
if (line.equals(name)) {
found = true;
} else
found = false;
can simplied:
found = line.equals(name);
Just move boolean found = false; right before while loop
package com.company;
import java.io.*;
import java.util.Scanner;
public class Ejercicio6 {
public static void main(String[] args) {
Character answer;
boolean exit;
String name;
String line;
Scanner sc = new Scanner(System.in);
File file = new File("file.txt");
try {
do {
FileInputStream fis = new FileInputStream(file);
BufferedReader readFile = new BufferedReader(new FileReader(file));
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Search a name, I'll tell you if it's found:");
name = userInput.readLine();
boolean found = false;
while ((line = readFile.readLine()) != null && found == false) {
found = line.equals(name);
}
if (found == true)
System.out.println("I have found the name " + name + " in the file " + file.getName());
if (found == false)
System.out.println("Can't find the name");
fis.getChannel().position(0);
BufferedReader fileRead = new BufferedReader(new InputStreamReader(fis));
System.out.println("Do you want to try again? (Y/N)");
answer = sc.nextLine().toUpperCase().charAt(0);
exit = answer != 'S';
fileRead.close();
} while (exit == false);
// }catch (FileNotFoundException e) {
// e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 7 years ago.
EDIT: While this issue has been marked as a duplicate, the other issue is different to my situation; it seems as though the program is ignoring this line:
decision = scan.nextInt();
I'm having some trouble with my scanner. I have a program that runs off a simple menu system.
The program works, but whenever it goes back to repeating the program again (I made the program have the ability to repeat by putting it in a while loop) it throws this error:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:919)
at java.util.Scanner.next(Scanner.java:1542)
at java.util.Scanner.nextInt(Scanner.java:2172)
at java.util.Scanner.nextInt(Scanner.java:2131)
at GuardSearch.Menu(GuardSearch.java:29)
at GuardSearch.main(GuardSearch.java:8)
The program all works on the first run through the menu and its actions, but then when the call of the if statement is completed and the program returns to the while loop, it throws this exception. What am I missing?
I can post all the classes of the program if needed, however I believe my problem is within the following class:
import java.util.Scanner;
import java.lang.*;
public class GuardSearch {
public static void main(String[] args) {
Menu();
}
public static void Menu(){
Scanner scan = new Scanner(System.in);
boolean leave = false;
while(leave!=true){
final String ANSI_CLS = "\u001b[2J";
final String ANSI_HOME = "\u001b[H";
System.out.print(ANSI_CLS + ANSI_HOME);
System.out.flush();
int decision = 0;
System.out.println("Welcome to GuardSearch, our little slice of Google.\n");
while ((decision != 1) || (decision != 2)){
System.out.println("Please enter the number of what you would like to do from the following list:");
System.out.println("1. Submit knowledge.");
System.out.println("2. Search.");
System.out.println("3. Quit.");
decision = scan.nextInt();
if (decision == 1) {
Submit submit = new Submit();
submit.takeinfo();
break;
}
else if (decision == 2){
Search search = new Search();
search.takekeywords();
break;
}
else if (decision == 3){
leave = true;
break;
}
}
}
scan.close();
}
}
Thanks in advance. I have researched this issue and found no occurrences relevant to my exact issue.
EDIT: Here is my Submit and Search class as requested:
import java.io.*;
import java.util.Scanner;
public class Submit {
public static void takeinfo() {
final String ANSI_CLS = "\u001b[2J";
final String ANSI_HOME = "\u001b[H";
System.out.print(ANSI_CLS + ANSI_HOME);
System.out.flush();
System.out.println("Submit your knowledge to the system.\n");
Scanner sc = new Scanner(System.in);
int decision = 0;
while ((decision != 1) || (decision != 2)){
System.out.println("1. Change an existing article.");
System.out.println("2. Create a new article.");
System.out.println("3. Delete an article.");
System.out.println("4. Back.");
decision = sc.nextInt();
if (decision == 1) {
ChangeArticle chngArt = new ChangeArticle();
chngArt.takeinfo();
break;
}
else if (decision == 2){
CreateArticle createArt = new CreateArticle();
createArt.title();
break;
}
else if (decision == 3){
DeleteArticle deleteArt = new DeleteArticle();
deleteArt.takeinfo();
break;
}
else if (decision == 4){
GuardSearch gs = new GuardSearch();
gs.Menu();
break;
}
else {
System.out.println("Please enter a valid number.\n");
}
}
sc.close();
}
}
And the Search class:
import java.util.*;
import java.io.*;
public class Search {
Scanner sc = new Scanner(System.in);
public void takekeywords() {
final String ANSI_CLS = "\u001b[2J";
final String ANSI_HOME = "\u001b[H";
System.out.print(ANSI_CLS + ANSI_HOME);
System.out.flush();
System.out.println("Search the system.\n");
boolean fin = false;
int dec;
while (fin != true){
System.out.println("Please select which search type you want:\n");
System.out.println("1. Keywords.");
System.out.println("2. Category listing.");
System.out.println("3. Back\n");
dec = sc.nextInt();
if (dec == 1) {
// Do a keyword thing
fin = true;
}
else if (dec == 2) {
// Do a category thing
searchCategories();
fin = true;
}
else if (dec == 3) {
GuardSearch gs = new GuardSearch();
gs.Menu();
break;
}
}
}
public void searchCategories(){
// Create an empty list of subcategories, that will be added to when the user wants to add sub categories
LinkedList<Category> newSubCategories = new LinkedList<Category>();
// Create a list of .txt's relevant to the category
LinkedList<String> relevantArticles = new LinkedList<String>();
relevantArticles.add("example.txt");
LinkedList<String> dirListing = new LinkedList<String>();
//System.out.println("Please select your category:\n");
String s = "Example Category";
// Create the first category, passing in its name, an empty list of subCategories (which are of type Category), and a list of .txt's relevant to the category
Category firstCategory = new Category(s, newSubCategories, relevantArticles);
File wd = new File("/bin");
Process proc = null;
try {
proc = Runtime.getRuntime().exec("/bin/bash", null, wd);
}
catch (IOException e) {
e.printStackTrace();
}
if (proc != null) {
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
out.println("cd /var/tmp/cholland/GuardSearch/");
out.println("ls *.art");
out.println("exit");
String line;
System.out.println();
try {
int x = 1;
while ((line = in.readLine()) != null) {
System.out.println(x + ") " + line);
dirListing.add(line);
x++;
}
System.out.println("Please select the article you want:\n");
int dec = sc.nextInt();
//System.out.println(Arrays.toString(dirListing.toArray()));
System.out.println(dirListing.size());
try {
for (int y=1; y<=dirListing.size(); y++) {
if (y == dec){
boolean fin = false;
while (fin != true){
System.out.println("You chose: " + (dirListing.get(boundIndex(y))) + ". Opening file...");
System.out.println("===========================================================\n");
String text;
String filepath = ("/var/tmp/cholland/GuardSearch/" + (dirListing.get(boundIndex(y))));
BufferedReader br = null;
StringBuffer contents = new StringBuffer();
try {
br = new BufferedReader(new FileReader(filepath));
text = null;
while ((text = br.readLine()) != null) {
contents.append(text).append(System.getProperty("line.separator"));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
text = (contents.toString());
System.out.println(text);
System.out.println("\n===========================================================\n");
fin = true;
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
proc.waitFor();
out.close();
in.close();
proc.destroy();
}
catch (Exception e) {
e.printStackTrace();
}
}
sc.close();
}
public int boundIndex(int x){
if (x != 0){
return (x - 1);
}
else {
return 0;
}
}
}
I think the problem is here decision = scan.nextInt();
NoSuchElementException will be thrown if no more tokens are available. This is caused by invoking nextInt() without checking if there's any integer available. You can hasNextInt() to check if any more tokens are available.
Something like:
if(scan.hasNextInt() )
decision = scan.nextInt(); // if there is another number
else
decision = 0; // nothing added in the input
The cause of the error is that you are closing the scanner at the end of searchCategories.
I keep getting this error
java.util.NoSuchElementException No line found
when I use this method
public boolean hasMoreCommands() {
if (input.hasNextLine()) {
return true;
} else {
//input.close();
return false;
}
}
public void advance() {
String str;
if(hasMoreCommands() == true){
do {
str = input.nextLine().trim();
// Strip out any comments
if (str.contains("//")) {
str = (str.substring(0, str.indexOf("//"))).trim();
}
} while (str.startsWith("//") || str.isEmpty() || hasMoreCommands());
command = str;
}
}
I have main code here:
public class Ptest
{
public Ptest(String fileName)
{
String line = null;
String nName = fileName.replace(".vm", ".asm");
Parser p = new Parser();
try{
File neF = new File(nName);
if(!neF.exists()){
neF.createNewFile();
}
File tempFile = new File("temp.txt");
if(!tempFile.exists()){
tempFile.createNewFile();
}
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter(nName);
BufferedWriter bw = new BufferedWriter(fw);
FileWriter writR = new FileWriter(tempFile);
BufferedWriter buffR = new BufferedWriter(writR);
while((line = br.readLine()) != null) {
buffR.write(line+ "\n");
//System.out.println(line);
}
buffR.flush();
buffR.close();
p.insertTitle(tempFile);
String ctype = p.commandType();
int len = ctype.length();
int spaces = 13 - len;
String sp = " ";
String asp = " ";
String a1 = null;
int a2;
int alen;
boolean t = false;
while(p.hasMoreCommands()){
for(int i= 0; i < spaces; i++){
sp += " ";
}
t = p.hasMoreCommands();
a1 = p.arg1();
alen = (10 - a1.length());
for(int i= 0; i < alen; i++){
asp += " ";
}
//a2 = p.arg2();
if (ctype == "C_PUSH" || ctype == "C_POP" || ctype == "C_FUNCTION" || ctype == "C_CALL") {
a2 = p.arg2();
bw.write(ctype + sp + a1 + asp + a2);
}
else {
bw.write(ctype + sp + a1);
}
p.advance();
ctype = p.commandType();
len = ctype.length();
spaces = 13 - len;
}
bw.flush();
bw.close();
}
catch(FileNotFoundException ex){
System.out.println("File not found!");
}
catch(IOException ex){
System.out.println("Error reading file '" + fileName + "'");
}
}
}
I went through debugger and it literally goes the entire file then gives me an error when its finished.
Like #hfontanez I think your problem is in this code:
if(hasMoreCommands() == true){
do {
str = input.nextLine().trim();
// Strip out any comments
if (str.contains("//")) {
str = (str.substring(0, str.indexOf("//"))).trim();
}
} while (str.startsWith("//") || str.isEmpty() || hasMoreCommands());
command = str;
}
However, my solution is to change the while clause to while (str.isEmpty() && hasMoreCommands());
I'm assuming that "advance" ought to return the next non-comment / blank line.
If the string from the previous pass is empty (after stripping any comment) it will go round the loop again provided that wasn't the last line. But, if that was the last line or str still has something in it, then it will exit the loop. Comments should have been stripped so don't need tested for in the while.
I think if you just test for hasNextLine within the loop then it will never exit the loop if the last line was comment / blank.
My guess is that your problem is here:
if(hasMoreCommands() == true){
do {
str = input.nextLine().trim();
// Strip out any comments
if (str.contains("//")) {
str = (str.substring(0, str.indexOf("//"))).trim();
}
} while (str.startsWith("//") || str.isEmpty() || hasMoreCommands());
command = str;
}
The exception you encountered (NoSuchElementException) typically occurs when someone tries to iterate though something (String tokens, a map, etc) without checking first if there are any more elements to get. The first time the code above is executed, it checks to see if it has more commands, THEN it gets in a loop. The first time it should work fine, however, if the test done by the while() succeeds, the next iteration will blow up when it tries to do input.nextLine(). You have to check is there is a next line to be got before calling this method. Surround this line with an if(input.hasNextLine()) and I think you should be fine.