I'm trying to do some homework for my computer science class and I can't seem to figure this one out. The question is:
Write a program that reads a line of text and then displays the line, but with the first occurrence of hate changed to love.
This sounded like a basic problem, so I went ahead and wrote this up:
import java.util.Scanner;
public class question {
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a line of text:");
String text = keyboard.next();
System.out.println("I have rephrased that line to read:");
System.out.println(text.replaceFirst("hate", "love"));
}
}
I expect a string input of "I hate you" to read "I love you", but all it outputs is "I". When it detects the first occurrence of the word I'm trying to replace, it removes the rest of the string, unless it's the first word of the string. For instance, if I just input "hate", it will change it to "love". I've looked at many sites and documentations, and I believe I'm following the correct steps. If anyone could explain what I'm doing wrong here so that it does display the full string with the replaced word, that would be fantastic.
Thank you!
Your mistake was on the keyboard.next() call. This reads the first (space-separated) word. You want to use keyboard.nextLine() instead, as that reads a whole line (which is what your input is in this case).
Revised, your code looks like this:
import java.util.Scanner;
public class question {
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a line of text:");
String text = keyboard.nextLine();
System.out.println("I have rephrased that line to read:");
System.out.println(text.replaceFirst("hate", "love"));
}
}
Try getting the whole line like this, instead of just the first token:
String text = keyboard.nextLine();
keyboard.next() only reads the next token.
Use keyboard.nextLine() to read the entire line.
In your current code, if you print the contents of text before the replace you will see that only I has been taken as input.
As an alternate answer, build a while loop and look for the word in question:
import java.util.Scanner;
public class question {
public static void main(String[] args)
{
// Start with the word we want to replace
String findStr = "hate";
// and the word we will replace it with
String replaceStr = "love";
// Need a place to put the response
StringBuilder response = new StringBuilder();
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a line of text:");
System.out.println("<Remember to end the stream with Ctrl-Z>");
String text = null;
while(keyboard.hasNext())
{
// Make sure we have a space between characters
if(text != null)
{
response.append(' ');
}
text = keyboard.next();
if(findStr.compareToIgnoreCase(text)==0)
{
// Found the word so replace it
response.append(replaceStr);
}
else
{
// Otherwise just return what was entered.
response.append(text);
}
}
System.out.println("I have rephrased that line to read:");
System.out.println(response.toString());
}
}
Takes advantage of the Scanner returning one word at a time. The matching will fail if the word is followed by a punctuation mark though. Anyway, this is the answer that popped into my head when I read the question.
Related
I'm a first year IT student and we recently had an activity that asks the programmer to create a program that will accept a sentence or a phrase, then detect if there is a space in that string and add a newline in between words that have a space after it.
For clarification, here's what the prompt should look like:
Enter a sentence or phrase: I am a student
then the output would be:
I
am
a
student
I tried to actually finish the code, but I was hit by a roadblock and got stuck. Here's my attempt though:
import java.util.*;
public class NumTwo{
public static void main (String[] args){
Scanner in = new Scanner(System.in);
String phr;
System.out.print("Enter a phrase: ");
phr = in.nextLine();
if(phr.contains(" ")){
System.out.print(phr + "\n");
}
else{
}
}
}
any comments to what i might have done wrong will be very much appreciated
EDIT:
I tried using sir Christoph Dahlen's solution which was to use String.replace, and it worked! Thank you very much.
You are currently checking weither the input line contains any spaces at all, but you have to react to every space instead.
One way would be to split phr by spaces and concatenating it with newlines.
String result = String.join(System.lineSeparator(), phr.split(" "))
I'm trying to progress displaying a file line by line with an Enter key, but the if statement that I try doesn't seem to work. If I disregard the if statement, it works, but it feels incomplete because then I'm asking for input and doing nothing with it.
This is what I have:
import java.util.Scanner;
import java.io.*;
public class LineByLine {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
System.out.println("What is the filename?");
String input = in.nextLine();
BufferedReader buff = new BufferedReader(new FileReader(input));
String sen = buff.readLine();
System.out.println(sen);
Scanner enter = new Scanner(System.in);
while (sen != null){
String output = enter.next();
if (output.equals("")){
System.out.println(sen = buff.readLine());
}
}
}
}
I just don't know why my if statement doesn't work.
The core issue is that you misunderstand Scanner and its default configuration: Out of the box, scanner splits on any amount of whitespace. .next() asks for the next token; a token is the thing that appears in between the whitespace.
Thus, pressing enter 500 times produces zero tokens. After all, tokens are what's in between the separator, and the default separator is 'any amount of whitespace'. Pressing enter a bunch of time is still just you entering the same separator.
The underlying problem is that most people appear to assume that Scanner reads one line at a time. It doesn't do that. At all. But you want it to. So, tell it to! Easy peasy - make scanner do what you already thought it did:
Scanner in = new Scanner(System.in);
in.useDelimiter("\\R"); // a single enter press is now the separator.
You should also stop using nextLine on scanners. nextLine and any other next call do not mix. The easiest way to solve this problem is to only ever use nextLine and nothing else, or, never use nextLine. With the above setup, .next() gets you a token which is an entire line - thus, no need for nextLine, which is good news, as nextLine is broken (it does what the spec says it should, but what it does is counterintuitive. We can debate semantics on whether 'broken' is a fair description of it. Point is, it doesn't do what you think it does).
Also, while you're at it, don't make multiple scanners. And, to improve this code, resources must be properly closed. You're not doing that. Let's use try-with, that's what it is for.
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
in.useDelimiter("\\R");
System.out.println("What is the filename?");
String input = in.next();
try (BufferedReader buff = new BufferedReader(new FileReader(input))) {
String sen = buff.readLine();
System.out.println(sen);
while (sen != null){
enter.next(); // why does it matter _what_ they entered?
// as long as they pressed it, we're good, right? Just ignore what it returns.
System.out.println(sen = buff.readLine());
}
}
}
public static void main(String[] args) {
//For String
Scanner input = new Scanner(System.in);
//For Letter
Scanner word = new Scanner(System.in);
String name;
//Input For a String
System.out.println("Enter A String");
name = input.nextLine();
//Input For a Char
char letter[] = new char[3];
System.out.println("Enter a Letter You Want to Search ");
for(char c : letter)
letter = word.nextLine().toCharArray();
elfish(letter, name);
}
public static void elfish(char letter[], String name) {
if(name.toLowerCase().contains(name.valueOf(letter).toLowerCase())) {
System.out.println("Yes The Letter Contains Elfish");
} else {
System.out.println("You're Word is not in this String");
}
}
i m making the program which is near to completion. It actually searches the desired letter in the string and if condition is true is prints the "if block" and if condition is false "else block" should run but actually its not working now. only "if block" is working. "else block" was also working fine until it was directly placed in main function. please tell me where what is wrong.
You're trying to iterate through letter before putting anything in the array. If you take out the for loop, (leaving the assignment of letter) the code should run properly in many cases. I do not know how you want to validate input.
I'm guessing you are new. Learning to use a debugger can be overwhelming, but it is a powerful tool. It'll be slightly different for every debugger and IDE but the process is the same.
A little more info here: Breakpoints and step by step debug in Java?
However, in this instance finding a guide for your IDE on Google might be the best option.
So my program knows where the file is and it can read how many words it has, however, I am trying to compare words to count the occurrences of a word that i will use with a scanner.
The program says i can't convert string to a boolean which i understand but how would i be able to make it happen?
can I get an answer why it runs but doesn't allow me to find the word to look for
thanks
import java.util.*;
import java.io.*;
public class wordOccurence {
public static void main(String[] args) throws IOException {
{
int wordCount=0;
int word =0;
Scanner scan=new Scanner(System.in);
System.out.println("Enter file name");
System.out.println("Enter the word you want to scan");
String fileName=scan.next().trim();
Scanner scr = new Scanner(new File(fileName));
// your code goes here ...
while(scr.nextLine()){
String word1 = scr.next();
if (word1.equals(scr)){
word++;
}
}
System.out.println("Total words = " + word);
}
}
}
At present you are only checking if there is a next line available:
while(scr.hasNextLine()){
but you are not fetching it. Its like you are staying at the same position in the file forever.
To fetch the next line, you can make use of
scanner.nextLine()
I'm stuck and need your help (yes, it's homework), what I'm trying to do is get my code to read the contents in the text file and output the words by specific words. For example I want it to output all words that start with letter "g".
Here's a pseudocode code if I didn't explain that well:
BEGIN
Get the initial letter from the user
While there are more entries in the file
Get the next personal name
Get the next surname
Get the next year info
If the surname starts with the initial letter
Output the person name, surname and year info
End while
END
So far I've managed to get this done, and now I'm stuck where you output the names correctly. Any help or tutorials will be appreciated.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class PrimeMinisters
{
public static void main(String[] args) throws FileNotFoundException
{
// ask the user for the first letter
Scanner keyboard = new Scanner(System.in);
System.out.print("What is the first letter? ");
String input = keyboard.next().toLowerCase();
char firstLetter = input.charAt(0);
// open the data file
File pmFile = new File ("OZPMS.txt");
// create a scanner from the file
Scanner pmInput = new Scanner (pmFile);
// read one line of data at a time, processing each line
while(pmInput.hasNext())
{
String names = pmInput.next();
System.out.println(names);
}
// be polite and close the file
pmInput.close();
}
}
I'd recommend using nextLine() over next(). From this you would then use the String's startsWith(String stringsequence) method which returns a boolean to get all the values beginning with the letter of your choice:
while(pmInput.hasNextLine())
{
String names = pmInput.nextLine();
System.out.println(names);
if(names.startsWith("g")) {
//the name begins with letter g do whatever
}
}
You can have a look at more methods for String here: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
Since your requirements state to look at the surname's first letter, it will be easier to tokenize each line while you read it (while checking to see if the user input is the first letter of the surname). Assuming that the line is in the order that you stated above, the surname will be token #2 (index 1 of the array).
public class PrimeMinisters
{
public static void main(String[] args) throws FileNotFoundException
{
// ask the user for the first letter
Scanner keyboard = new Scanner(System.in);
System.out.print("What is the first letter? ");
String input = keyboard.next().toLowerCase();
char firstLetter = input.charAt(0);
// open the data file
File pmFile = new File ("OZPMS.txt");
// create a scanner from the file
Scanner pmInput = new Scanner (pmFile);
// read one line of data at a time, processing each line
while(pmInput.hasNextLine())
{
String names = pmInput.nextLine();
// Break line into tokens. This is assuming that there are only
// 3 strings per line in the following order (personal name, surname, yearinfo)
//
String[] info = names.split("\\s");
// Check 2nd string in line (since you are looking for the first character in
// the surname and not the personal name.
//
if(info[1].startsWith(input))
{
System.out.println(info[0] + "\t" + info[1] + "\t" + info[2]);
}
}
// be polite and close the file
pmInput.close();
}
}