I'm having a bit of trouble figuring out how to read multiple lines of user input into a scanner and then storing it into a single string.
What I have so far is down below:
public static String getUserString(Scanner keyboard) {
System.out.println("Enter Initial Text:");
String input = "";
String nextLine = keyboard.nextLine();
while(keyboard.hasNextLine()){
input += keyboard.nextLine
};
return input;
}
then the first three statements of the main method is:
Scanner scnr = new Scanner(System.in);
String userString = getUserString(scnr);
System.out.println("\nCurrent Text: " + userString );
My goal is to have it where once the user types their text, all they have to do is hit Enter twice for everything they've typed to be displayed back at them (following "Current text: "). Also I need to store the string in the variable userString in the main (I have to use this variable in other methods). Any help at all with this would be very much appreciated. It's for class, and we can't use arrays or Stringbuilder or anything much more complicated than a while loop and basic string methods.
Thanks!
Using BufferedReader:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = "";
String line;
while((line = br.readLine()) != null){
if(line.isEmpty()){
break; // if an input is empty, break
}
input += line + "\n";
}
br.close();
System.out.println(input);
Or using Scanner:
String input = "";
Scanner keyboard = new Scanner(System.in);
String line;
while (keyboard.hasNextLine()) {
line = keyboard.nextLine();
if (line.isEmpty()) {
break;
}
input += line + "\n";
}
System.out.println(input);
For both cases, Sample I/O:
Welcome to Stackoverflow
Hello My friend
Its over now
Welcome to Stackoverflow
Hello My friend
Its over now
Complete code
public static void main (String[] args) {
Scanner scnr = new Scanner(System.in);
String userString = getUserString(scnr);
System.out.println("\nCurrent Text: " + userString);
}
public static String getUserString(Scanner keyboard) {
System.out.println("Enter Initial Text: ");
String input = "";
String line;
while (keyboard.hasNextLine()) {
line = keyboard.nextLine();
if (line.isEmpty()) {
break;
}
input += line + "\n";
}
return input;
}
Related
The same question was asked before but I the help wasn't sufficient enough for me to get it solved. When I run the program many times, it goes well for a string with comma in between(e.g. Washington,DC ). For a string without comma(e.g. Washington DC) the program is expected to print an error message to the screen and prompt the user to enter the correct input again. Yes, it does for the first run. However, on the second and so run, it fails and my suspect is on the while loop.
Console snapshot:
Enter input string:
Washington DC =>first time entered & printed the following two lines
Error: No comma in string.
Enter input string:
Washington DC => second time, no printouts following i.e failed
Here's my attempt seeking your help.
public class practice {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
String delimit =",";
boolean inputString = false;
System.out.println("Enter input string:");
userInput = scnr.nextLine();
while (!inputString) {
if (userInput.contains(delimit)){
String[] userArray = userInput.split(delimit);
// for(int i=0; i<userArray.length-1; i++){
System.out.println("First word: " + userArray[0]); //space
System.out.println("Second word:" + userArray[1]);
System.out.println();
//}
}
else if (!userInput.contains(delimit)){
System.out.println("Error: No comma in string.");
inputString= true;
}
System.out.println("Enter input string:");
userInput = scnr.nextLine();
while(inputString);
}
}
}
You can easily solve this problem using a simple regex ^[A-Z][A-Za-z]+, [A-Z][A-Za-z]+$
So you can check the input using :
boolean check = str.matches("^[A-Z][A-Za-z]+, [A-Z][A-Za-z]+$");
Then you can use do{}while() loop instead, so your code should look like this :
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput;
do {
System.out.println("Enter input string:");
userInput = scnr.nextLine();
} while (!userInput.matches("^[A-Z][A-Za-z]+, [A-Z][A-Za-z]+$"));
}
regex demo
Solution 2
...But I can't apply regex at this time and I wish others help me to
finish up the work the way I set it up
In this case you can use do{}while(); like this :
Scanner scnr = new Scanner(System.in);
String userInput;
String delimit = ",";
boolean inputString = false;
do {
System.out.println("Enter input string:");
userInput = scnr.nextLine();
if (userInput.contains(delimit)) {
String[] userArray = userInput.split(delimit);
System.out.println("First word: " + userArray[0]);
System.out.println("Second word:" + userArray[1]);
System.out.println();
} else if (!userInput.contains(delimit)) {
System.out.println("Error: No comma in string.");
inputString = true;
}
} while (inputString);
I am attempting to write a program that will take user input ( a long message of characters), store the message and search a text file to see if those words occur in the text file. The problem I am having is that I am only ever able to read in the first string of the message and compare it to the text file. For instance if I type in "learning"; a word in the text file, I will get a result showing that is is found in the file. However if I type "learning is" It will still only return learning as a word found in the file even though "is" is also a word in the text file. My program seems to not be able to read past the blank space. So I suppose my questions is, how do I augment my program to do this and read every word in the file? Would it also be possible for my program to read every word, with or without spaces, in the original message taken from the user, and compare that to the text file?
Thank you
import java.io.*;
import java.util.Scanner;
public class Affine_English2
{
public static void main(String[] args) throws IOException
{
String message = "";
String name = "";
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
System.out.println("Please enter in a message: ");
message = scan.next();
Scanner file = new Scanner(new File("example.txt"));
while(file.hasNextLine())
{
String line = file.nextLine();
for(int i = 0; i < message.length(); i++)
{
if(line.indexOf(message) != -1)
{
System.out.println(message + " is an English word ");
break;
}
}
}
}
}
I recommend you first process the file and build a set of legal English words:
public static void main(String[] args) throws IOException {
Set<String> legalEnglishWords = new HashSet<String>();
Scanner file = new Scanner(new File("example.txt"));
while (file.hasNextLine()) {
String line = file.nextLine();
for (String word : line.split(" ")) {
legalEnglishWords.add(word);
}
}
file.close();
Next, get input from the user:
Scanner input = new Scanner(System.in);
System.out.println("Please enter in a message: ");
String message = input.nextLine();
input.close();
Finally, split the user's input to tokens and check each one if it is a legal word:
for (String userToken : message.split(" ")) {
if (legalEnglishWords.contains(userToken)) {
System.out.println(userToken + " is an English word ");
}
}
}
}
You may try with this. With this solution you can find each word entered by the user in your example.txt file:
public static void main(String[] args) throws IOException
{
String message = "";
String name = "";
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
System.out.println("Please enter in a message: ");
message = scan.nextLine();
Scanner file = new Scanner(new File("example.txt"));
while (file.hasNextLine())
{
String line = file.nextLine();
for (String word : message.split(" "))
{
if (line.contains(word))
{
System.out.println(word + " is an English word ");
}
}
}
}
As Mark pointed out in the comment, change
scan.next();
To:
scan.nextLine();
should work, i tried and works for me.
If you can use Java 8 and Streams API
public static void main(String[] args) throws Exception{ // You need to handle this exception
String message = "";
Scanner input = new Scanner(System.in);
System.out.println("Please enter in a message: ");
message = input.nextLine();
List<String> messageParts = Arrays.stream(message.split(" ")).collect(Collectors.toList());
BufferedReader reader = new BufferedReader(new FileReader("example.txt"));
reader.lines()
.filter( line -> !messageParts.contains(line))
.forEach(System.out::println);
}
You have many solution, but when it comes to find matches I suggest you to take a look to the Pattern and Matcher and use Regular Expression
I haven't fully understood your question, but you could do add something like this (I did not tested the code but the idea should work fine):
public static void main(String[] args) throws IOException{
String message = "";
String name = "";
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
System.out.println("Please enter in a message: ");
message = scan.next();
Scanner file = new Scanner(new File("example.txt"));
String pattern = "";
for(String word : input.split(" ")){
pattern += "(\\b" + word + "\\b)";
}
Pattern r = Pattern.compile(pattern);
while(file.hasNextLine())
{
String line = file.nextLine();
Matcher m = r.matcher(line);
if(m.matches()) {
System.out.println("Word found in: " + line);
}
}
}
public class Try{
public static void main (String args[]) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("Try.txt"));
Scanner sc = new Scanner(System.in);
System.out.print("Enter the subtring to look for: ");
String Word=sc.next();
String line=in.readLine();
int count =0;
String s[];
do
{
s=line.split(" ");
for(int i=0; i < s.length; i++)
{
String a = s[i];
if(a.contains(Word))
count++;
}
line=in.readLine();
}while(line!=null);
System.out.print("There are " +count+ " occurences of " +Word+ " in ");
java.io.File file = new java.io.File("Try.txt");
Scanner input = new Scanner(file);
while(input.hasNext())
{
String word = input.nextLine();
System.out.print(word);
}
}
}
The intended purpose of my program is to ask the user for a certain word(s) that will be checked in a text file and if it exists, it will count the number of times the user-entered word occurs in the text file. So far, my program can only search for one word. If I try two words separated by space, only the first word will be searched and counted for its number of occurrence. Any tips on how to search multiple words?
I was following literally the title of the question and therefore I will suggest this algorithm:
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("Test.txt"));
Scanner sc = new Scanner(System.in);
System.out.print("Enter the subtring to look for: ");
String word = sc.next();
String line = in.readLine();
int count = 0;
// here is where the efficiently magic happens
do {
// 1. you dont need to split a line by spaces, too much overhead...
// 2. and you dont need to do counter++
// 3. do instead: calculate the number of coincidences that the word is
//repeated in a whole line...that is what the line below does..
count += (line.length() - line.replace(word, "").length()) / word.length();
//the rest looks fine
//NOTE: if you need a whole word then wrap the input of the user and add the empty spaces at begin and at the end...so the match will be perfect to a word
line = in.readLine();
} while (line != null);
System.out.print("There are " + count + " occurences of " + word + " in ");
}
Edit:
if you want to check more than one word in the document then use this
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("Test.txt"));
Scanner sc = new Scanner(System.in);
System.out.print("Enter the subtring to look for: ");
String input = sc.nextLine();
String[] word = input.split(" ");
String line = in.readLine();
int count = 0;
do {
for (String string : word) {
count += (line.length() - line.replace(string, "").length()) / string.length();
}
line = in.readLine();
} while (line != null);
System.out.print("There are " + count + " occurences of " + Arrays.toString(word) + " in ");
}
I've written majority of this. I just can't figure out how to capitalize the first letter of each line. the problem is:
Write a program that checks a text file for several formatting and punctuation matters. The program asks for the names of both an input file and an output file. It then copies all the text from the input file to the output file, but with the following two changes (1) Any string of two or more blank characters is replaced by a single blank; (2) all sentences start with an uppercase letter. All sentences after the first one begin after either a period, a question mark, or an exclamation mark that is followed by one or more whitespace characters.
I've written most of the code. I just need help with the capitalization of the first letter of each sentence. Here's my code:
import java.io.*;
import java.util.Scanner;
public class TextFileProcessor
{
public static void textFile()
{
Scanner keyboard = new Scanner(System.in);
String inputSent;
String oldText;
String newText;
System.out.print("Enter the name of the file that you want to test: ");
oldText = keyboard.next();
System.out.print("Enter the name of your output file:");
newText = keyboard.next();
System.out.println("\n");
try
{
BufferedReader inputStream = new BufferedReader(new FileReader(oldText));
PrintWriter outputStream = new PrintWriter(new FileOutputStream(newText));
inputSent = inputStream.readLine();
inputSent = inputSent.replaceAll("\\s+", " ").trim();
inputSent = inputSent.substring(0,1).toUpperCase() + inputSent.substring(1);
inputSent = inputSent.replace("?", "?\n").replace("!", "!\n").replace(".", ".\n");
//Find a way to make the first letter capitalized
while(inputSent != null)
{
outputStream.println(inputSent);
System.out.println(inputSent);
inputSent = inputStream.readLine();
}
inputStream.close();
outputStream.close();
}
catch(FileNotFoundException e)
{
System.out.println("File" + oldText + " could not be located.");
}
catch(IOException e)
{
System.out.println("There was an error in file" + oldText);
}
}
}
import java.util.Scanner;
import java.io.*;
public class TextFileProcessorDemo
{
public static void main(String[] args)
{
String inputName;
String result;
String sentence;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the name of your input file: ");
inputName = keyboard.nextLine();
File input = new File(inputName);
PrintWriter outputStream = null;
try
{
outputStream = new PrintWriter(input);
}
catch(FileNotFoundException e)
{
System.out.println("There was an error opening the file. Goodbye!" + input);
System.exit(0);
}
System.out.println("Enter a line of text:");
sentence = keyboard.nextLine();
outputStream.println(sentence);
outputStream.close();
System.out.println("This line was written to:" + " " + input);
System.out.println("\n");
}
}
Since your code already contains inputSent = inputSent.substring(0,1).toUpperCase() + inputSent.substring(1); I assume that inputSent can contain more than one sentence or might just represent a line of the file with parts of sentences.
Thus I'd suggest you first read the entire file into a string (if it's not too large) and then use split() on that string to break it into individual sentences, capitalize the first character and join them again.
Example:
String[] sentences = fileContent.split("(?<=[?!.])\\s*");
StringBuilder result = new StringBuilder();
for( String sentence : sentences) {
//append the first character as upper case
result.append( Character.toUpperCase( sentence.charAt(0) ) );
//add the rest of the sentence
result.append( sentence.substring(1) );
//add a newline
result.append("\n");
}
//I'd not replace the input, but to be consistent with your code
fileContent = result.toString();
The easiest way is maybe using WordUtil from Apache commons-langs.
You should use the capitalise method with the delimiters as parameter.
You can try the following regular expression:
(\S)([^.!?]*[.!?]( |$))
Code:
public static void main(String[] args) {
String inputSent = "hi! how are you? fine, thanks.";
inputSent = inputSent.replaceAll("\\s+", " ").trim();
Matcher m = Pattern.compile("(\\S)([^.!?]*[.!?]( |$))").matcher(inputSent);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, m.group(1).toUpperCase() + m.group(2) + "\n");
}
m.appendTail(sb);
System.out.println(sb);
}
See a demo online.
Output:
Hi!
How are you?
Fine, thanks.
In the ASCII table lower and upper case are just integers that are 32 positions away from each other...
try something like this:
String inputSent = .... //where ever it does come from...
System.out.println(inputSent.replace(inputSent.charAt(0), (char) (inputSent.charAt(0) - 32)));
or use some kind of APACHE libs like WordUtils.
I would change the textFile() to the below:
public static void textFile()
{
Scanner keyboard = new Scanner(System.in);
String inputSent;
String oldText;
String newText;
System.out.print("Enter the name of the file that you want to test: ");
oldText = keyboard.next();
System.out.print("Enter the name of your output file:");
newText = keyboard.next();
System.out.println("\n");
try
{
BufferedReader inputStream = new BufferedReader(new FileReader(oldText));
PrintWriter outputStream = new PrintWriter(new FileOutputStream(newText));
while ((inputSent = inputStream.readLine()) != null) {
char[] chars = inputSent.toCharArray();
chars[0] = Character.toUpperCase(chars[0]);
inputSent = new String(chars);
inputSent = inputSent.replaceAll("\\s+", " ").trim();
inputSent = inputSent.substring(0,1).toUpperCase() + inputSent.substring(1);
inputSent = inputSent.replace("?", "?\n").replace("!", "!\n").replace(".", ".\n");
System.out.println("-> " + inputSent);
outputStream.println(inputSent);
}
inputStream.close();
outputStream.close();
}
catch(FileNotFoundException e)
{
System.out.println("File" + oldText + " could not be located.");
}
catch(IOException e)
{
System.out.println("There was an error in file" + oldText);
}
}
This will read the text file line by line.
Upper the first char
Do this in a while loop
The problem with your original textFile() is that it only applies uppercase first char, blank space etc on the very first line it reads.
My first post here on stackoverflow.
The task is:
Write a method that shall return a String, the method has no parameters. The method is going to read some word from the keyboard. The inputs ends with the word "END" the method should return this whole text as a long row:
"HI" "HELLO" "HOW" "END"
Make is so that the method return the string
HIHELLOHOW
MY CODE IS:
import java.util.*;
public class Upg13_IS_IT_tenta {
String x, y, c, v;
public String text(){
System.out.println("Enter your first letter");
Scanner sc = new Scanner(System.in); //Can you even make this outside main?
x = sc.next();
y = sc.next();
c = sc.next();
v = sc.next(); // Here I assign every word with a variable which i later will return. (at the bottom //i write return x + y + c;). This is so that i get the string "HIHELLOWHOW"
sc.next();
sc.next();
sc.next();
sc.next(); // Here I want to return all the input text as a long row
return x + y + c;
}
}
I know that my code has a lot of errors in it, I am new to Java so I would like so help and explaining of what I've done wrong. THANKS!
you can do something like this:
public String text(){
InputStreamReader iReader = new InputStreamReader(System.in);
BufferedReader bReader = new BufferedReader(iReader);
String line = "";
String outputString = "";
while ((line = bReader.readLine()) != null) {
outputString += line;
}
return outputString;
}
Probably you want something like
public String text() {
String input;
String output = "";
Scanner sc = new Scanner(System.in);
input = sc.next();
while (! input.equals("END")) {
output = output + input;
input = sc.next();
}
return output;
}
What you have done now is build a program that can only handle one specific input.
You might want to aim for something more reusable:
public String text(){
System.out.println("Talk to me:");
Scanner sc = new Scanner(System.in);
StringBuilder text = new StringBuilder();
while(!text.toString().endsWith("END"))
{
text.append(sc.next());
}
return text.toString().substring(0, text.toString().length()-3);
}
This builds a single String out of your input, stops when the String ends with "END" and returns the String without the last 3 letters ("END").