I am writing a program where if someone types in the following two lines:
HELLO, I’D LIKE TO ORDER A FZGH
KID’S MEAL
The program will output it like this:
HELLO, I’D LIKE TO ORDER A KID’S MEAL
In other words, the "FZGH" the user inputs into the sentence will be replaced with the second line's words, as you can see: the "FZGH" is replaced by "KID'S MEAL." Kinda get what I mean? If not, I can elaborate more but this is the best I can explain it as.
I'm really close to solving this! My current output is: HELLO, I’D LIKE TO ORDER A FZGH KID’S MEAL
My program didn't replace the "FZGH" with "KID'S MEAL," and I don't know why that is. I thought that by using the .replaceAll() thingy, it would replace "FZGH" with the "KID'S MEAL," but that didn't really happen. Here is my program so far:
public static void main(String[] args) {
sentences();
}
public static void sentences() {
Scanner console = new Scanner(System.in);
String sentence1 = console.nextLine();
String sentence2 = console.nextLine();
//System.out.println(sentence1 + "\n" + sentence2);
String word = sentence1.replaceAll("[FZGH]", "");
word = sentence2;
System.out.print(sentence1 + word);
}
Where did I mess up, resulting in the FZGH still appearing in output?
Use
sentence1 = sentence1.replaceAll("FZGH", "");
String word = sentence2;
Your first (and primary) problem is that you're creating a new String named word, that you're setting to the value of sentence1.replaceAll("[FZGH]", ""). You're then changing the value of word to be sentence2 immediately afterward, so the replacement is lost.
Instead, setting sentence1 to sentence1.replaceAll("FZGH", ""); will change sentence1 to no longer contain the string "FZGH", which is what you're going for. You don't actually need a word value at all, so if you'd like to remove it, it wouldn't hurt.
In addition, using [FZGH] will replace all F's, Z's, G's, and H's from the string- you should use FZGH instead, as this will only remove instances of all four letters in a row.
I think you have a couple of mistakes. Maybe the following is close...
public static void main(String[] args) {
sentences();
}
public static void sentences() {
Scanner console = new Scanner(System.in);
String sentence1 = console.nextLine();
String sentence2 = console.nextLine();
String sentence3 = sentence1+sentence2;
String final = sentence3.replaceAll("FZGH", "");
System.out.print(final);
}
You are reassigning the string "word"
in place of lines :
String word = sentence1.replaceAll("[FZGH]", "");
word = sentence2;
System.out.print(sentence1 + word);
use the following lines
sentence1 = sentence1.replaceAll("[FZGH]", "");
System.out.print(sentence1 + sentence2);
Actually replace method return a string that should be assign again to sentence1. you can run this code its works fine.
public static void main(String[] args) {
sentences();
}
public static void sentences() {
Scanner console = new Scanner(System.in);
String sentence1 = "HELLO, I’D LIKE TO ORDER A FZGH";
String sentence2 = "KID’S MEAL";
//System.out.println(sentence1 + "\n" + sentence2);
sentence1 = sentence1.replace("FZGH", "");
String word = sentence2;
System.out.print(sentence1 + word);
}
Related
We have to make a program on printing initials, which seems pretty easy ok, but I don't know how to cut the string when the input is all on one line using the scanner class in.nextline();. I cant seem to find a way to cut the string using only string methods. Also, another problem arose when I have to also be able to adjust if there isn't a middle name either. if anyone can help me or lead me in the right direction that would be nice.
If you can use split function as you can see below:
String inputString=s.nextLine();
String [] str = inputString.split(" ");
If you want to have extract only first letter then -
import java.util.Scanner;
public class TestStringInput {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please Enter the Name");
String input = scan.nextLine();
int value = input.indexOf(" ",input.indexOf(" "));
String result = input.substring(0,value);
System.out.println(result);
}
}
But if you want to Extract Starting 2 Initials then change this line-
int value = input.indexOf(" ",input.indexOf(" ")+1);
As Stephen mentioned, your question is about Java, consider re-tagging.
You can use a for loop to iterate through the string. Remember a string is an object. It would help a lot if you posted your code.
import java.util.Scanner;
public class HW03 {
public static void main (String args[])
{
Scanner in = new Scanner(System.in);
String str = "";
System.out.println("What are your first, middle and last names?");
str = in.nextLine();
}
}
I need to do this:
Create a program that asks for the user's name and says how many characters the name contains.
Your program should be structured so that you put the calculating of the name length in it's own method: public static int calculateCharacters(String text). The tests will be testing both the method calculateCharacters and the program overall.
I know how to count the characters in a string. I just can't figure out how to do this when I have to use a seperate method. Can someone please help me?
import java.util.Scanner;
public class LengthOfName {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type your name: ");
String name = reader.nextLine ();
int cal = calculateCharacters(name);
System.out.println(Number of characters: " + cal);
}
public static int calculateCharacters(String text) {
int cal = text.length ();
//System.out.println("Number of characters: " + count ());
return cal;`
What's the error? I'm not seeing any errors in logic here, just a couple syntax issues like missing a quotation mark around "Number of characters: ", a missing curly brace at the end of the calculateCharacters method, and an extra whitespace between reader.nextLine and ().
Your method call itself looks fine.
As the title suggests, I'm trying to make a method that will individually work on each word of a string. I've gotten the code down but I'm not sure if it is right. So I ran a couple of tests to see if it prints out appropriately. After multiple tries and absolutely nothing printing out. I need help. Can anyone find anything wrong my code?
public static String build( String str4, one test){
Scanner find = new Scanner( System.in);
String phrase = " ";
while ( find.hasNext()){
String word = find.next();
word = test.change(word);
phrase += word + " ";
}
return phrase;
}
The method change just changes the word to pig latin ( my intended goal ).
Here are the simple lines in my main method:
String str4 = "I am fluent in pig latin";
System.out.println (test.build(str4, test));
I intended for this code to print out this:
Iyay amyay uentflay inyay igPay atinLay
You attempt to get some input inside your function, using the Scanner instance, giving user input as its construction argument.
In order to print what is going to be returned, add this line:
System.out.println (phrase);
before your return statement.
What I am guessing though, is you are mistakenly using user input.
Try this instead:
public static String build( String str4, one test){
Scanner find = new Scanner(str4);
String phrase = " ";
while ( find.hasNext()){
String word = find.next();
word = test.change(word);
phrase += word + " ";
}
//Print your phrase here if you want.
System.out.println(phrase);
return phrase;
}
You have:
Scanner find = new Scanner( System.in);
Which means you're reading from user input.
You also have this str4 parameter, but you're not actually using it. You seem to have inadvertently used System.in as your input string source when you really meant to use your str4 parameter. Hence, nothing happens, as find.next() is waiting for input from the console rather than using the string you passed in.
You probably mean:
Scanner find = new Scanner(str4);
I am having trouble getting my program to produce the exact output I would like it to. My program currently will remove any one instance of a string in a sentence the user inputs (Ex: Sentence- Hello there– String to be removed Hello and Output there).
What I would like to do is add something else so that the program will remove any and all instances of the string the user would like omitted (Ex: Hello there there in my current program, it would output Hello there. What I would like is it to simply print Hello). Can someone give me any idea on how to implement this. Thanks!
(Im also rather new to coding, so if you have an input on my code as is, please feel free to correct it)
Here is my current code:
import java.util.Scanner;
public class RemoveWord
{
Scanner scan = new Scanner(System.in);
String sentence;
String word;
public void removing()
{
System.out.println("Please enter a sentence");
sentence = scan.nextLine();
System.out.println("Please enter a word you would like removed from the sentence");
word = scan.nextLine();
int start = sentence.indexOf(word), end=0;
while(start!=-1)
{
sentence = sentence.substring(0, start) + sentence.substring(start+word.length());
end = start+word.length();
if(end>=sentence.length())
break;
start = sentence.indexOf(word, end);
}
System.out.println(sentence);
}
}
public class RemoveWordR
{
public static void main(String[]args)
{
RemoveWord r1 = new RemoveWord();
r1.removing();
}//main
}//class
Your problem is with end, because indexOf(x,y) check for occurrence of x after index y. It is int indexOf(String str, int fromIndex)
while(start!=-1)
{
sentence = sentence.substring(0, start) + sentence.substring(start+word.length());
end = start+word.length();
if(end>=sentence.length())
break;
start = sentence.indexOf(word, 0); //this line must be 0 or nothing
}
replaceAll() method provided by a string should replace all occurrences of a given word in the string
Example:
sentence.replaceAll("there","")
or
sentence.removeAll("there")
I am exceptionally new to java, as in, I can barely write 20 lines of basic code and have them work, level of new, I have 2 issues which may or may not be related as they are from very similar pieces of code that I have personally written.
import java.util.Scanner;
public class StringCW {
public static void main (String [] args) {
String word = "";
while(!(word.equals("stop"))){
Scanner capconversion = new Scanner(System.in);
System.out.println("Enter word:" );
word = capconversion.next();
String lower = word.toLowerCase();
word = lower;
System.out.println("conversion = " + word);
}
System.out.println("ending program");
}
}
}
This is my first chunk of code, it is designed to take any string and convert it into lowercase, however if I am to print anything seperated by a space, eg: "WEWEFRDWSRGdfgdfg DFGDFGDFG" only the first 'word' will be printed and converted, I am also getting a memory leak from cap conversion, though I don't understand what that means or how to fix it
My second problem is likely along the same lines
import java.util.Scanner;
public class splitstring {
private static Scanner capconversion;
public static void main (String [] args) {
String word = "";
while(!(word.equals("stop"))){
capconversion = new Scanner(System.in);
System.out.println("Enter word:" );
word = capconversion.next();
String lower = word.toLowerCase();
String[] parts = lower.split(" ");
parts [0] = "";
parts [1] = "";
parts [2] = "";
parts [3] = "";
parts [4] = "";
System.out.println("conversion = " + lower
parts [0] + parts [1] + parts [2] + parts [3] + parts [4]);
}
System.out.println("ending program");
}
}
this is the 2nd chunk of code and is designed to do the same job as the previous one except print out each 'word' on a new line, then return to the input part until the stop command is entered
the error I get is
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at splitstring.main(splitstring.java:21)
however I don't understand where the error is coming in
This is because you're using Scanner.next(), which returns a single token - and which uses whitespace as a token separator by default.
Perhaps you should use nextLine() instead, if you want to capture a whole line at a time?
As for your ArrayIndexOutOfBoundsException - that has basically the same cause. You're calling split on a single word, so the array returned has only one element (element 0). When you try to set element 1, that's outside the bounds of the array, hence the exception.
Note that nothing in here really has anything to do with toLowerCase().