Dead code java eclipse - java

I am trying to check if the word given by the user already exists in the text file or a substring of it already exists. Here's my code:
String ans = null;
Scanner scanner = null;
do
{
System.out.print("Please enter a new word: ");
String Nword = scan.next();
System.out.print("And its appropriate Hint: ");
String Nhint = scan.next();
Word word = new Word(Nword , Nhint);
File file = new File("C:\\Users\\Charbel\\Desktop\\Dictionary.txt");
file.createNewFile();
scanner = new Scanner(file);
if (scanner != null)
{
String line;
while (scanner.hasNext()) {
line = scanner.next();
for(int i = 0 ; i<line.length(); i++)
if ((line.equals(Nword)) || (Nword.equals(line.substring(i))))
{
System.out.println("The word already exists.");
break;
}
}
}
else
{
FileWriter writer = new FileWriter(file , true);
writer.write(word.toString());
writer.write(System.lineSeparator());
writer.flush();
writer.close();
System.out.println("Your word has successfuly added.");
System.out.print("\nWould you like to add another word ?\nPress 0 to continue.");
ans = scan.next();
}
} while(ans.equals("0"));
Eclipse said that the statements after the else condition are "Dead Code" and I don't know why.

scanner = new Scanner(file);
scanner is initialized, can never be null, so the else statement will never be reached.
See the constructor:
Throws: FileNotFoundException - if source is not found
So if the file doesn't exists, scanner won't be null, you'll have an exception.

scanner = new Scanner(file);
This statement is creating a new instance here. So this:
if (scanner != null) will never be false.

Dead-Code is which never gets executed, for example:
if(true) {
// do something
}else {
// do something else <-- this is dead code, or else-block is dead code
}
In your case since Scanner is getting created before if(scanner != null) there is no way of execution of associated else. If Scanner creation fails error will be thrown again in which else will not be executed, hence from compiler point-of-view no chance of else block getting executed hence dead-code.
if-else would have made sense if scanner instance is passed as argument.
To solve this, else should be removed!
Following should correct your code:
scanner = new Scanner(file);
FileWriter writer = new FileWriter(file, true);
if (scanner != null) {
String line;
while (scanner.hasNext()) {
line = scanner.next();
for (int i = 0; i < line.length(); i++)
if ((line.equals(""))
|| ("".equals(line.substring(i)))) {
System.out.println("The word already exists.");
break;
} else {
writer.write(word.toString());
writer.write(System.lineSeparator());
writer.flush();
System.out.println("Your word has successfuly added.");
System.out.print("\nWould you like to add another word ?\nPress 0 to continue.");
ans = scan.next();
}
}
}
writer.close();

Related

How to incorporate a method in a filewriter

I'm having trouble with one of my homework problems, I think i've done everything right up until the last part which is to call the method and write the method to the output file. Here is the assignment:
Write a method isPrime which takes a number and determines whether the
number is prime or not. It returns a Boolean.
Write a main method that asks the user for an input file that contains
numbers and an output file name where it will write the prime numbers
to.
Main opens the input file and calls isPrime on each number. Main
writes the prime numbers to the output file.
Modify main to throw the appropriate exceptions for working with
files.
I've tried several different ways to write the method with the output file but I'm not sure exactly how to do it.
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
System.out.println("What is the name of the input file?");
String inputfile = keyboard.nextLine();
File f = new File(inputfile);
System.out.println("What is the name of the output file?");
String outputfile = keyboard.nextLine();
Scanner inputFile = new Scanner(f);
FileWriter fw = new FileWriter(outputfile);
PrintWriter pw = new PrintWriter(new File(outputfile));
while (inputFile.hasNextLine()) {
pw.write(inputFile.nextLine().isPrime());
pw.write(System.lineSeparator());
}
pw.close();
inputFile.close();
}
public static void isPrime (int num) throws IOException {
boolean flag = false;
for (int i =2; i <= num/2; i++) {
if (num % i ==0) {
flag = true;
break;
}
}
if (!flag)
System.out.println(num + "is a prime number");
else
System.out.println(num + "is not a prime number");
}
I need the program to be able to read a inputfile of a different numbers and then write out to the output file which of those numbers is prime.
You wrote "inputFile.nextLine().isPrime()". But inputFile.nextLine() gives you back a String. There is no method isPrime() that you can call on a String, therefore you will get a compilation error.
You must first convert it to an integer, pass it to your method, and then deal with the result:
isPrime(Integer.parseInt(inputFile.nextLine()));
I suggest you just return a message string from your method isPrime() instead of void, then you can deal with it properly:
pw.write(isPrime(Integer.parseInt(inputFile.nextLine())));
ADDENDUM:
I modified your code so you can see where to add the suggested lines. I also left out unnecessary lines.
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
System.out.println("What is the name of the input file?");
String inputfile = keyboard.nextLine();
File f = new File(inputfile);
System.out.println("What is the name of the output file?");
String outputfile = keyboard.nextLine();
Scanner inputFile = new Scanner(f);
PrintWriter pw = new PrintWriter(new File(outputfile));
while (inputFile.hasNextLine()) {
String nextLine = inputFile.nextLine();
boolean isPrime = isPrime(Integer.parseInt(nextLine));
if (isPrime) {
pw.write(nextLine + System.lineSeparator());
}
}
pw.close();
inputFile.close();
}
public boolean isPrime (int num) {
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
TODO: put your file-opening code inside a try-catch-finally block and put your close() commands into its finally block. (If you don't know why it should be inside finally, just ask)

Saving integer input in a .txt file (Java)

I'm trying to get the integers I enter to be written to a text file, yet however I edit the code my notepad spits out my integers as nonsense. Example:
Integer inputted: java.util.Scanner[delimiters=\p{javaWhitespace}+][position=1][match valid=true][need input=false][source closed=false][skipped=false]...
I believe my problem is in the line which I have marked with a "*". How would I go about fixing this? I believe it has something to do with the "String.valueOf(input)" line. Full code linked below!
for (int i = 0 ; i < 10 ; i++) {
System.out.printf("Please enter integer %d: ", i+1);
numbers[i] = input.nextInt();
{
try
{
*output.format("Integer inputted: %s%n", String.valueOf(input));
}
catch (FormatterClosedException formatterClosedexception)
{
System.err.println("Error writing to the file. Terminating.");
break;
}
catch (NoSuchElementException elementException)
{
System.err.println("Invalid input. Please try again.");
input.nextLine();
}
http://pastebin.com/yV6dhSMt
You can use this to write in to a file:
PrintWriter writer = new PrintWriter(fileName);
writer.println("1");
writer.println("2");
writer.close();
And this to read from that file:
String line, newLine; // Variable to store a line and to check for a new line
String[] splited; // Variable to split text
int lines = 0; // Variable to check how many lines in a file
Scanner myReader = new Scanner(new File(fileName));
BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName));
Numbers[] numbers = new numbers[2];
while ((line = bufferedReader.readLine()) != null) {
lines++;
for (int i = 1 ; i < 2 ; i++) {
while (myReader.hasNextLine()) {
newLine = myReader.nextLine();
splited = newLine.split(",");
numbers[i] = Integer.parseInt(splited[i]);
}
}
}
myReader.close();
I just wrote this here, but from what I remember this is how I did it.

Skipping whitespace on new line?

I can't seem to get this correct. Basically if the line is blank inside the text file it should skip the line instead of numbering it.
Ex: If the file contains, Apples,Oranges,Pineapples
it should produce
Apples
Oranges
Pineapples
or
1. Apples
(blank)
Oranges
Pineapples
try {
Scanner reader = new Scanner(System.in);
System.out.print("Enter file name with extension: ");
File file = new File(reader.nextLine());
reader = new Scanner(file);
int counter = 1;
while (reader.hasNextLine())
{
if (reader.equals(" ")){
System.out.println();
}else{
String line = reader.nextLine();
System.out.printf("%2d.", counter++); // Use printf to format
System.out.println(line);
}
}
reader.close();
} catch (Exception ex){
ex.printStackTrace();
}
}
}
Space or " " is actually totally different to an empty line...
so the reason why is not working is the condition
if (reader.equals(" ")){.....
use instead the String.isEmpty() method, since this is what you need...
or try this:
...
reader = new Scanner(file);
int counter = 1;
while (reader.hasNextLine()) {
final String line = reader.nextLine();
if (line.isEmpty()) {
System.out.println("This is an empty line");
} else {
System.out.printf("%2d.", counter++); // Use printf to format
System.out.println(line);
}
}
reader.close();
...

Updating an old line inside a text file

Okay, so i have an issue trying to update a line or sentence in a text file.
The way my program works is this: If a user enters a question the program searches the text file for that exact question(lets say is n). The answer to the question would be on the following line(n + 1). My issue is trying to update the following line(n + 1) to some new line entered by the user.
I keep getting a Exception in thread "main" java.util.NoSuchElementException: No line found when i try to update the line in the text file. my removedata() is where i am trying to update the line of text.
Here is my code
public static void removedata(String s) throws IOException {
File f = new File("data.txt");
File f1 = new File("data2.txt");
BufferedReader input = new BufferedReader(new InputStreamReader(
System.in));
BufferedReader br = new BufferedReader(new FileReader(f));
PrintWriter pr = new PrintWriter(f1);
String line;
while ((line = br.readLine()) != null) {
if (line.contains(s)) {
System.out.println("Enter new Text :");
String newText = input.readLine();
line = newText;
System.out.println("Thank you, Have a good Day!");
}
pr.println(line);
}
br.close();
pr.close();
input.close();
Files.move(f1.toPath(), f.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
public static void parseFile(String s) throws IOException {
File file = new File("data.txt");
Scanner scanner = new Scanner(file);
Scanner forget = new Scanner(System.in);
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(s)) {
System.out.println(scanner.nextLine());
System.out
.println(" Would you like to update this information ? ");
String yellow = forget.nextLine();
if (yellow.equals("yes")) {
removedata(scanner.nextLine()); // NoSuchElementException
// error
} else if (yellow.equals("no")) {
System.out.println("Have a good day");
// break;
}
}
}
}
public static void getinput() throws IOException {
Scanner scanner = new Scanner(System.in);
String input = null;
/* End Initialization */
System.out.println("Welcome ");
System.out.println("What would you like to know?");
System.out.print("> ");
input = scanner.nextLine().toLowerCase();
parseFile(input);
}
public static void main(String args[]) throws ParseException, IOException {
/* Initialization */
getinput();
}
My text file is :
what is the textbook name?
the textbook name is Java
how is the major?
the major is difficult
how much did the shoes cost?
the shoes cost ten dollars
Can someone help me solve this issue?
Change the code in the if block in parsefile to
String temp = scanner.nextLine();
System.out.println(temp);
System.out
.println(" Would you like to update this information ? ");
String yellow = forget.nextLine();
if (yellow.equals("yes")) {
removedata(temp); // NoSuchElementException
// error
} else if (yellow.equals("no")) {
System.out.println("Have a good day");
// break;
}
for an explanation why this works, look at Nick L.s answer.
The problem is here:
while (scanner.hasNextLine()) { //(1)
final String lineFromFile = scanner.nextLine(); //(2)
if (lineFromFile.contains(s)) { //(3)
System.out.println(scanner.nextLine()); //(4)
//....
String yellow = forget.nextLine(); //(5)
if (yellow.equals("yes")) {
removedata(scanner.nextLine()); //(6)
}
}
//....
}
First of all, you are correctly iterating the scanner lines checking whether there is a line (1). Now, you are getting the first line of the scanner on (2), but if the condition (3) succeeds, you are retrieving the next line again at (4) inside System.out.println(....). Same thing applies to (5) and (6) accordingly.
Now, imagine that you have reached the end of file at (2) and the condition at (3) succeeds. You will receive an exception of no such line, as you logically have. The same can happen at (5) and (6).
Each call of the nextLine(), will get the next line of the file opened on the stream.
I suggest that you do one readline inside the loop, then apply the received string when needed.

I have to make a loop taking a users input until "done" is entered

I'm trying to make an ArrayList that takes in multiple names that the user enters, until the word done is inserted but I'm not really sure how. How to achieve that?
ArrayList<String> list = new ArrayList<String>();
String input = null;
while (!"done".equals(input)) {
// prompt the user to enter an input
System.out.print("Enter input: ");
// open up standard input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// read the input from the command-line; need to use try/catch with the
// readLine() method
try {
input = br.readLine();
} catch (IOException ioe) {
System.out.println("IO error trying to read input!");
System.exit(1);
}
if (!"done".equals(input) && !"".equals(input))
list.add(input);
}
System.out.println("list = " + list);
I would probably do it like this -
public static void main(String[] args) {
System.out.println("Please enter names seperated by newline, or done to stop");
Scanner scanner = new Scanner(System.in); // Use a Scanner.
List<String> al = new ArrayList<String>(); // The list of names (String(s)).
String word; // The current line.
while (scanner.hasNextLine()) { // make sure there is a line.
word = scanner.nextLine(); // get the line.
if (word != null) { // make sure it isn't null.
word = word.trim(); // trim it.
if (word.equalsIgnoreCase("done")) { // check for done.
break; // End on "done".
}
al.add(word); // Add the line to the list.
} else {
break; // End on null.
}
}
System.out.println("The list contains - "); // Print the list.
for (String str : al) { // line
System.out.println(str); // by line.
}
}
String[] inputArray = new String[0];
do{
String input=getinput();//replace with custom input code
newInputArray=new String[inputArray.length+1];
for(int i=0; i<inputArray.length; i++){
newInputArray[i]=inputArray[i];
}
newInputArray[inputArray.length]=input
intputArray=newInputArray;
}while(!input.equals("done"));
untested code, take it with a grain of salt.
ArrayList<String> names = new ArrayList<String>();
String userInput;
Scanner scanner = new Scanner(System.in);
while (true) {
userInput = scanner.next();
if (userInput.equals("done")) {
break;
} else {
names.add(userInput);
}
}
scanner.close();

Categories