public class Main {
public static void main(String[] args)
{
int ch = 0;
do
{
Scanner in = new Scanner(System.in);
String s;
System.out.println("Enter the part number");
s=in.nextLine();
try{
BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\Ankit\\Documents\\NetBeansProjects\\tcs_1\\number.txt"));
BufferedReader Br = new BufferedReader(new FileReader("C:\\Users\\Ankit\\Documents\\NetBeansProjects\\tcs_1\\number1.txt"));
String strLine;
int flag=0;
while ((strLine = br.readLine()) != null)
{
if(strLine.equals(s))
{
flag=1;
System.out.println ("Part Number exists in 1");
break;
}
else
{
flag=0;
System.out.println ("Part Number doesnot exist in 1");
break;
}
}
if(flag==0)
{
while ((strLine = Br.readLine()) != null)
{
if(strLine.equals(s))
{
System.out.println ("Part Number exists in 2");
break;
}
else
{
System.out.println("File does not exist in 2");
break;
}
}
}
System.out.println ("Do you want to continue-Press1 for yes and 2 for no");
ch= in.nextInt();
br.close();
Br.close();
}
catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
}
}
while(ch==1);
}
}
this is the program that I made to search a user given string from 2 diff text files. Its working fine but only searching the first line.
eg.: If a file has
1000
1001
1002
it wll only search 1000. How do I go to next line and keep on using the .equals() method?
You should use Scanner not BufferedReader as it's a more recent class
and I feel does a nicer job with this task. Especially since you have
already used Scanner elsewhere in your code and thus imported it.
Below is a scanner that will read all the lines in a file while there
is a next one to read.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class JavaApplication32
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
Scanner scanner1 = null;
Scanner scanner2 = null;
String partCheck;
String repeatLoop;
boolean isInOne;
boolean isInTwo;
File file1 = new File("data1.txt");
File file2 = new File("data2.txt");
try
{
scanner1 = new Scanner(file1);
scanner2 = new Scanner(file2);
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
do
{
isInOne = false;
isInTwo = false;
System.out.println("Enter the part number");
partCheck = keyboard.nextLine();
while (scanner1.hasNextLine() && !isInOne)
{
String line = scanner1.nextLine();
if(line.equals(partCheck))
{
System.out.println("Part Number exists in 1");
isInOne = true;
}
}
if(!isInOne)
{
System.out.println("Part Number does not exist in 1");
}
while(scanner2.hasNextLine() && !isInOne && !isInTwo)
{
String line = scanner2.nextLine();
if(line.equals(partCheck))
{
System.out.println("Part Number exists in 2");
isInTwo = true;
}
}
if(!isInTwo)
{
System.out.println("Part Number does not exist in 2");
}
System.out.println("Do you want to continue? (Y/N)");
repeatLoop = keyboard.nextLine();
} while(repeatLoop.equalsIgnoreCase("y"));
scanner1.close();
scanner2.close();
}
}
Example Text File data1.txt:
Test1
Test2
Test3
Test4
Example Test File data2.txt
Check1
Check2
Check3
Check4
Example stdout when code is run with these datafiles:
run:
Enter the part number
Test1
Part Number exists in 1
Part Number does not exist in 2
Do you want to continue? (Y/N)
y
Enter the part number
Check1
Part Number does not exist in 1
Part Number exists in 2
Do you want to continue? (Y/N)
n
BUILD SUCCESSFUL (total time: 19 seconds)
You also shouldn't put all of your read in information in a loop. By
putting do at the top you effectively keep creating a new set of
BufferedReaders and naming them the same thing and telling to do the
same thing and then telling them to break after the first hit. If you
did actually get rid of the break you'd have even more problems since
all of this other stuff is in the loop where it shouldn't be.
Since you have used
break;
in while loop it will exit from the loop after check first line. Try removing break; if you want to read all lines.
Related
I'm confused while using an Java program I created.
public static void main(String[] args) {
Scanner scanner1 = new Scanner(System.in);
int input1 = 0;
boolean Input1Real = false;
System.out.print("Your first input integer? ");
while (!Input1Real) {
String line = scanner1.nextLine();
try {
input1 = Integer.parseInt(line);
Input1Real = true;
}
catch (NumberFormatException e) {
System.out.println("Use an integer! Try again!");
System.out.print("Your first input integer? ");
}
}
System.out.println("Your first input is " + input1);
}
Initially, when a user Ctrl+D during the input, it will promptly end the program and display an error in the form of this,
Your first input integer? ^D
Class transformation time: 0.0073103s for 244 classes or 2.9960245901639343E-5s per class
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651);
at Playground.Test1.main(Test1.java:13)
Doing a bit of research I note that Ctrl+D terminates the input of sort. Therefore, I tried add few more lines to my codes to prevent the error from appearing again and instead printing a simple "Console has been terminated successfully!" and as far as my skills can go.
public static void main(String[] args) {
Scanner scanner1 = new Scanner(System.in);
int input1 = 0;
boolean Input1Real = false;
System.out.print("Your first input integer? ");
while (!Input1Real) {
String line = scanner1.nextLine();
try {
try {
input1 = Integer.parseInt(line);
Input1Real = true;
}
catch (NumberFormatException e) {
System.out.println("Use an integer! Try again!");
System.out.print("Your first input integer? ");
}
}
catch (NoSuchElementException e) {
System.out.println("Console has been terminated successfully!");
}
}
System.out.println("Your first input is " + input1);
}
In the end, I still got the same error.
Got it!, the code hasNext() will ensure that the error will not appear. This method is to check whether there is another line in the input of the scanner and to check if its filled or empty. I am also using null to check my statement after passing the loop so the program stops if the input value is still null while keeping the function of Ctrl+D.
public static void main(String[] args) {
Integer input1 = null;
System.out.println("Your first input integer? ");
Scanner scanner1 = new Scanner(System.in);
while(scanner1.hasNextLine()) {
String line = scanner1.nextLine();
try {
input1 = Integer.parseInt(line);
break;
}
catch (NumberFormatException e) {
System.out.println("Use an integer! Try again!");
System.out.println("Your first input integer? ");
}
}
if (input1 == null) {
System.out.println("Console has been terminated successfully!");
System.exit(0);
}
System.out.println(input1);
}
This solution is not prefect of course but I would appreciate if there were much simpler options.
I have looked around and couldn't find a solution. My code is supposed to take input from the user and stop when there input is blank. The code was simple at first but now I think I've over complicated it so sorry about it.
Scanner read = new Scanner(System.in);
System.out.println("Input words, enter blank to stop");
boolean working = true;
do {
if(working == false)
{
break;
}
String a = read.next();
if (a.equals("")) {
working = false;
System.out.println("no data");
} else {
Container.addWord(a);
}
} while (working == true);
Thanks.
Change next() to nextLine():
Scanner read = new Scanner(System.in);
System.out.println("Input words, enter blank to stop");
boolean working = true;
do {
if (working == false) {
break;
}
String a = read.nextLine();
if (a.isEmpty()) {
working = false;
System.out.println("no data");
} else {
Container.addWord(a);
}
} while (working == true);
Have you tried using String#trim().isEmpty()
It'll also consider strings like " " to be empty.
do {
String a = read.next();
if (a.trim().isEmpty()) {
working = false;
System.out.println("no data");
} else {
Container.addWord(a);
}
} while (working);
Here is a bit more elegant version
public static void main(String...args){
Scanner read = new Scanner(System.in);
String line = null;
System.out.println("Enter text:");
while(!(line=read.nextLine()).equals("")){
System.out.println("Your text:"+line);
System.out.println("Enter text or press enter to exit:");
}
System.out.println("Bye bye !!!");
}
I think your code could be replaced with the following:
Scanner read = new Scanner(System.in);
System.out.println("Input words, enter blank to stop");
while(true) {
if (!read.hasNext()) {
System.out.println("no data");
break;
}
String a = read.next();
Container.addWord(a);
}
I also removed the working variable and replaced it with a break statement.
If you change read.next() to read.nextLine() be sure to also update the read.hasNext() to read.hasNextLine().
yourString.isEmpty() || yourString.equals("")
You can simplify the whole thing:
Scanner read = new Scanner(System.in);
System.out.println("Input words, enter blank to stop");
boolean working = true;
do {
String keyEntered = read.nextLine();
if (keyEntered.isEmpty()) {
working = false;
System.out.println("No data");
} else {
System.out.println("You entered: " + keyEntered);
}
} while (working);
I have this application which prompts the user for a text file for input, from this text file, it contains strings of integers and text. And from there, it supposed to write to another text file, result.txt. Right now, as I'm still new to IO I am having problems with writing to the file although the file successfully created. The application stops right at the part after the user inputs the text file's name. So could you guys give me some help on that please? Thanks in advance!
import java.util.*;
import java.io.*;
class FileReadingExercise3 {
public static void main(String [] args)
{
Scanner userInput = new Scanner(System.in);
Scanner fileInput = null;
String a = null;
int sum = 0;
do
{
try
{
System.out.println("Please enter the name of a file or type QUIT to finish");
a = userInput.nextLine();
if(a.equals("QUIT"))
{
System.exit(0);
}
fileInput = new Scanner(new File(a));
}
catch(FileNotFoundException e)
{
System.out.println("Error " + a + " does not exist.");
}
}while(fileInput == null);
PrintWriter output = null;
try
{
output = new PrintWriter(new File("result.txt"));
}
catch(IOException g)
{
System.out.println("Error");
System.exit(0);
}
while(fileInput.hasNext())
{
if(fileInput.hasNextInt())
{
int num = fileInput.nextInt();
sum += num;
String str = Integer.toString(num);
output.println(str);
}
}
fileInput.close();
output.close();
}
}
It is stuck because you have to call the next() method after calling hasNext()so the pointer goes to next line of your input file.
Also you are not using sum so check if you need this variable.
Here is the code that works:
public static void main(String[] args) throws FileNotFoundException {
Scanner userInput = new Scanner(System.in);
Scanner fileInput = null;
String a = null;
int sum = 0;
do {
try {
System.out
.println("Please enter the name of a file or type QUIT to finish");
a = userInput.nextLine();
if (a.equals("QUIT")) {
System.exit(0);
}
fileInput = new Scanner(new File(a));
} catch (FileNotFoundException e) {
System.out.println("Error " + a + " does not exist.");
}
} while (fileInput == null);
PrintWriter output = null;
try {
output = new PrintWriter(new File("result.txt"));
} catch (IOException g) {
System.out.println("Error");
System.exit(0);
}
while (fileInput.hasNext()) {
if (fileInput.hasNextInt()) {
int num = fileInput.nextInt();
sum += num;
String str = Integer.toString(num);
output.println(str);
} else {
fileInput.next();
}
}
fileInput.close();
output.close();
}
}
Update:
As per java doc for Scanner.hasNext() method:
Returns true if this scanner has another token in its input. This
method may block while waiting for input to scan. The scanner does not
advance past any input.
So to go to the next position, you need to call the next() method, otherwise the Scanner will be at same position and the program gets stuck in infinite loop.
The bufferedreader I have used in my code seems to read only the first line of the code. Can some one help me solve the problem, I've been trying for a long time.
import java.util.Scanner;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.BufferedReader;
public class Task2Recipe {
private static String Ingredient;
private static String ServingNumber;
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
System.out.println("Hello. If you would like to write a new recipe, please type in 'write', if you would like to change and view a recipe, please type in 'read'");
String choice = user_input.next();
user_input.nextLine();
if (choice.equals("write")) {
write();
}
if (choice.equals("read")) {
read();
}
}
public static void write() {
try {
FileWriter Task2Recipe = new FileWriter("P:/Year 11/GCSE Computing/A453/Task 2/Recipe.txt");
BufferedWriter recipe = new BufferedWriter(Task2Recipe);
Scanner user_input = new Scanner(System.in);
System.out.println("Please enter the name of your recipe, if more than 1 word, seperate your words with a dash");
String RecipeName = user_input.next();
recipe.write("Name of recipe: " + RecipeName);
recipe.newLine();
System.out.println("Please enter the number of people your recipe serves");
ServingNumber = user_input.next();
recipe.write(ServingNumber);
recipe.newLine();
System.out.println("Please enter the name of your first ingredient, the quantity and units separated with a comma");
Ingredient = user_input.next();
recipe.write(Ingredient);
recipe.newLine();
System.out.println("Do you want to enter another ingredient? yes/no? Please type in either in lower case");
String choice2 = user_input.next();
user_input.nextLine();
while (choice2.equals("yes")) {
System.out.println("Please enter the name of your ingredient, the quantity and units separated with a comma");
Ingredient = user_input.nextLine();
recipe.write(Ingredient);
System.out.println("Do you want to enter another ingredient? yes/no? Please type in either in lower case");
choice2 = user_input.next();
user_input.nextLine();
}
recipe.close();
} catch (Exception e) {
System.out.println("A write error has occured");
}
}
public static void read() {
try {
Scanner user_input = new Scanner(System.in);
FileReader file = new FileReader("P:Year 11/GCSE Computing/A453/Task 2/Recipe.txt");
BufferedReader buffer = new BufferedReader(file);
System.out.println("Would you like to change the serving number of your recipe, type in 'yes' to proceed, type in 'no'");
String choice3 = user_input.next();
user_input.nextLine();
while (choice3.equals("yes")) {
String line;
System.out.println("Please enter the new serving number");
int NewServingNumber = user_input.nextInt();
int counter = 0;
while ((line = buffer.readLine()) != null) {
counter++;
if (counter == 2) {
}
if (counter > 3) {
String[] word = Ingredient.split(",");
int Quantity = Integer.parseInt(word[1]);
int ServingNumberInt = Integer.parseInt(ServingNumber);
int Multiplier = ServingNumberInt / Quantity;
int NewQuantity = (Multiplier * NewServingNumber);
System.out.println("Your new quantity is " + NewQuantity);
}
}
System.out.println(line);
buffer.close();
}
} catch (Exception e) {
System.out.println("A read error has occured");
}
}
}
My input was:
applep - for the recipe name
10 - for serving number
apple,10,apples - for the ingredient, I only added 1 ingredient.
When I read and read my file and change the recipe servinging number, it doesn't not work and gives in an 'read error'. In addition, to test the problem, I printed the variable 'line' and it only seems to read the first line.
Thanks in advance!
You have two independent cases - one for reading and one for writing. If in one case, you assign values to variables, it does not mean that in other case you can read them. Also the counter is not set correctly. Try this code -
while((line = buffer.readLine()) !=null) {
counter++;
if (counter == 3) {
//String[]word = Ingredient.split(",");
String[]word = line.split(",");
int Quantity = Integer.parseInt(word[1]);
//int ServingNumberInt = Integer.parseInt();
int Multiplier = NewServingNumber / Quantity;
int NewQuantity = (Multiplier * NewServingNumber);
System.out.println("Your new quantity is " + NewQuantity);
}
}
it gives -
Hello. If you would like to write a new recipe, please type in 'write', if you would like to change and view a recipe, please type in 'read'
read
Would you like to change the serving number of your recipe, type in 'yes' to proceed, type in 'no'
yes
Please enter the new serving number
10
Your new quantity is 10
How do i return an error and ask the question Do you want to try again (Y/N)? again when the user entered neither Y/N as an answer?
import java.io.*;
public class Num10 {
public static void main(String[] args){
String in="";
int start=0, end=0, step=0;
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
do{
try{
System.out.print("Input START value = ");
in=input.readLine();
start=Integer.parseInt(in);
System.out.print("Input END value = ");
in=input.readLine();
end=Integer.parseInt(in);
System.out.print("Input STEP value = ");
in=input.readLine();
step=Integer.parseInt(in);
}catch(IOException e){
System.out.println("Error!");
}
if(start>=end){
System.out.println("The starting number should be lesser than the ending number");
System.exit(0);
}else
if(step<=0){
System.out.println("The step number should always be greater than zero.");
System.exit(0);
}
for(start=start;start<=end;start=start+step){
System.out.println(start);
}
try{
System.out.print("\nDo you want to try again (Y/N)?");
in=input.readLine();
}catch(IOException e){
System.out.println("Error!");
}
}while(in.equalsIgnoreCase("Y"));
}
}
Should i be using if-else?
First +1 for supplying a fully compilable program. That's more than 90% of question askers do.
In your final try/catch block, check that the user entered 'y' or 'n' like this
try{
while (!in.equalsIgnoreCase("y") && !in.equalsIgnoreCase("n")) {
System.out.print("\nDo you want to try again (Y/N)?");
in=input.readLine();
}
}catch(IOException e){
System.out.println("Error!");
}
}while(in.equalsIgnoreCase("Y"));
Do something like this:
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
boolean w4f = true;
do {
String in = input.readLine();
if ("Y".equalsIgnoreCase(in)) {
w4f = false;
// do something
} else if ("N".equalsIgnoreCase(in)) {
w4f = false;
// do something
} else {
// Your error message here
System.out.println("blahblah");
}
} while(w4f);