Java program involving substring() and charAt() methods - java

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));
}
}

Related

Missing While loop logic

found this code on the internet, it's missing the while loop logic "while(i....)" for some reason and though I found other working solutions for the PigLatin* problem, I really want to understand how this one is working.
*PigLatin problem: take a sentence, take the first letter from each word and place it at the end of the same word, then suffix "ay". So "I am confused" becomes "Iay maay onfusedcay".
Here is the code:
import java.util.*;
public class PigLatin {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter an English sentence: ");
String sentence = input.nextLine();
System.out.println("Original sentence: "+sentence);
System.out.println("PigLatin conversion: "+convert(sentence));
}
private static String convert (String sentence) {
String []words = sentence.split(" ");
int i = 0;
String pigLatin = "";
while(i ){ //MISSING CODE
pigLatin+=words[i].substring(1,words[i].length())+words[i].charAt(0)+"ay"+" ";
i++;
}
return pigLatin;
}
}
Thank you.
PS: I basically found the "convert" method on the internet and wrote the rest of the code, tried a few things but could not get the while loop to work.
The loop appears to be iterating the words array. So it should just be something like
while(i < words.length) {
pigLatin += words[i].substring(1, words[i].length())
+ words[i].charAt(0) + "ay ";
i++;
}
import java.util.Scanner;
public class PigLatin {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter an English sentence: ");
String sentence = input.nextLine();
System.out.println("Original sentence: "+sentence);
System.out.println("PigLatin conversion: "+convert(sentence));
}
private static String convert (String sentence) {
String []words = sentence.split(" ");
int i = 0;
String pigLatin = "";
while(i<words.length){ //CORRECTION CODE
pigLatin+=words[i].substring(1,words[i].length())+words[i].charAt(0)+"ay"+" ";
i++;
}
return pigLatin;
}
}

Using for-loops to replace a certain character

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:";
}
}

How to print the middle name in reverse order?

The problem I am having is that when I enter for example Gina Charlene Doe it will print out enelr.
import java.util.Scanner;
import java.io.*;
public class test_1
{
static Scanner in = new Scanner(System.in);
public static void main() {
String name, middle;
System.out.println("Enter your first, middle, and last name ");
name=in.nextLine();
int space1=name.indexOf(" ");
int space2=name.lastIndexOf(" ");
middle=name.substring(space1+1,space2);
for (int x=middle.length();x>=space1;x--)
{
System.out.print(middle.substring(x-1,x));
}
}
}
Sorry I am new to posting things to here so I hope it's formatted well enough.
Based on your output, your loop is working but terminating too early. So something is wrong with your for loop
for (int x=middle.length();x>=space1;x--)
Your condition, x>=space1, is the source of error because you set it to 5 here:
int space1=name.indexOf(" ");
So in your loop, it works down your string from 8 and terminates when x = 4, which is midway through your string, obviously not what you want. So the correct fix is
for (int x=middle.length();x>0;x--)
Your for loop is just logically flawed. Here is the correct code
import java.util.Scanner;
public class Middle
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String name, middle, reversed = "";
System.out.println("Enter your first, middle, and last name ");
name=in.nextLine();
int space1=name.indexOf(" ");
int space2=name.lastIndexOf(" ");
middle=name.substring(space1+1,space2);
for(int i=middle.length(); i > 0; i--)
{
reversed = reversed + middle.charAt(i-1);
}
System.out.println(reversed);
}
}
Try this way!
import java.util.Scanner;
public class Middle{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Enter your first, middle and last name.");
String[] name = in.nextLine().split(" ");
for(int i=name[1].length()-1; i>=0; i--){
System.out.print(name[1].charAt(i));
}
}
}
How to print the middle name in reverse order?
The straight answer is new StringBuilder(middle).reverse().toString();
Solution:
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
// input
System.out.println("Enter your first, middle, and last name ");
String fullname = in.nextLine();
// split
String[] fullnameArray = fullname.trim().split("\\s");
// parse
String first = fullnameArray[0];
String middle = fullnameArray[1];
String last = fullnameArray[2];
// reverse middle name
String middleReversed = new StringBuilder(middle).reverse().toString();
// output
System.out.println("First name:" + first);
System.out.println("middle name (reversed):" + middleReversed);
System.out.println("last name:" + last);
}

Accept a sentence and print the words that have same consecutive characters

Here is my homework:
accept a sentence and print the words that have consecutive characters equal
INPUT: an apple a day keeps
OUTPUT: apple keeps
Here is what I am working on:
import java.util.*;
public class Program1
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a sentence");
String s=sc.nextLine();
String str=s.toLowerCase();
int l,i=0; char c,d;int a,b,m=0;int n=0; String r=""; String res="";
l=s.length();
str=" "+str+" ";
for(i=0;i<(l-1);i++)
{
c=str.charAt(i);
d=str.charAt(i+1);
a=c;
b=d;
m=str.indexOf(' ');
n=str.indexOf(' ',(i+1));
if(d==' ')
{
m=str.indexOf(' ',(i-1));
n=str.indexOf(' ',(i+1));
}
if(a==b)
{
r=str.substring(m,n);
res=res +" "+ r;
}
}
System.out.println(res);
}
}
It gets compiled, but it does not give correct output.
If I enter the above example, it returns:
an apple an apple a day keeps
What do I need to do?
You can do something like this to achieve the result,
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence");
String s = sc.nextLine();
String str = s.toLowerCase();
String[] words = str.split(" "); // Split the sentence into an array of words.
for(String ss : words){
char previousChar = '\u0000';
for (char c : ss.toCharArray()) {
if (previousChar == c) { // Same character has occurred
System.out.println(ss);
break;
}
previousChar = c;
}
}
The problem is in the line:
m=str.indexOf(' ');
you start aat the beginning of the sentence every time, so you print the sentence from beginning to the word you want.
This is my proposal. :-D
Input: mi aasas es mass pp
Output: aasas mass pp
import java.util.*;
public class code10
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a sentence");
String s=sc.nextLine();
String str=s.toLowerCase();
String cadena = str;
String delimitadores= "[ .,;?!¡¿\'\"\\[\\]]+";
String[] palabrasSeparadas = cadena.split(delimitadores);
for(int x=0; x<palabrasSeparadas.length; x++)
{
char[] tmpstr = palabrasSeparadas[x].toCharArray();
for(int y=0; y<tmpstr.length; y++)
{
if((y+1) < tmpstr.length)
{
if(tmpstr[y] == tmpstr[y+1])
{
System.out.print(palabrasSeparadas[x] + " ");
}
}
}
}
System.out.println("");
}
}

Getting the number of occurrences of one string in another string

I need to input a two strings, with the first one being any word and the second string being a part of the previous string and i need to output the number of times string number two occurs. So for instance:String 1 = CATSATONTHEMAT String 2 = AT. Output would be 3 because AT occurs three times in CATSATONTHEMAT. Here is my code:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word8 = sc.next();
String word9 = sc.next();
int occurences = word8.indexOf(word9);
System.out.println(occurences);
}
It outputs 1 when I use this code.
Interesting solution:
public static int countOccurrences(String main, String sub) {
return (main.length() - main.replace(sub, "").length()) / sub.length();
}
Basically what we're doing here is subtracting the length of main from the length of the string resulting from deleting all instances of sub in main - we then divide this number by the length of sub to determine how many occurrences of sub were removed, giving us our answer.
So in the end you would have something like this:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word8 = sc.next();
String word9 = sc.next();
int occurrences = countOccurrences(word8, word9);
System.out.println(occurrences);
sc.close();
}
You could also try:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word8 = sc.nextLine();
String word9 = sc.nextLine();
int index = word8.indexOf(word9);
sc.close();
int occurrences = 0;
while (index != -1) {
occurrences++;
word8 = word8.substring(index + 1);
index = word8.indexOf(word9);
}
System.out.println("No of " + word9 + " in the input is : " + occurrences);
}
Why no one posts the most obvious and fast solution?
int occurrences(String str, String substr) {
int occurrences = 0;
int index = str.indexOf(substr);
while (index != -1) {
occurrences++;
index = str.indexOf(substr, index + 1);
}
return occurrences;
}
Another option:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word8 = sc.next();
String word9 = sc.next();
int occurences = word8.split(word9).length;
if (word8.startsWith(word9)) occurences++;
if (word8.endsWith(word9)) occurences++;
System.out.println(occurences);
sc.close();
}
The startsWith and endsWith are required because split() omits trailing empty strings.

Categories