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();
...
Related
I am writing a program to change an input file. It should start a new line after a ? . and ! but I can't seem to figure it out. Each new line should also begin with an Uppercase letter which I think I got. It should also eliminate unnecessary spaces which I also believe I got.
For example: hello? bartender. can I have a drink!whiskey please.
Output should be:
Hello?
Bartender.
Can I have a drink!whiskey please.
It should only make a new line after those operators followed by a whitespace. If there is no space it will not make new line.
import java.util.Scanner;
import java.io.*;
public class TextFileProcessorDemo
{
public static void main(String[] args)
{
String fileName, answer;
Scanner keyboard = new Scanner(System.in);
System.out.println("Test Input File:");
fileName = keyboard.nextLine();
File file = new File(fileName);
PrintWriter outputStream = null;
try
{
outputStream = new PrintWriter(file);
}
catch(FileNotFoundException e)
{
System.out.println("Error opening file" + file);
System.exit(0);
}
System.out.println("Enter a line of text:");
String line = keyboard.nextLine();
outputStream.println(line);
outputStream.close();
System.out.println("This line was written to:" + " " + file);
System.out.println(" ");
TextFileProcessor.textFile();
}
}
Second Class
import java.io.*;
import java.util.Scanner;
public class TextFileProcessor
{
public static void textFile()
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Test Input File:");
String inputFile = keyboard.next();
System.out.print("Output File:");
String outputFile = keyboard.next();
try
{
BufferedReader inputStream = new BufferedReader(new FileReader(inputFile));
PrintWriter outputStream = new PrintWriter(new FileOutputStream(outputFile));
String line = inputStream.readLine();
line = line.replaceAll("\\s+", " ").trim();
line = line.substring(0,1).toUpperCase() + line.substring(1);
//This is where I would like to add code
while(line != null)
{
outputStream.println(line);
System.out.println(line);
line = inputStream.readLine();
}
inputStream.close();
outputStream.close();
}
catch(FileNotFoundException e)
{
System.out.println("File" + inputFile + " not found");
}
catch(IOException e)
{
System.out.println("Error reading from file" + inputFile);
}
}
}
A simple regex would suffice:
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
for(String s:"hello? bartender. can I have a drink!whiskey please.".replaceAll("(\\W)(\\s+)", "$1\n").split("\n"))
System.out.println(s.substring(0, 1).toUpperCase()+s.substring(1));
}
}
Output :
Hello?
Bartender.
Can I have a drink!whiskey please.
https://ideone.com/Zo2N7Q
Would this solve your problem?
if(line.endsWith("! ") || line.endsWith("? ") || line.endsWith(". ")) {
line = line + '\n';
}
You can use a "capture group" in a regex to achieve what you want.
line.replaceAll("(\\? )|(\\! )|(\\. )", "$0\n");
Update:
With regards to your comment on how to capitalize the first character of each line, you can use the toUpperCase method in the Character class.
line = Character.toUpperCase(line.charAt(0)) + line.substring(1);
Note:
If you are using Java 1.7 or above you should consider using a try-with-resources block for the Scanner
try (Scanner keyboard = new Scanner(System.in)) {
...
}
Then when you read input from the user you can manipulate it to the correct format before writing to your file. For example you could do something like...
System.out.println("Enter a line of text:");
String[] lines = keyboard.nextLine().replaceAll("(\\? )|(\\! )|(\\. )", "$0\n").split("\n");
// Replace the first character of each line with an uppercase character
for (int i = 0; i < lines.length; i++) {
lines[i] = Character.toUpperCase(lines[i].charAt(0)) + lines[i].substring(1);
}
Path path = Paths.get(fileName);
Files.write(path, Arrays.asList(lines), Charset.defaultCharset());
System.out.println("This line was written to:" + " " + path.toString());
System.out.println(" ");
As for reading and writing from files you are better off using the non-blocking Files class in the java.nio package. It's as simple as the following;
Path path = Paths.get(fileName);
Files.write(path, Arrays.asList(lines), Charset.defaultCharset());
Then for reading your file you can just use the readAllLines method.
List<String> lines = Files.readAllLines(path);
for (String line : lines ) {
System.out.println(line);
}
I have a text file with the following line define : Hi 0x01. I'm trying to read in the word Hi and store it in its own variables and 0x01 in its own variable.The problem I'm having is that i seem to be able to read in Hi, but i cant read in0x01`.Here is my code
File comms =new File("src/Resources/com.txt");
try (Scanner scan = new Scanner(comms)) {
while (scan.hasNext()) {
String line = scan.nextLine();
Scanner sc = new Scanner(line);
sc.useDelimiter("\\s+");
try {
String comm1 = sc.next();
// System.out.println(comm1);
int value =sc.nextInt();
System.out.println(value);
sc.close();
} catch (Exception ef){
}
I honestly have no idea what you're trying to do here. You'd better scan it once:
File comms = new File("src/Resources/com.txt");
try(Scanner scan = new Scanner(comms)) {
while(scan.hasNext()) {
String line = scan.nextLine();
String[] words = line.split(" ");
System.out.println(words[0]); // "Hi"
System.out.println(words[1]); // "0x01"
}
}
catch(Exception e) {
}
Now, having these in separate strings you can do anything in the world with it like converting words[1] to int.
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.
I would like to write a paragraph using file.
This is my code(my effort).
import java.io.*;
import java.util.Scanner;
public class Test {
public static void main (String [] args)
{
Scanner input = new Scanner(System.in);
try {
BufferedWriter out = new BufferedWriter(new FileWriter("C:/Users/Akram/Documents/akram.txt")) ;
System.out.println("Write the Text in the File ");
String str = input.nextLine();
out.write(str);
out.close();
System.out.println("File created successfuly");
} catch (IOException e) {
e.printStackTrace();
}
}
}
With this code I can add just one word but I want to add a lot of word (paragraph).
I would use a while loop around Scanner#hasNextLine(). I would also recommend a PrintWriter. So, all together, that would look something like,
Scanner input = new Scanner(System.in);
PrintWriter out = null;
try {
out = new PrintWriter(new FileWriter(
"C:/Users/Akram/Documents/akram.txt"));
System.out.println("Write the Text in the File ");
while (input.hasNextLine()) {
String str = input.nextLine();
out.println(str);
}
System.out.println("File created successfuly");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
In order to write a paragraph, Decide a terminating character or string,Write your code so that it takes the input till that character or string is given in the input, Do some operation to remove the character in the file,
The code which I used is given below,Terminating Character is +
I haven't kept try and catch statements to reduce complexity in understanding
pw = new PrintWriter(new FileWriter("E://files//myfile.txt"));
System.out.println("Write the Text in the File,End the text with + ");
do
{
Scanner sc =new Scanner(System.in);
String S=sc.nextLine();
if(S.endsWith("+"))
{
S= S.replace("+"," ");
flag=1;
pw.println(S);
}
else
pw.println(S);
}while(flag!=1);
Cheers
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();