I am supposed to write code that replaces a letter in an input. For example, if the word is "hello" and the letter to replace is "l" and put "y" it would make "heyyo". I just don't know what to do after the user inputs.
import java.util.Scanner;
public class Letter
{
public static void main(String[] args)
{
// Ask the user for 3 things: their word, letter they want to replace,
// and replacing letter.
Scanner input = new Scanner(System.in);
System.out.println("Enter your word:");
String word = input.nextLine();
System.out.println();
System.out.println("Enter the letter you want to replace:");
String letter = input.nextLine();
System.out.println();
System.out.println("Enter the replacing letter:");
String replace = input.nextLine();
System.out.println();
// Call the method replaceLetter and pass all 3 of these items to it for
// string processing.
}
// Modify this method so that it will take a third parameter from a user that is the String
//they
//want
//to replace letterToReplace with. This method should return the modified String.
public static int replaceLetter(String word, String letterToReplace, String replacement)
{
int count = 0;
for(int i = 0; i < word.length(); i++)
{
if(word.substring(i, i+1).equals(letterToReplace))
{
count++;
}
}
return count;
}
}
Try doing the next, replacing the char at the position if it is the same as the letter to replace.
for(int i = 0; i < word.length(); i++)
{
if(word.charAt(i) == letterToReplace)
{
word = word.substring(0, i)
+ replacement
+ word.substring(i + 1);
count++;
}
}
Or you could just do the next:
word = word.replace(letterToReplace, replacement);
YCF_L is correct, the best way would be with replace. If you need to do things programatically for some reason, this will work:
public static void main(String[] args)
{
// Ask the user for 3 things: their word, letter they want to replace,
// and replacing letter.
Scanner input = new Scanner(System.in);
System.out.println("Enter your word:");
String word = input.nextLine();
System.out.println();
System.out.println("Enter the letter you want to replace:");
String letter = input.nextLine();
System.out.println();
System.out.println("Enter the replacing letter:");
String replace = input.nextLine();
System.out.println();
// Call the method replaceLetter and pass all 3 of these items to it for
// string processing.
System.out.println(replaceLetter(word, letter, replace));
}
// Modify this method so that it will take a third parameter from a user that is the String
//they
//want
//to replace letterToReplace with. This method should return the modified String.
public static String replaceLetter(String word, String letterToReplace, String replacement)
{
//Short way:
String wayOne = word.replace(letterToReplace, replacement);
//Long way:
String wayTwo = "";
for(int i = 0; i < word.length(); i++){
if(word.charAt(i) == letterToReplace.charAt(0)){
wayTwo += replacement;
} else {
wayTwo += Character.toString(word.charAt(i));
}
}
return wayOne + " VS " + wayTwo;
}
Related
I'm making a function that returns the second occurrence of a character the user inputs. The problem is that it's not printing anything. I remember hearing something about using a nested for loop for it but I don't know. Here's the program; the function I'm having problems with is the last one.
import javax.swing.JOptionPane;
public class IntroToWHILELoops
{
public static void main(String[] args)
{
//Thiis section tests the first method
String myString = GetAndStoreInput();
System.out.println(myString);
//This section tests the second method
System.out.println("Enter a character to search for --> ");
String searchChar = System.console().readLine();
int position = SecondCharPosition(myString,searchChar);
System.out.println("The second position of " +searchChar +" is " +position);
}
//This method keeps getting input from the user until a "X" or "x" is entered
//It then stores the input in a string.
public static String GetAndStoreInput()
{
String input;
String sentence = "";
input = JOptionPane.showInputDialog("Enter something (press x to stop)");
while(!input.equals("x") && !input.equals("X") ){
System.out.println(input);
sentence = sentence + input;
input = JOptionPane.showInputDialog("Enter something else (press x to stop)");
}
return sentence;
}
//Given a string, this method returns the position of the second occurrence of a given character.
//If the character occurs less than 2 times it returns -1.
public static int SecondCharPosition(String str, String Charr)
{
String sentence = str;
int count = 1;
int position = 0;
int i = 0;
while(count < 10){
if(sentence.substring(i,i+1).equals(Charr)){
count++;
}
if(count == 2){
position = i;
}
}
return position;
}
}
#Tyler - Hope this helps you.
import java.util.Scanner;
import javax.swing.*;
class Scratch {
public static void main(String[] args) {
// Thiis section tests the first method
String myString = GetAndStoreInput();
System.out.println(myString);
// This section tests the second method
System.out.println("Enter a character to search for --> ");
final Scanner in = new Scanner(System.in);
String searchChar = in.next();
int position = SecondCharPosition(myString, searchChar);
System.out.println("The second position of " + searchChar + " is " + position);
}
// This method keeps getting input from the user until a "X" or "x" is entered
// It then stores the input in a string.
public static String GetAndStoreInput() {
String input;
String sentence = "";
input = JOptionPane.showInputDialog("Enter something (press x to stop)");
while (!input.equals("x") && !input.equals("X")) {
System.out.println(input);
sentence = sentence + input;
input = JOptionPane.showInputDialog("Enter something else (press x to stop)");
}
return sentence;
}
// Given a string, this method returns the position of the second occurrence of a given character.
// If the character occurs less than 2 times it returns -1.
public static int SecondCharPosition(String str, String Charr) {
int count = 0;
int position = 0;
for (int i = 0; i < str.length(); i++) {
if (String.valueOf(str.charAt(i)).equals(Charr))
count++;
if (count == 2) {
position = i;
break;
}
}
return position;
}
}
The following Java program is supposed to manipulate a string input by the user in such a way that the user will decide which character needs to be replaced with another and just the last character from the string should be replaced. Example if the user enters the string "OYOVESTER" and decides to replace "O" with "L", the program should output the following result: "OYLVESTER" (notice that only the last "O" was replaced with "L")
NOTE: YOU CANNOT USE BREAK COMMAND TO STOP THE LOOP. IT IS PROHIBITED.
import java.util.Scanner;
public class StringFun {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
String inString = keyboard.nextLine();
String outString = "";
//Replace Last
System.out.println("Enter the character to replace");
char oldCharF = keyboard.next().charAt(0);
System.out.println("Enter the new character");
char newCharF = keyboard.next().charAt(0);
int count = 0; // variable that tracks number of letter occurrences
for(int index = inString.length() - 1;index >= 0;index--) {
if(inString.charAt(index) == oldCharF && count < 1){
outString = newCharF + outString;
outString = outString + inString.substring(0,index);
count++;
}
if (count < 1) {
outString = outString + inString.charAt(index);
}
}
System.out.print("The new sentence is: "+outString);
}
}
I keep getting the following output which is incorrect:
Enter the string to be manipulated
OYOVESTER
Enter the character to replace
O
Enter the new character
L
The new sentence is: LRETSEVOY
There are many simpler ways to achieve your requirement but I hope you have to demonstrate this with loops (without breaks)
Then you can use some thing like this :
boolean skip = false;
for (int index = inString.length() - 1; index >= 0; index--) {
if (!skip && inString.charAt(index) == oldCharF) {
outString = newCharF + outString;
skip = true;
}
else {
outString = inString.charAt(index) + outString;
}
}
PS : Using String concatenation inside loops is not recommended since
every String concatenation copies the whole String, usually it is preferable to
replace it with explicit calls to StringBuilder.append() or StringBuffer.append()
No break command seems like a weird condition. You could just a boolean value, and other methods, to break the loop when you need. Why not do something like this?
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
String word = keyboard.nextLine();
//Replace Last
System.out.println("Enter the character to replace");
char oldCharF = keyboard.next().charAt(0);
System.out.println("Enter the new character");
char newCharF = keyboard.next().charAt(0);
int index = word.lastIndexOf(oldCharF);
if(index > 1){
word = word.substring(0,index) + newCharF + word.substring(index+1);
}
System.out.println("The new sentence is: " + word);
}
In this code, I am trying to replace a letter from a String entered by a user. For example, the program asks for a word, and the user enters "hello", the next variable that the user inputs is the letter that is going to be replaced ("l"), and the final variable is the letter that is going to replace the previous variable ("x").
The result should be "hexxo", but my program is only replacing one of the l's, what is wrong with my program?
import java.util.Scanner;
public class Letter
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter your word:");
String word = input.nextLine();
System.out.println("\nEnter the letter you want to replace:");
String replace = input.nextLine();
System.out.println("\nEnter the replacing letter:");
String add = input.nextLine();
System.out.println(replaceLetter(word, replace, add));
}
public static String replaceLetter(String word, String letterToReplace, String add)
{
String newWord = "";
for(int i = 0; i < word.length(); i++)
{
if(word.substring(i, i+1).equals(letterToReplace))
{
String front = word.substring(0, word.indexOf(letterToReplace));
String back = word.substring(word.indexOf(letterToReplace)+1);
newWord = front + add + back;
}
}
return newWord;
}
}
There are 2 problems.
First, your program updates newWord everytime,
but whenever newWord is updated, it is calculated with not-updated word.
if(word.substring(i, i+1).equals(letterToReplace))
{
String front = !!!!!word!!!!!.substring(0, word.indexOf(letterToReplace));
String back = !!!!!word!!!!!.substring(word.indexOf(letterToReplace)+1);
newWord = front + add + back;
}
Second, why substring() in the if block does not use i?
String front = word.substring(0, !!!!!word.indexOf(letterToReplace)!!!!!);
String back = word.substring(!!!!!word.indexOf(letterToReplace)+1!!!!!);
The reason why your algorithm is not working, is that you're assigning a new String to newWord every time you replace a letter. So you will only get an output of the last replacement.
Every time the loop checks the the original string word.
First, your program updates newWord every-time, but whenever newWord is updated, it is calculated with not-updated word.
Just remove the variable newWord and perform operations on variable word only as presented in the following code:
import java.util.Scanner;
public class Letter
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter your word:");
String word = input.nextLine();
System.out.println("\nEnter the letter you want to replace:");
String replace = input.nextLine();
System.out.println("\nEnter the replacing letter:");
String add = input.nextLine();
System.out.println(replaceLetter(word, replace, add));
}
public static String replaceLetter(String word, String letterToReplace, String add)
{
for(int i = 0; i < word.length(); i++)
{
if(word.substring(i, i+1).equals(letterToReplace))
{
String front = word.substring(0, word.indexOf(letterToReplace));
String back = word.substring(word.indexOf(letterToReplace)+1);
word = front + add + back;
}
}
return word;
}
}
You could simply use String#replace or String#replaceAll. Just take a look into the java-doc to understand how they work.
Because you are using word.indexOf(letterToReplace) which will always return the first index of string. So, Instead, you need to use word.indexOf(letterToReplace,i); with minor code, changes will help you to solve your problem. Try it yourself.
Happy Coding !!!
This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I have an assignment due in about 6 hours and I really need help. I stayed up all night working on this but I can't seem to figure it out.
Basically what I need to do is, I have a user defined array. I'm supposed to take that array and manipulate that string into a variety of things. I've gotten most of it but I can't seem to remove a user defined element in the user defined string. I've tried using a for loop to try and find the specific character that the user wants to remove but I can't seem to get it to compile or write properly. This is my code so far:
import java.util.Scanner;
import java.util.Arrays;
public class StringManipulator {
public static void main(String[] args) {
String userStr;
Scanner input = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
userStr = input.nextLine();
while (true) {
System.out.println("Enter your command");
System.out.println("Print Reverse");
System.out.println("Replace All");
System.out.println("Replace Single");
System.out.println("Remove");
System.out.println("Quit");
String choice = input.nextLine();
String[] array = userStr.split("");
if (choice.equals("Print Reverse") || choice.equals("print reverse")) { //reverses the string
for(int i = array.length - 1;i >= 0; i --) {
System.out.print(array[i]);
}
System.out.println();
}
else if (choice.equals("Replace All")) { //Replaces all input letters with new letters that user inputs
System.out.println("What letter would you like to replace?");
String ridOf = input.nextLine();
System.out.println("What letter do you want to replace it as?");
String replace = input.nextLine();
String[] newArray = array;
for (int i = 0; i < array.length; i++) {
if(array[i].equals(ridOf)) {
array[i] = replace;
}
}
System.out.println("");
for(int i = 0; i < array.length; i++) {
System.out.print(array[i]);
}
System.out.println("");
}
else if (choice.equals("Replace Single") || choice.equals("replace single")) {
System.out.println("Enter the character to replace?");
String ridOf1 = input.nextLine();
System.out.println("Enter the new character");
String replace1 = input.nextLine();
System.out.println("Which " + ridOf1 + " would you like to replace?");
int choice1 = input.nextInt();
}
else if (choice.equals("Remove") || choice.equals("remove")) {
System.out.println("Enter the character to remove");
String ridOf2 = input.nextLine();
char charRemove = ridOf2.charAt(0);
for (int i = 0; i < array.length; i++) {
if(userStr.charAt(i) != ridOf2) {
userStr += userStr.charAt(i);
}
}
}
else if (choice.equals("Quit") || choice.equals("quit")) {
System.exit(0);
}
}
}
}
The only section that i'm actually worried about at this moment is the
else if(choice.equals("Remove")
section of the code.
Give this a shot explanation further down
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
String userStr;
Scanner input = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
userStr = input.nextLine();
while (true) {
System.out.println("Enter your command");
System.out.println("Print Reverse");
System.out.println("Replace All");
System.out.println("Replace Single");
System.out.println("Remove");
System.out.println("Quit");
String choice = input.nextLine();
String[] array = userStr.split("");
if (choice.equalsIgnoreCase("Print Reverse")) { //reverses the string
for(int i = array.length - 1;i >= 0; i --) {
System.out.print(array[i]);
}
System.out.println();
}
else if (choice.equalsIgnoreCase("Replace All")) { //Replaces all input letters with new letters that user inputs
System.out.println("What letter would you like to replace?");
String ridOf = input.nextLine();
System.out.println("What letter do you want to replace it as?");
String replace = input.nextLine();
String[] newArray = array;
for (int i = 0; i < array.length; i++) {
if(array[i].equals(ridOf)) {
array[i] = replace;
}
}
System.out.println("");
for(int i = 0; i < array.length; i++) {
System.out.print(array[i]);
}
System.out.println("");
}
else if (choice.equalsIgnoreCase("Replace Single")) {
System.out.println("Enter the character to replace?");
String ridOf1 = input.nextLine();
System.out.println("Enter the new character");
String replace1 = input.nextLine();
System.out.println("Which " + ridOf1 + " would you like to replace?");
int choice1 = input.nextInt();
}
This is the section I changed .equalsIgnoreCase compares them ignoring case as expected. Then I made sure the user only entered one char and if more ignore them. Then changed the char remove to be a string of only the first char(because you cannot replace with a char it needs to be a string) then I replaced the char to be removed in the string with nothing essentially removing it and set the user string to the new user string
else if (choice.equalsIgnoreCase("Remove")) {
System.out.println("Enter the character to remove");
String ridOf2 = input.nextLine();
String charRemove = String.valueOf(ridOf2.charAt(0));
userStr = userStr.replaceAll(charRemove, "");//This will replace the first char the enter with nothing
}
End of section
else if (choice.equals("Quit") || choice.equals("quit")) {
System.exit(0);
}
}
}
}
String's replace should do it -
public class Test
{
public static void main(String [] args) {
String s = "Hello World";
s = s.replace(" ", "");
System.out.println(s);
}
}
I want to write a program that count the number of words that starts with capital letters. It only count no. Of capital letter not word try this line
"Hi hOw are yOu"
According to my code output will be 3
But their is only 1 word that starts with capital letter that is 'Hi'...so how can I solve these problem..Please help me with this.
import java.util.*;
class Cap
{
public static void main(String m[])
{
Scanner in=new Scanner(System.in);
String s=new String();
System.out.println("Enter a line:");
s=in.nextLine();
char c;
int ct=0;
for(int i=0;i<s.length();i++)
{
c=s.charAt(i);
if(c>=65 && c<=90)
{
ct++;
}
}
System.out.println("total number of words start with capital letters are :"+ct);
}
}
You should better use scanner.next();, which returns the token up to white space in other way a word.Now, you can check the first character of String returned by next() is in uppercase or not.
For statement This is StackOverflow you will have three tokens, This, is and StackOverflow and you can use String.charAt(0) on this String.
Moreover, you can simply use Character.isUpperCase method to check whether character is in upper case or not.
import java.util.*;
public class program_6
{
public static void main(String[] args)
{
String s1;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the string... ");
s1 = scan.nextLine();
int count=0,i=0,n;
n = s1.length();
System.out.println("Size of the string is... " + n );
if ( null == s1 || s1.isEmpty())
{
System.out.println("Text empty");
}
else
{
if( Character.isUpperCase(s1.charAt(0) ))
{
count++;
}
for (i=1 ; i<n ; i++)
{
if ( Character.isWhitespace(s1.charAt(i-1)) && Character.isUpperCase(s1.charAt(i) ) )
{
count++;
}
}
}
System.out.println("Number of the word wich starts with capital latter... " + count );
}
}
Currently you are counting all the capital letters that are entered.
What you want to do is split the line on space and check only for the first letter if it is capital.
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
String s;
System.out.println("Enter a line:");
s=in.nextLine();
int ct=0;
for(String str: s.split(" ")) {
if(str.charAt(0)>=65 && str.charAt(0)<=90)
{
ct++;
}
}
System.out.println("total number of words start with capital letters are :"+ct);
}
You are comparing each character.Instead you can add a space at the begining of the string and check each character after space if it is in uppercase.
Scanner in = new Scanner(System. in );
String s = new String();
System.out.println("Enter a line:");
s = " " + in .nextLine().trim();
char c;
int ct = 0;
for (int i = 1; i < s.length(); i++) {
c = s.charAt(i);
if (c >= 65 && c <= 90 && s.charAt(i - 1) == 32) {
ct++;
}
}
System.out.println("total number of words start with capital letters are :" + ct);
DEMO
or better use scanner.next() as said by TAsk
Try this:
Scanner in = new Scanner(System.in);
String s = new String();
System.out.println("Enter a line:");
s = in.nextLine();
char c;
int ct = 0;
for (int i = 0; i < s.length(); i++) {
c = s.charAt(i);
if (Character.isUpperCase(c)
&& (i == 0 || Character.isWhitespace(s.charAt(i - 1)))) {
ct++;
}
}
System.out
.println("total number of words start with capital letters are :"
+ ct);
First of all we check on the first position whether it is starts with capital letter or not and it is only for the string which starts with capital letter... If yes then the count will be incremented. Next condition( Which is used for string which start with blank space or any other string) will check that left position must have blank space to start new word and the character must be capital to increment the count variable...
import java.util.*;
public class program_6
{
public static void main(String[] args)
{
String s1;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the string... ");
s1 = scan.nextLine();
int count=0,i=0,n;
n = s1.length();
System.out.println("Size of the string is... " + n );
if ( null == s1 || s1.isEmpty())
{
System.out.println("Text empty");
}
else
{
if( Character.isUpperCase(s1.charAt(0) ))
{
count++;
}
for (i=1 ; i<n ; i++)
{
if ( Character.isWhitespace(s1.charAt(i-1)) && Character.isUpperCase(s1.charAt(i) ) )
{
count++;
}
}
}
System.out.println("Number of the word wich starts with capital letter... " + count );
}
}