Using for-loops to replace a certain character - java

The purpose of my code is to ask the user for a string, but the user has to use the number "2" to replace the word "to". Then, in my method useProperGrammar, the program should replace the number "2" for the word "to". The method returns the corrected sentence along with the number of errors fixed, which indicates the purpose of the variable counter. However, when I execute my code, the corrected code nor the number of grammar mistakes is displayed, what is the problem with my method? I know I can use the static method ".replace()", but I wanted to know if there were any other ways to solve this problem.
import java.util.Scanner;
public class Grammar
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a sentence (replace \"to\" for the number \"2\")");
String begin = input.nextLine();
System.out.println(useProperGrammar(begin));
}
public static String useProperGrammar(String sentence)
{
int counter = 0;
for(int i = 0; i<sentence.length(); i++)
{
String character = sentence.substring(i, i+1);
if(character.equals("2"));
{
String front = sentence.substring(0, i);
String back = sentence.substring(i+1);
sentence = front + " to " + back;
counter++;
}
}
return sentence + "\nFixed " + counter + "grammatical errors:";
}
}

you need to remove the ; after if(character.equals("2"))
import java.util.Scanner;
public class Grammar
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a sentence (replace \"to\" for the number \"2\")");
String begin = input.nextLine();
System.out.println(useProperGrammar(begin));
}
public static String useProperGrammar(String sentence)
{
int counter = 0;
for(int i = 0; i<sentence.length(); i++)
{
String character = sentence.substring(i, i+1);
if(character.equals("2"))
{
String front = sentence.substring(0, i);
String back = sentence.substring(i+1);
sentence = front + " to " + back;
counter++;
}
}
return sentence + "\nFixed " + counter + "grammatical errors:";
}
}

Related

I have a problem with methods on Java could I have some advice?

I was given the task of splitting my program which outputted the longest word in a sentence into a number of methods within the same class. I keep on trying out different ways but none seem to work. Could someone help me out?
This is the program:
import java.util.Scanner;
public class Test{
public static str getUserInput(Scanner sc) {
System.out.print("Enter a string or sentence: ");
// Return the string inputted by the user
return sc.nextLine();
return str;
}
public static void getlongestWord(str) {
Scanner str2 = new Scanner(str);
//Initialise longestWord with the first word in str
String longestWord = str2.next();
//Initiaise maxlen with length of first word in str
int maxlen = longestWord.length();
while(str2.hasNext()) //This loop will keep running till words are present
{
String word = str2.next(); //Storing next word in variable
int len = word.length(); //Storing word's length
if(len>maxlen) //If this length is more than maxlen, longestWord and maxlen are changed
{
longestWord = word;
maxlen = len;
}
}
return longestWord;
return maxlen;
}
int longestWord;
int maxlen;
public static void getOutput (int longestWord) {
System.out.println("The longest word is '" + longestWord );
}
public static void getOuput2 (int maxlen){
System.out.println ("of length "+maxlen+" characters.");
}
}
I left some comments in your code:
import java.util.Scanner;
public class Test {
public static str getUserInput(Scanner sc) { // The return type should be of type String and not str.
System.out.print("Enter a string or sentence: ");
return sc.nextLine();
return str; // you can't have a return statement immediately after another return statement :)
}
public static void getlongestWord(str) { // The method parameter is not of a valid type (it is not String)
Scanner str2 = new Scanner(str);
String longestWord = str2.next();
int maxlen = longestWord.length();
while(str2.hasNext())
{
String word = str2.next();
int len = word.length();
if(len>maxlen)
{
longestWord = word;
maxlen = len;
}
}
return longestWord;
return maxlen; // you can't have a return statement immediately after another return statement :)
}
int longestWord; // Instance variables should be declared at the top of the class
int maxlen;
public static void getOutput(int longestWord) { // Methods named {getSomething()} should return that something. This method returns void.
System.out.println("The longest word is '" + longestWord);
}
public static void getOuput2(int maxlen) { // Focus on proper naming.
System.out.println("of length " + maxlen + " characters.");
}
}
I also wrote my own version of what you are trying to do:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
System.out.print("Enter a string or sentence: ");
Scanner sc = new Scanner(System.in);
processInput(sc);
}
public static void processInput(Scanner sc) {
String sentence = sc.nextLine();
String longestWord = findLongestWord(sentence);
printInfo(longestWord);
}
public static String findLongestWord(String sentence) {
String longest = "";
for (String currentWord : sentence.split(" ")) {
if (longest.length() < currentWord.length())
longest = currentWord;
}
return longest;
}
public static void printInfo(String longestWord) {
System.out.println("The longest word is '" + longestWord);
System.out.println("of length " + longestWord.length() + " characters.");
}
}
My solution is in no way a perfect solution so you could go ahead and understand the changes I made, and then implement your own changes.
Remember: every class and method should be responsible for one thing only.
A simple way to do it is to split the string on whitespace and then iterate the resulting array to find the longest word. To find the longest word, you can start with the assumption that the first word is the longest and store it in a variable (e.g. String longestWord) and whenever a word longer than this is encountered, replace the stored word with that word.
public class Main {
public static void main(String[] args) {
// Test string
String str = "Stack Overflow is the largest, most trusted online community for developers to learn, share​ ​their programming ​knowledge, and build their careers.";
System.out.println("The longest word in the sentence: " + getLongestWord(str));
}
static String getLongestWord(String str) {
// Split the string on whitespace
String[] arr = str.split("\\s+");
// Start with the assumption that the first word is longest
String longestWord = arr[0];
int maxLen = longestWord.length();
for (String s : arr) {
if (s.length() > maxLen) {
maxLen = s.length();
longestWord = s;
}
}
return longestWord;
}
}
Output:
The longest word in the sentence: programming

There is a logic error in a simple counting algorithm in my java code

So there is a logic error inside my simple java counting words, first of in cmd, it's asking me to type the string twice, when it should show once
I run this in cmd, here is the output:
C:\Users\Me\Documents>java count
shapeshifting
shapeshifting
Number of Occurrence of s is 2 in string shapeshifting
s
2
import java.util.Scanner;
public class count5 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();
char key = input.nextLine().charAt(0);
countString(str, key);
}
public static void countString(String str, char key) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == key)
count++;
}
System.out.println("Number of Occurrence of "
+ key + " is " + count + " in string " + str);
for (int i = 0; i < count; i++) {
System.out.println(key);
}
if (count > 0) {
System.out.println(count);
}
}
}
So here some thing that confuses me:
why is there 3 lines needed allow user to type an input. I thought the previous line already let me enter the input. What is char key = input.nextLine().charAt(0); needed for, and the previous line? Shouldn't there be only input entering line?
Why is there 2 for loops inside the code, don't they do same thing?
Try this solution which should ask for one time input and traverse the complete input string entered for the match
import java.util.Scanner;
public class stringCompair {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();
for(int i=0 ; i < str.length();i++) {
char key = str.charAt(i);
countString(str, key);
}
}
public static void countString(String str, char key) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == key)
count++;
}
System.out.println("Number of Occurrence of "
+ key + " is " + count + " in string " + str);
}
}

Java Splitting Strings and Applying A Method

I'm working on a code in java that will swap a random letter inside of a word with another random letter within that word.
I need to apply this code to an entire string. The issue I'm having is my code can't identify white space and therefore runs the method for once per string instead of once per word. How can I split the input string and apply the method to each word individually. Here's what I have so far.
import java.util.Scanner;
import java.util.Random;
public class Main {
public static void main(String[] args {
Scanner in=new Scanner(System.in);
System.out.println("Please enter a sentance to scramble: ");
String word = in.nextLine();
System.out.print(scramble(word));
}
public static String scramble (String word) {
int wordlength = word.length();
Random r = new Random();
if (wordlength > 3) {
int x = (r.nextInt(word.length()-2) + 1);
int y;
do {
y = (r.nextInt(word.length()-2) + 1);
} while (x == y);
char [] arr = word.toCharArray();
arr[x] = arr[y];
arr[y] = word.charAt(x);
return word.valueOf(arr);
}
else {
return word;
}
}
}
Check the inline comments:
import java.util.Scanner;
import java.util.Random;
public class Main {
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
System.out.println("Please enter a sentance to scramble: ");
String word = in.nextLine();
//Split your input phrase
String[] wordsArray = word.split(" ");
//For each word in the phrase call your scramble function
// and print the output plus a space
for (String s : wordsArray){
System.out.print(scramble(s) + " ");
}
}
public static String scramble (String word) {
int wordlength = word.length();
Random r = new Random();
if (wordlength > 3) {
int x = (r.nextInt(word.length()-2) + 1);
int y;
do {
y = (r.nextInt(word.length()-2) + 1);
} while (x == y);
char [] arr = word.toCharArray();
arr[x] = arr[y];
arr[y] = word.charAt(x);
return word.valueOf(arr);
}
else {
return word;
}
}
}
As destriped in teh String.split(); you can define a regrex for instance " " and then a return array of String[] for all substrings split on the input is returned
see String split
example
String in = "hello world";
String[] splitIn = in.split(" ");
The same way you can test for other things such as "," "." ";" ":" etc

Palindrome checker - What am i doing wrong?

I am to create a program that checks for palindromes in a sentence and display the palindromes that have been found. My following code keeps giving me a "String is out of bounds" error. What am i doing wrong?
My Program:
import javax.swing.JOptionPane;
public class Palindromechkr {
public static void main(String[] args) {
//Declare Variables
String Palin, input, Rinput = "";
int wordlength, spacePos;
//Ask for sentance
input = JOptionPane.showInputDialog("enter a sentance");
//Split string
spacePos = input.indexOf(" ");
String word = input.substring(0, spacePos);
//Get palindromes
System.out.println("Your Palindromes are:");
for (int counter = 0; counter < input.length(); counter++) {
//Reverse first word
wordlength = word.length();
for (int i = wordlength - 1; i >= 0; i--) {
Rinput = Rinput + word.charAt(i);
//Add word to An array of Palindromes
if (Rinput.equalsIgnoreCase(word)) {
Palin = word;
System.out.println("Palin:" + Palin);
break;
}
//Move on to the next word in the string
input = input.substring(input.indexOf(" ") + 1) + " ";
word = input.substring(0, input.indexOf(" "));
}
}
}
}
If you know functions you can use a recursive function to build the palindrome version of a string (it's a common example of how recursion works).
Here's an example:
import javax.swing.JOptionPane;
public class Palindromechkr {
public static void main(String[] args) {
//Declare Variables
String Palin, input, Rinput = "";
int wordlength, spacePos;
//Ask for sentance
input = JOptionPane.showInputDialog("enter a sentance");
String[] words = input.split(" +"); // see regular expressions to understand the "+"
for(int i = 0; i < words.length; i++) { // cycle through all the words in the array
Rinput = makePalindrome(words[i]); // build the palindrome version of the current word using the recursive function
if(Rinput.equalsIgnoreCase(words[i])) {
Palin = words[i];
System.out.println("Palin: " + Palin);
}
}
}
// this is the recursive function that build the palindrome version of its parameter "word"
public static String makePalindrome(String word) {
if(word.length() <= 1) return word; // recursion base case
char first = word.charAt(0); // get the first character
char last = word.charAt(word.length()-1); // get the last character
String middle = word.substring(1, word.length()-1); // take the "internal" part of the word
// i.e. the word without the first and last characters
String palindrome = last + makePalindrome(middle) + first; // recursive call building the palindrome
return palindrome; // return the palindrome word
}
}
You should have done is
public static void main(String[] args) {
String Palin, input, Rinput = "";
input = new Scanner(System.in).nextLine();
//Split string
for(String str : input.split(" ")){
for (int counter = str.length()-1; counter >= 0; counter--) {
Rinput = Rinput + str.charAt(counter);
}
if (Rinput.equalsIgnoreCase(str)) {
Palin = str;
System.out.println("Palin:" + Palin);
}
Rinput="";
}
}
I don't know if you are aware but StringBuilder has a reverse method to it. Which can be used like this :
public static void main(String[] args) {
String input;
input = new Scanner(System.in).nextLine();
//Split string
for(String str : input.split(" ")){
if (new StringBuilder(str).reverse().toString().equalsIgnoreCase(str)) {
System.out.println("Palin:" + str);
}
}
}

Java program involving substring() and charAt() methods

My program is supposed to print out the initials of the name and print the last name.
Eg. if the name entered is Mohan Das Karamchand Gandhi, the output must be MDK Gandhi. Although I get a "String index out of range" exception.
import java.util.Scanner;
public class name {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("Enter a string");
String w=s.nextLine();
int l=w.length();
char ch=0; int space=0;int spacel = 0;
for(int i=0;i<l;i++){
ch=w.charAt(i);
if(ch==32||ch==' '){
space+=1;
spacel=i+1;
System.out.print(w.charAt(spacel) + " ");
}
}
System.out.println(w.substring(spacel,l+1));
}
This is the culprit:
spacel=i+1;
System.out.print(w.charAt(spacel) + " ");
When i is equal to l - 1, then space1 is going to be equal to l or w.length(), which is beyond the end of the string.
This can be easily achieved using String's split() method or using StringTokenizer.
First split string using space as delimiter. Then according to your format last string would be Last Name and iterate over other string objects to get initial characters.
String name = "Mohan Das Karamchand Gandhi";
String broken[] = name.split(" ");
int len = broken.length;
char initials[] = new char[len-1];
for(int i=0;i<len-1;i++) {
initials[i] = broken[i].charAt(0);
}
String finalAns = new String(initials)+" "+broken[len-1];
import java.util.Scanner;
public class name
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("Enter a string");
String w=s.nextLine();
int l=w.length();
char ch=0; int space=0;int spacel = 0;
System.out.print(w.charAt(0) + " ");
for(int i=0;i<l;i++)
{
ch=w.charAt(i);
if(ch==32||ch==' ')
{
space+=1;
spacel=i+1;
System.out.print(w.charAt(spacel) + " ");
}
}
System.out.println("\b\b"+w.substring(spacel,l));
}
}

Categories