Saving integer input in a .txt file (Java) - 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.

Related

Code to convert sentence to ASCII doesn't work when there are space characters

I'd like to convert a sentence to ASCII but when the input is a sentence with spaces, the output is blank.
Code outputs the intended ASCII if it is just a single word.
Overall, the code written will receive an input from user, converts the String input, writes the converted sentence into a text file and reads from it.
String sentence;
int[] convert;
int l;
Scanner s = new Scanner(System.in);
System.out.print("Enter a sentence: ");
sentence=s.nextLine();
l=sentence.length();
convert = new int[l];
for(int i=0; i<l; i++){
convert[i]=sentence.charAt(i);
}
//Write to text file
try{
PrintWriter os = new PrintWriter(new FileOutputStream("data.txt"));
for(int i=0; i<l; i++){
os.print(convert[i]);
}
os.close();
}catch(IOException e){
System.out.println("Problem with file output");
}
//Read from text file and print
int num;
try{
Scanner is = new Scanner(new FileInputStream("data.txt"));
while(is.hasNextInt()){
num= is.nextInt();
System.out.print(num);
}
System.out.println("");
is.close();
}catch(FileNotFoundException e){
System.out.println("File was not found");
}
The following change in the code will print entire output:
while(is.hasNext()){System.out.println(is.next());}

I need a program that will ask the user to enter the information to save, line to line in a file. How can I do it?

I need a program that will ask the user to enter the information to save, line to line in a file. How can I do it?
It has to look like this:
Please, choose an option:
1. Read a file
2. Write in a new file
2
File name? problema.txt
How many lines do you want to write? 2
Write line 1: Hey
Write line 2: How are you?
Done! The file problema.txt has been created and updated with the content given.
I have tried in various ways but I have not succeeded. First I have done it in a two-dimensional array but I can not jump to the next line.
Then I tried it with the ".newline" method without the array but it does not let me save more than one word.
Attempt 1
System.out.println("How many lines do you want to write? ");
int mida = sc.nextInt();
PrintStream escriptor = new PrintStream(f);
String [][] dades = new String [mida][3];
for (int i = 0; i < dades.length; i++) {
System.out.println("Write line " + i + " :");
for (int y=0; y < dades[i].length; y++) {
String paraula = sc.next();
System.out.println(paraula + " " + y);
dades[i][y] = paraula;
escriptor.print(" " + dades[i][y]);
}
escriptor.println();
}
Attempt 2
System.out.println("How many lines do you want to write? ");
int mida = sc.nextInt();
PrintStream escriptor = new PrintStream(f);
BufferedWriter ficheroSalida = new BufferedWriter(new FileWriter(new File(file1)));
for (int i = 0; i < mida; i++) {
System.out.println("Write line " + i + " :");
String paraula = sc.next();
ficheroSalida.write (paraula);
ficheroSalida.newLine();
ficheroSalida.flush();
}
System.out.println("Done! The file " + fitxer + " has been created and updated with the content given. ");
escriptor.close();
Attempt 1:
Write line 1: Hey How are
Write line 1: you...
Attempt 2:
Write line 1: Hey
Write line 2: How
Write line 3: are
Write line 4: you
Write line 5: ?
Well, you're almost there. First, I'd use a java.io.FileWriter in order to write the strings to a file.
It's not really necessary to use an array here if you just want to write the lines to a file.
You should also use the try-with-resources statement in order to create your writer. This makes sure that escriptor.close() gets called even if there is an error. You don't need to call .flush() in this case either because this will be done before the handles gets closed. It was good that you intended to do this on your own but in general its safer to use this special kind of statement whenever possible.
import java.io.*;
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
File f = new File("/tmp/output.txt");
System.out.println("How many lines do you want to write? ");
int mida = sc.nextInt();
sc.nextLine(); // Consume next empty line
try (FileWriter escriptor = new FileWriter(f)) {
for (int i = 0; i < mida; i++) {
System.out.println(String.format("Write line %d:", i + 1));
String paraula = sc.nextLine();
escriptor.write(String.format("%s\n", paraula));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
In cases where your text file is kind of small and usage of streamreaders/streamwriters is not required, you can read the text, add what you want and write it all over again. Check this example:
public class ReadWrite {
private static Scanner scanner;
public static void main(String[] args) throws FileNotFoundException, IOException {
scanner = new Scanner(System.in);
File desktop = new File(System.getProperty("user.home"), "Desktop");
System.out.println("Yo, which file would you like to edit from " + desktop.getAbsolutePath() + "?");
String fileName = scanner.next();
File textFile = new File(desktop, fileName);
if (!textFile.exists()) {
System.err.println("File " + textFile.getAbsolutePath() + " does not exist.");
System.exit(0);
}
String fileContent = readFileContent(textFile);
System.out.println("How many lines would you like to add?");
int lineNumber = scanner.nextInt();
for (int i = 1; i <= lineNumber; i++) {
System.out.println("Write line number #" + i + ":");
String line = scanner.next();
fileContent += line;
fileContent += System.lineSeparator();
}
//Write all the content again
try (PrintWriter out = new PrintWriter(textFile)) {
out.write(fileContent);
out.flush();
}
scanner.close();
}
private static String readFileContent(File f) throws FileNotFoundException, IOException {
try (BufferedReader br = new BufferedReader(new FileReader(f))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
return everything;
}
}
}
An execution of the example would be:
Yo, which file would you like to edit from C:\Users\George\Desktop?
hello.txt
How many lines would you like to add?
4
Write line number #1:
Hello
Write line number #2:
Stack
Write line number #3:
Over
Write line number #4:
Flow
with the file containing after:
Hello
Stack
Over
Flow
And if you run again, with the following input:
Yo, which file would you like to edit from C:\Users\George\Desktop?
hello.txt
How many lines would you like to add?
2
Write line number #1:
Hey
Write line number #2:
too
text file will contain:
Hello
Stack
Over
Flow
Hey
too
However, if you try to do it with huge files, your memory will not be enough, hence an OutOfMemoryError will be thrown. But for small files, it is ok.

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();
...

How do I achieve the following results using the PrinterWriter class from a text file?

My application here prompts the user for a text file, mixed.txt which contains
12.2 Andrew
22 Simon
Sophie 33.33
10 Fred
21.21 Hank
Candice 12.2222
Next, the application is to PrintWrite to all text files namely result.txt and errorlog.txt. Each line from mixed.txt should begin with a number first followed by a name. However, certain lines may contain the other way round meaning to say name then followed by a number. Those which begins with a number shall be added to a sum variable and written to the result.txt file while those lines which begin with the name along with the number shall be written to the errorlog.txt file.
Therefore, on the MS-DOS console the results are as follow:
type result.txt
Total: 65.41
type errorlog.txt
Error at line 3 - Sophie 33.33
Error at line 6 - Candice 12.2222
Ok here's my problem. I only managed to get up to the stage whereby I have had all numbers added to result.txt and names to errorlog.txt files and I have no idea how to continue from there onwards. So could you guys give me some advice or help on how to achieve the results I need?
Below will be my code:
import java.util.*;
import java.io.*;
class FileReadingExercise3 {
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;
PrintWriter output2 = null;
try
{
output = new PrintWriter(new File("result.txt")); //writes all double values to the file
output2 = new PrintWriter(new File("errorlog.txt")); //writes all string values to the file
}
catch (IOException g)
{
System.out.println("Error");
System.exit(0);
}
while (fileInput.hasNext())
{
if (fileInput.hasNextDouble())
{
double num = fileInput.nextDouble();
String str = Double.toString(num);
output.println(str);
} else
{
output2.println(fileInput.next());
fileInput.next();
}
}
fileInput.close();
output.close();
output2.close();
}
}
This is the screenshot of the mixed.txt file:
You can change your while loop like this:
int lineNumber = 1;
while (fileInput.hasNextLine()) {
String line = fileInput.nextLine();
String[] data = line.split(" ");
try {
sum+= Double.valueOf(data[0]);
} catch (Exception ex) {
output2.println("Error at line "+lineNumber+ " - "+line);
}
lineNumber++;
}
output.println("Total: "+sum);
Here you can go through each line of the mixed.txt and check if it starts with a double or not. If it is double you can just add it to sum or else you can add the String to errorlog.txt. Finaly you can add the sum to result.txt
you should accumulate the result and after the loop write the summation, also you can count the lines for error using normal counter variable. for example:
double mSums =0d;
int lineCount = 1;
while (fileInput.hasNext())
{
String line = fileInput.nextLine();
String part1 = line.split(" ")[0];
if ( isNumeric(part1) ) {
mSums += Double.valueOf(part1);
}
else {
output2.println("Error at line " + lineCount + " - " + line);
}
lineCount++;
}
output.println("Totals: " + mSums);
// one way to know if this string is number or not
// http://stackoverflow.com/questions/1102891/how-to-check-if-a-string-is-a-numeric-type-in-java
public static boolean isNumeric(String str)
{
try
{
double d = Double.parseDouble(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
this will give you the result you want in error files:
Error at line 3 - Sophie 33.33
Error at line 6 - Candice 12.2222

Dead code java eclipse

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();

Categories