Program outputs code from multiple methods instead of just one method - java

I have a Java program that troubleshoots common problems with phones. To do this I have set up a scanner that reads the user input for any keywords. If one of these keywords is found, a method will output from a text file a solution to the problem suggested by that keyword.
My problem is that when I run the program, all the lines from the text file are outputted, from every method, disregarding my input.
Here's the code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class task2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("What is your problem?");
String input = scan.nextLine();
String[] problems = {"screen", "display", "broken", "cracked", "camera", "flash", "ports"};
String[] solutions = input.split("broken");
for(int x=0; x < problems.length; x++){
if(input.contains("broken")){
if(input.contains("screen")){
brokenScreen();
} else{
}
if(input.contains("display")) {
brokenDisplay();
} else{
}
if(input.contains("camera")) {
brokenCamera();
} else{
}
if(input.contains("flash")) {
brokenFlash();
} else{
}
if(input.contains("ports")) {
brokenPorts();
} else{
}
}
else{
}
if(input.contains("cracked")) {
if(input.contains("screen")) {
crackedScreen();
} else{
}
}
if(input.contains("water")) {
waterPhone();
}
else{
}
}
brokenScreen();
brokenDisplay();
crackedScreen();
brokenCamera();
brokenFlash();
brokenPorts();
waterPhone();
noSolution();
}
public static void noSolution() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; //Location of the text file
try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void waterPhone() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void brokenPorts() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void brokenFlash() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void brokenCamera() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void crackedScreen() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void brokenDisplay() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void brokenScreen() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Can anyone please solve this issue? Any help would be greatly appreciated.

Remove
brokenScreen();
brokenDisplay();
crackedScreen();
brokenCamera();
brokenFlash();
brokenPorts();
waterPhone();
noSolution();
at the end of your main method (after the for loop).

Related

What is wrong in my code. Decryption.txt not accepting any message in java file operation.?

import java.io.*;
import java.util.Random;
import java.util.Scanner;
class EncryptDecryptFile{
public String readEncryptionFile()
{
String contentLine1 = "";
//String encryptFilename = Solution.filepath + "EncryptionFile.txt";
BufferedReader br = null;
try
{
br = new BufferedReader(new FileReader("C:\\Users\\HP\\Desktop\\EncryptionFile.txt"));
String contentLine = br.readLine();
while (contentLine != null)
{
contentLine1 = contentLine;
}
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
finally
{
try
{
if(br != null)
br.close();
}
catch (IOException ioe)
{
System.out.println("Error in closing the BufferedReader");
}
}
return contentLine1;
}
public void writeDecryptionFile(String message)
{
BufferedWriter bw = null;
//String decryptFilename = Solution.filepath + "DecryptionFile.txt";
try
{
File file = new File("C:\\Users\\HP\\Desktop\\DecryptionFile.txt");
if (!file.exists())
{
file.createNewFile();
FileWriter fw = new FileWriter(file);
bw = new BufferedWriter(fw);
bw.write(message);
}
else
{
FileWriter fw = new FileWriter(file);
bw = new BufferedWriter(fw);
bw.write(message);
}
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
finally
{
try
{
if(bw!=null)
bw.close();
}
catch(Exception ex)
{
System.out.println("Error in closing the BufferedWriter"+ex);
}
}
}
}
public class Solution {
public static String filepath = "C:\\Users\\HP\\Desktop\\";
private static String generateString()
{
char[] chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".toCharArray();
StringBuilder generatedString = new StringBuilder(20);
Random random = new Random();
for (int i = 0; i < 40; i++) {
char c = chars[random.nextInt(chars.length)];
generatedString.append(c);
}
return generatedString.toString();
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
String message = sc.nextLine();
try{
EncryptDecryptFile f = new EncryptDecryptFile ();
String encryptFilename = Solution.filepath + "EncryptionFile.txt";
String generatedString = generateString();
BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\Users\\HP\\Desktop\\EncryptionFile.txt"));
writer.write(generatedString);
writer.close();
if(f.readEncryptionFile().equals(generatedString))
{
f.writeDecryptionFile(message);
String decryptFilename = Solution.filepath + "DecryptionFile.txt";
BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\HP\\Desktop\\DecryptionFile.txt"));
String messageFromFile = reader.readLine();
reader.close();
System.out.println(messageFromFile);
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
When I write in the Decryption.txt file using writeDecryptionFile(message) method the file not accept the message.
There are two method readEncryptionFile() method and writeDecryptionFile(message) method.
readEncryptionFile() read the content from Encryption.txt and it matches with generatedString if it equals true then,
writeDecryptionFile(message) method write the message String message = sc.nextLine(); to the Decryption.txt file.
instead of this you can use library to decrypt and encrypt.
I'm not quite sure, what you are trying to ask, but it seem's like you are missing a 'flush' in writeDecryptionFile
...
bw = new BufferedWriter(fw);
bw.write(message);
bw.flush();
...
without the flush the buffered characters are never written to the stream
https://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html#flush()

How to delete or remove a specific line from a text file

I was trying to delete a line from a file. I've search on the internet. And i made a method. Here is it.
public void removeLine(BufferedReader br , File f, String Line) throws IOException{
File temp = new File("temp.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
String removeID = Line;
String currentLine;
while((currentLine = br.readLine()) != null){
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(removeID)){
currentLine = "";
}
bw.write(currentLine + System.getProperty("line.separator"));
}
temp.renameTo(f);
bw.close();
br.close();
}
I don't know what is wrong with this method. Could you help me?
Here is where i use this method
delete.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent evt) {
BufferedReader br = null;
try{
String enterID2 = enterID1.getText().trim();
File books = new File("books.txt");
br = new BufferedReader(new FileReader(books));
removeLine(br , books, enterID2);
System.out.println("done");
}catch (NumberFormatException e1) {
System.out.println("This is not a number");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Delete is a JButton. No error recieved.
Try this code:
public static void removeLine(BufferedReader br , File f, String Line) throws IOException{
File temp = new File("temp.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
String removeID = Line;
String currentLine;
while((currentLine = br.readLine()) != null){
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(removeID)){
currentLine = "";
}
bw.write(currentLine + System.getProperty("line.separator"));
}
bw.close();
br.close();
boolean delete = f.delete();
boolean b = temp.renameTo(f);
}

multiple words replace in txt file using java

I need to replace multiple words in txt file using java. This program only replacing the only one word, in whole file.
import java.io.*;
public class MultiReplace
{
public static void main(String args[])
{
try
{
File file = new File("file.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while((line = reader.readLine()) != null)
{
oldtext += line + "\r\n";
}
reader.close();
String newtext = oldtext.replaceAll("india", "freedom");
FileWriter writer = new FileWriter("file.txt");
writer.write(newtext);writer.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
Try this:
import java.io.*;
public class MultiReplace
{
public static void main(String args[])
{
try
{
File file = new File("file.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while((line = reader.readLine()) != null)
{
// Replace in the line and append
line = line.replaceAll("india", "freedom");
oldtext += line + "\r\n";
}
reader.close();
FileWriter writer = new FileWriter("file.txt");
writer.write(newtext);
writer.flush();
writer.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
Refer this to understand why your version is not working.
Your solution is correct!! I ran your program as is and it is able to replace all the india with freedom in the text file

Using exceptions in Java with user I/O

I am trying to do the following: I am making a program in Java which let me create and read text files. So far I have been able to do this, but the hard(?) part is this: I have to be able to get an error when anything else but A, B or C is inside the text file.
So far I got:
package textfile;
import java.io.*;
import static java.lang.System.*;
class OutWrite {
public static void main(String[] args) {
try{
FileWriter fw = new FileWriter("FAS.txt");
PrintWriter pw = new PrintWriter(fw);
pw.println("A");
pw.println("B");
pw.println("C");
pw.close();
} catch (IOException e){
out.println("ERROR!");
}
}
}
And
package textfile;
import java.io.*;
import static java.lang.System.*;
class InRead {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("FSA.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null){
out.println(str);
}
br.close();
} catch (IOException e) {
out.println("File not found");
}
}
}
Can anyone steer me in the right direction, please?
Just throw Exception when a new Character is found other than A,B,C .
use,
class InRead {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("FSA.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
if (str.equals("A") || str.equals("B") || str.equals("c")) //compare
out.println(str);
else
throw new Exception(); //throw exception
}
br.close();
} catch (IOException e) {
out.println("File not found");
}
catch (Exception e) {//catch it here and print the req message
System.out.println("New Character Found");
}
}
}

File read, changed but how to write out?

Ok, forgive my beginner-ness and please tell me how I can output my text from "before.txt" into a fresh new file called "after". Obviously I have altered the text along the way to make it lower-case and eliminate non alphabetic characters.
import java.io.*;
public class TextReader {
public void openFile() throws IOException {
try {
// Read in the file
BufferedReader br = new BufferedReader(
new FileReader(
new File("before.txt")));
String currentLine = br.readLine();
currentLine = currentLine.toLowerCase();
currentLine = currentLine.replaceAll("[A-Z]", "");
br.close(); // Close br to prevent resource leak
}
// Exception if the file is not in the path specified
catch (Exception e) {
System.out.println("Error: File not found");
}
}
public void writeFile() throws IOException {
BufferedWriter output = new BufferedWriter(new FileWriter("/WS3Ex3/after.txt"));
output.write("before.txt");
output.close();
}
}
What about this
public void openFile() throws IOException {
try {
// Read in the file
BufferedReader br = new BufferedReader(
new FileReader(
new File("before.txt")));
String currentLine = br.readLine();
currentLine = currentLine.toLowerCase();
currentLine = currentLine.replaceAll("[A-Z]", "");
br.close(); // Close br to prevent resource leak
writeFile(currentLine);
}
// Exception if the file is not in the path specified
catch (Exception e) {
System.out.println("Error: File not found");
}
}
public void writeFile(String text) throws IOException {
BufferedWriter output = new BufferedWriter(new FileWriter("/WS3Ex3/after.txt"));
output.write(text);
output.close();
}
}
Let me guess, is this a school assignment?
Try this:
public void ReadAndWrite() throws IOException {
try {
// Read in the file
BufferedWriter output = new BufferedWriter(new FileWriter("/WS3Ex3/after.txt"));
BufferedReader br = new BufferedReader(
new FileReader(
new File("before.txt")));
String currentLine;
while((currentLine = br.readLine()) != NULL){
currentLine = currentLine.toLowerCase();
currentLine = currentLine.replaceAll("[A-Z]", "");
output.write(currentLine);
}
br.close(); // Close br to prevent resource leak
output.close();
}
// Exception if the file is not in the path specified
catch (Exception e) {
System.out.println("Error: File not found");
}
}

Categories

Resources