In my assignment I need to get this output:
Enter a word: house
What letter do you want to replace?: e
With what letter do you wish to replace it? w
The new word is housw.
_____________________________________________.
I got the program to work with this code, but now I need to set while loops. Here is my current code.
String word = "";
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a word: " + word);
word = keyboard.nextLine();
String readChar = null;
System.out.print("What letter do you want to replace?: ");
readChar = keyboard.next();
String changeChar;
System.out.print("With what letter do you wish to replace it? ");
changeChar = keyboard.next();
keyboard.close();
System.out.println(word.replaceAll(readChar, changeChar));
System.out.println();
I need to now make my program output this:
Enter a word: house
What letter do you want to replace?: a
There is no a in house.
What letter do you want to replace?: b
There is no a in house.
What letter do you want to replace?: e
With what letter do you wish to replace it? w
The new word is housw.
How would my while loop look to portray this output?
After you read the word and the character you want to replace (plus the character you want to replace it with) you can use replace method from the String class.
Here is an example usage (adapt the variable names to your code)
word = word.replace(letterToReplace, replacementLetter);
So for example
String word = "aba";
word = word.replace('a', 'c');
System.out.println(word); // Prints out 'cbc'
Also here is an obligatory link to the JavaDoc for the replace method:
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replace%28char,%20char%29
Okay this is one possible way to implement the edited second part of the question:
public static void main(String[] args) {
String word = "";
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a word: " + word);
word = keyboard.nextLine();
boolean done = false;
do{
String readChar = null;
System.out.print("What letter do you want to replace?: ");
readChar = keyboard.next();
if(word.contains(readChar)){
String changeChar;
System.out.print("With what letter do you wish to replace it? ");
changeChar = keyboard.next();
done = true;
keyboard.close();
System.out.println(word.replace(readChar, changeChar));
}
}
while(!done);
}
I hope you don't mind hard interpretation,Below is the example you can follow the same.
String a = "HelloBrother How are you!";
String r = a.replace("HelloBrother","Brother");
print.i(r);
If you want to replace all of the letters, you can do it like this (working code):
public static void main(String[] args) {
String word = "";
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a word: " + word);
word = keyboard.nextLine();
String readChar = null;
System.out.print("What letter do you want to replace?: ");
readChar = keyboard.next();
String changeChar;
System.out.print("With what letter do you wish to replace it? ");
changeChar = keyboard.next();
keyboard.close();
System.out.println(word.replace(readChar, changeChar));
}
This illustrates what you need to do.
import java.util.Scanner;
public class WordScrambler{
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a word: ");
String word = keyboard.nextLine();
System.out.print("What letter do you want to replace?: ");
char letter = keyboard.next().charAt(0);
StringBuffer out = new StringBuffer(word);
System.out.print("With what letter do you wish to replace it? ");
char changeChar = keyboard.next().charAt(0);
for (int i=0; i<word.length(); ++i)
if(word.charAt(i) == changeChar)
out.setCharAt(i, changeChar);
System.out.println("The new word is "+out);
}
}
Related
I am a beginner to java. I try to write a program to read a series of words from the command-line arguments, and find the index of the first match of a given word. Like user can enter "I love apple", and the given word is "apple". The program will display "The index of the first match of ‘apple’ is 2".
What I did so far does not work. Is it my way of storing the input into the string array not correct?
import java.util.Scanner;
public class test {
public static void main(String [] args) {
System.out.println("Enter sentence: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
int num=1;
String sentence[]=new String[num];
for(int i=0; i< num; i++) {
sentence[i] = input; // store the user input into the array.
num = num+1;
}
System.out.println("Enter the given words to find the index of its first match: ");
Scanner sc2 = new Scanner(System.in);
String key = sc2.next();
for(int j=0; j<num; j++) {
while (sentence[j].equals(key)) {
System.out.println("The index of the first match of "+key+" is "+j);
}
}
}
}
String array is not required in your solution.
Try this :-
System.out.println("enter sentence ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
System.out.println("enter the given word to fin the index ");
sc = new Scanner(System.in);
String toBeMatched = sc.nextLine();
if (input.contains(toBeMatched)) {
System.out.println("index is " + input.indexOf(toBeMatched));
} else {
System.out.println("doesn't contain string");
}
I have made the following changes to make your code work. Note you were storing the input string incorrectly. In your code, the entire code was being stored as the first index in the array. You don't need the first for-loop as we can use the function .split() to distinguish each word into a different index in the array. Rest of the code stays as it is.
public class ConfigTest {
public static void main(String[] args) {
System.out.println("Enter sentence: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
// Use this to split the input into different indexes of the array
String[] sentence = input.split(" ");
System.out.println("Enter the given words to find the index of its first match: ");
Scanner sc2 = new Scanner(System.in);
String key = sc2.next();
for (int i = 0; i < sentence.length; i++) {
if (sentence[i].equals(key)) {
System.out.println("The index of the first match of " + key + " is " + i);
}
}
}
}
I think you have a scope problem. sentence[] is declared and instantiated in your first forloop. Try moving the declaration outside of the loop and you should do away with the error.
I also noticed a couple of errors. You could try this
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Enter Sentence");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String sentence[] = input.split("\\s");
System.out.println("Enter Word");
Scanner sc2 = new Scanner(System.in);
String key = sc2.next();
int index = 0;
for(String word : sentence)
{
if(word.equals(key))
{
System.out.println("The index of the first match of " + key + " is " + index);
break;
}
index++;
}
}
Turtle
sentence variable is only defined inside the for loop, it needs to be declared outside it
You can use the first Scanner (sc) declared variable again instead of declaring another one (sc2)
sentence[i] = input -- will mean -- sentence[0] = "I love apple"
Scanner variable can do all the work for you for the input into the array instead of a for loop
String[] a = sc. nextLine(). split(" ");
This will scan an input of new line and separate each string separated by a space into each array.
System.out.println("Enter sentence: ");
Scanner sc = new Scanner(System.in);
String[] sentence = sc. nextLine(). split(" ");
System.out.println("Enter the given words to find the index of its first match: ");
String key = sc.nextLine();
for(int j=0; j<num; j++) {
if (sentence[j].matches(key)) {
System.out.println("The index of the first match of "+ key +" is "+ j);
}
}
Declare the String [] sentence outside the for loop. It is not visible outside the first for block.
The sentence array is created over and over again during the iteration of the for loop. The loop is not required to get the String from the command line.
Edited my answer and removed the use of any for loops, Arrays.asList() will take the words array and fetch the index of the word from the resulting List.
public static void main(String[] args) throws IOException {
System.out.println("Enter sentence: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
System.out.println("Enter the given word to find the index of its first match: ");
Scanner wordInput = new Scanner(System.in);
String key = wordInput.next();
String[] words = input.split(" ");
int occurence = Arrays.asList(words).indexOf(key);
if(occurence != -1){
System.out.println(String.format("Index of first occurence of the word is %d", occurence));
}
}
You just need to declare sentence array outside the for loop, as for now, the issue is of scope.For more on the scope of a variable in java . Also, this is not you intend to do, you intended to take input as a command line.
So, the input which you will get will come in String[] args. For more on command line arguments check here.
so my problem is that I need to get the user to enter a string. then they will enter a character that they want counted. So the program is supposed to count how many times the character they entered will appear in the string, this is my issue. If someone can give me some information as to how to do this, it'll be greatly appreciated.
import java.util.Scanner;
public class LetterCounter {
public static void main(String[] args) {
Scanner keyboard= new Scanner(System.in);
System.out.println("please enter a word");//get the word from the user
String word= keyboard.nextLine();
System.out.println("Enter a character");//Ask the user to enter the character they wan counted in the string
String character= keyboard.nextLine();
}
}
Here is a solution taken from this previously asked question and edited to better fit your situation.
Either have the user enter a char, or take the first character from
the string they entered using character.chatAt(0).
Use word.length to figure out how long the string is
Create a for loop and use word.charAt() to count how many times your character appears.
System.out.println("please enter a word");//get the word from the user
String word= keyboard.nextLine();
System.out.println("Enter a character");//Ask the user to enter the character they want counted in the string
String character = keyboard.nextLine();
char myChar = character.charAt(0);
int charCount = 0;
for (int i = 1; i < word.length();i++)
{
if (word.charAt(i) == myChar)
{
charCount++;
}
}
System.out.printf("It appears %d times",charCount);
This should do it. What it does is that it gets a string to look at, gets a character to look at, iterates through the string looking for matches, counts the number of matches, and then returns the information. There are more elegant ways to do this (for example, using a regex matcher would also work).
#SuppressWarnings("resource") Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string:\t");
String word = scanner.nextLine();
System.out.print("Enter a character:\t");
String character = scanner.nextLine();
char charVar = 0;
if (character.length() > 1) {
System.err.println("Please input only one character.");
} else {
charVar = character.charAt(0);
}
int count = 0;
for (char x : word.toCharArray()) {
if (x == charVar) {
count++;
}
}
System.out.println("Character " + charVar + " appears " + count + (count == 1 ? " time" : " times"));
I have a question regarding StringBuilder. I'm trying to write a program that takes the user input : for example "DOG DOG CAT DOG DOGCAT", then asks the user to input a word they would like to change and what they would like to change it to. It should then replace all occurrences and print the result.
I have a code:
public class ChangeSentence
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Write text: ");
String text = sc.nextLine();
StringBuilder x = new StringBuilder(text);
System.out.println("Write which word would you like to change: ");
String rep = sc.nextLine();
System.out.println("For what do you want to change it: ");
String change = sc.nextLine();
System.out.println(Pattern.compile(x.toString()).matcher(rep).replaceAll(change));
}
}
How should I change it to achieve the result?
Thanks!
**Forgot to mention, I need to use the StringBuilder (without it i know how to write it).
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Write text: ");
original = sc.nextLine();
//StringBuilder x = new StringBuilder(text);
System.out.println("Write which word would you like to change: ");
String replacableWord = sc.nextLine();
System.out.println("For what do you want to change it: ");
String newWord = sc.nextLine();
String output = original.replace(replacableWord ,newWord);
System.out.println(output);
}
You just use the function replace on the original String and the
first parameter is the target String
the
second parameter is the replacement String
Last line should be replaced by following:
System.out.println(text.replaceAll(rep, change));
It's simple. You have to excercise a little
I am trying to create a program in which a user enters a string (which is put into a char array) and then enters a letter and the program checks if the string contains that letter. Here is my code so far:
Scanner keyboard = new Scanner (System.in);
System.out.println("Please enter a word: ");
String input = keyboard.nextLine();
char[] word = input.toCharArray();
Scanner keyboard1 = new Scanner (System.in);
char letter = keyboard1.findInLine(".").charAt(0);
if (word contains letter) { //This is just used as an example of what I want it to do
System.out.println("The word does contain the letter.");
} else {
System.out.println("The word does not contain the letter.");
}
I realize that the condition in the if statement is not valid, I used it just as an example of what I want it to do.
So my question here is: What can I enter in the if statement condition for it to check if the user entered word contains the user entered letter?
You don't need to convert your first input to a char[], just leave it as a string and use the contains()
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a word: ");
String input = keyboard.nextLine();
System.out.print("Please enter a letter to search in the word: ");
Scanner keyboard1 = new Scanner(System.in);
char letter = keyboard1.nextLine().charAt(0);
// Using toLowerCase() to ignore capital vs lowercase letters.
// Locale may need to be considered.
if (input.toLowerCase().contains(String.valueOf(letter).toLowerCase())) {
System.out.println("The word does contain the letter " + letter + ".");
} else {
System.out.println("The word does not contain the letter " + letter + ".");
}
}
Results:
If you want it on one line:
if (new String(word).indexOf(letter) != -1)
Otherwise use a loop:
boolean found = false;
for (char c : word) {
if (c == letter) {
found = true;
break;
}
}
if (found)
This is what I have so far. I want the program to print out the words the user inputs as a sentence. But
I don't know how I get that to happen with the code I have written so far.
ex: if you entered
Hello
World
done
The program should say: "Hello World"
import java.util.Scanner;
public class Chapter3ProblemsSet {
public static void main(String [] args) {
String word = "";
final String SENTINEL = "done";
double count = 0;
String userInput = "";
Scanner in = new Scanner (System.in);
System.out.println("Please enter words: ");
System.out.println("Enter done to finish.");
word = in.next();
do {
word = in.next();
count++;
System.out.print(" "+word);
}
while (!word.equals(SENTINEL));
System.out.println(" "+word);
}
}
What you need it to store it in a variable which is declared outside the loop.
StringBuilder sentence=new StringBuilder();
do {
word = in.nextLine();
count++;
System.out.print(" "+word);
sentence.append(" "+word);
}
while (!word.equals(SENTINEL));
Then for printing use
System.out.println(sentence.toString());
You will need to create an additional string to "collect" all of the words that the user enters. The problem with your original is that you replace 'word' with the word entered. This should do the trick:
import java.util.Scanner;
public class Chapter3ProblemsSet {
public static void main(String [] args) {
String word = "";
String sentence = "";
final String SENTINEL = "done";
double count = 0;
String userInput = "";
Scanner in = new Scanner (System.in);
System.out.println("Please enter words: ");
System.out.println("Enter done to finish.");
word = in.next();
do {
word = in.next();
count++;
sentence += " " + word;
System.out.print(" "+word);
}
while (!word.equals(SENTINEL));
System.out.println(" "+sentence);
}
}
You can read it by pieces and put them together using a StringBuffer - http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html
StringBuffer sb = new StringBuffer();
do {
sb.append( in.next() );
count++;
}
while (!word.equals(SENTINEL));