Simple space trimming program - java

I have this java code to trim all spaces in a String for me.
import java.util.Scanner;
import java.util.Arrays;
public class trimSpace {
public static void main( String[] args ) {
Scanner input = new Scanner(System.in);
String str;
System.out.print("Please enter a string:");
str = input.nextLine();
System.out.println("The result is : ");
char[] charArray = new char[A.length()];
for(int i=0;i<A.length();i++){
if (A.charAt(i) != ' ') { //This line should ignore the space in the str
charArray[i] = A.charAt(i);
System.out.print(charArray[i]);
}
}
//Expected output [j,a,v,a,,,]
System.out.println(Arrays.toString(charArray)); //Output [j," ",A," ",V," ",A]
}
}
If I insert "J A V A" into str, the charArray still include the spaces after printing i.e. [j," ",A," ",V," ",A] What am I doing wrong here?

You put the "correct characters" into the same index where you found them. That way you skip the spaces and leave them.
charArray[i] = A.charAt(i);
System.out.print(charArray[i]);
You need to add a counter in charArray:
charArray[counter++] = A.charAt(i);
That way you'll only advance in charArray if the input was not a space. Or more complete:
int counter = 0;
for(int i=0;i<A.length();i++){
if (A.charAt(i) != ' ') { //This line should ignore the space in the str
charArray[counter++] = A.charAt(i);
}

You can try this:
String str = "J A V A";
str = str.replaceAll("\\s+", "");

Related

ArrayIndexOutOfBoundsException when finding words in an array that and with a specific letter

I am trying to find words in an array that end with a letter 'a'. I thought of doing it using two for loops but I keep getting integer out of bounds error.
Could anyone tell me what i am doing wrong?
The code:
Scanner sc = new Scanner(System.in);
System.out.println("Enter text: ");
String text = sc.nextLine();
String[] words = text.split(" ");
for (int i = 0; i < words.length; i++) {
words[i] = words[i] + " ";
}
for (int i = 0; i < words.length ; i++) {
for (int j = 0; j <= words[i].charAt(j); j++) {
if (words[i].charAt(j) == 'a' && words[i].charAt(j + 1) == ' ') {
System.out.println(words[i]);
}
}
}
You've got too much code for the task, which has lead to a bug creeping in and hiding in plain sight. As a general rule, keeping code as simple as possible results in less bugs.
Delete this, which you don't need.
for (int i = 0; i < words.length; i++) {
words[i] = words[i] + " ";
}
And delete all of this:
for (int j = 0; j <= words[i].charAt(j); j++) {
if( words[i].charAt(j) == 'a' && words[i].charAt(j + 1) == ' '){
System.out.println(words[i]);
}
}
instead basing your code on endsWith("a"):
for (String word : words) {
if (word.endsWith("a")) {
System.out.println(word);
}
}
which is easy to read and understand (and thus easier to avoid bugs).
Even simpler, since you don't need to reference the array, use the result of the split directly:
String text = sc.nextLine();
for (String word : text.split(" ")) {
if (word.endsWith("a")) {
System.out.println(word);
}
}
In your second for loop, you are checking against the character at the current position, not the length of the word. Change the condition to words[i].length()to fix it.
In order to check if some words end with character a, we can do the following:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Read the input
System.out.println("Enter text: ");
String text = sc.nextLine();
// Split the input by spaces
String[] words = text.split(" ");
// Iterate through the array of words and check if any of those ends with "a"
for (String word : words) {
if (word.endsWith("a")) {
System.out.println(word);
}
}
}
It would be simple as that, we don't really need an embedded loop.
Try this instead
String[] words = {"apple", "ada", "cat", "material", "recursion", "stacksa"};
for (int i = 0; i < words.length; i++) {
// get each word first
String word = words[I];
int lenOfWord = word.length();
// check the last item in the word
if (word.charAt(lenOfWord - 1) == 'a') {
System.out.println("Last char is a" + word);
}
}
Other answers explain the logic via loops. Another approach to do the same could be through Java streams:
Scanner sc = new Scanner(System.in);
System.out.println("Enter text: ");
String text = sc.nextLine();
String[] words = text.split(" ");
Arrays.stream(words).filter(w -> w.endsWith("a")).forEach(System.out::println);

to print all the words in a string which starts and ends with same letter in java

*
import java.util.*;
class Word{
void main(){
char ch='\u0000',firstc,lastc;
int c=0,lw; String w="",s1="";
Scanner in = new Scanner(System.in);
System.out.println("Enter a String");
String n = in.nextLine();n=n+"";
for (int i=0;i<n.length();i++){
ch = n.charAt(i);
if(ch!=' '){
w=w+ch;
}else{
firstc = w.charAt(0);
lastc = w.charAt(w.length()-1);
if(firstc==(lastc))
s1=s1+w;
System.out.println(""+s1);
}
}
w=" ";
}
}
*
Now the output comes for one string like if I give MADAM HAVE A MODEM as input it only gives me MADAM as output.
You have to split your "in" string by spaces " ".
After that, if both characters at the start and at the end.
Notice String.charAt() method will get characters from position 0 (start) to the string lenght - 1.
Scanner in = new Scanner(System.in);
System.out.println("Enter a String");
String n = in.nextLine();
String[] parts = n.split(" ");
for(String part : parts) {
if(part.charAt(0)==part.charAt(part.length()-1)) {
System.out.println(part);
}
}
Your code is overly complicated. It would be much simpler to either split the string on space or just read one word at a time:
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
// Get next word
String s = in.next();
if (Character.toLowerCase(s.charAt(0)) == Character.toLowerCase(s.charAt(s.length() - 1))) {
System.out.println(s);
}
}
But back to your code, I see these issues.
It will always skip the last word
You reset w outside of the for and it should be w = "";
Your indentation is really bad
Your code fixed (well, at least working):
char firstc, lastc;
String w = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a String");
String n = in.nextLine();
for (int i = 0; i < n.length(); i++) {
ch = n.charAt(i);
if (ch != ' '){
w = w + ch;
}
if (ch == ' ' || i == n.length()-1) {
firstc = w.charAt(0);
lastc = w.charAt(w.length()-1);
if (firstc == lastc) {
System.out.println(w);
}
w="";
}
}

java doubling characters/tripling characters

I am trying to write a Java program that will print letters twice; all other characters, such as spaces, numbers, and punctuation marks, are to be left alone, except for "!" which should be tripled. My program only doubles all characters so I'm not too sure what to do now as I am very new to Java.
This is what I have so far:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a line of text.");
String myStr = scan.nextLine();
if (myStr.length()>0){
String answer = "";
for(int j=0; j<myStr.length(); j++){
char ch = myStr.charAt(j);
answer = answer + ch + ch;
}
System.out.println(answer);
}
else {
System.out.println("Please enter a string longer than 0 characters");
}
}
How about something like this, using each line as IntStream, since char values are just integers;
String myStr = scan.nextLine().chars()
.flatMap(ch -> {
if (ch == '!') {
return IntStream.of(ch, ch, ch);
} else if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
return IntStream.of(ch, ch);
}
return IntStream.of(ch);
})
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
It works great, and so much fun to work with Java streams
You can do this:
String str = "abc!123";
for(int x=0; x<str.length(); x++)
if(str.substring(x, x+1).matches("[a-zA-Z+]")) //if is alphabet
System.out.print(str.substring(x, x+1) + str.substring(x, x+1));
else if (str.substring(x, x+1).equals("!"))
System.out.print("!!!");
else
System.out.print(str.substring(x, x+1));
A rather straight forward approach which works accordingly to what you currently is doing. check whether a character is alphabet, print twice. If it is !, print 3 times. Else print the respective character once.
Input:
abc!123
Output:
aabbcc!!!123
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
String str = input.nextLine();
doubleStr(str);
}
public static void doubleStr(String s)
{
char[] array = s.toCharArray();
for(char a: array)
{
if(a>='0' && a<='9')
{
System.out.print(a);
}else if(a=='!')
{
for(int i=0; i<=2; i++)
{
System.out.print(a);
}
}
else
{
for(int i=0; i<=1; i++)
{
System.out.print(a);
}
}
}
}
Result
Original: abc ! 9
aabbcc !!! 9
A simple for loop of the characters will do it. Assuming you might want the result for other than simple printing, a transformation method returning the result would be better. That will also allow unit testing, if needed.
private static String transform(CharSequence input) {
StringBuilder buf = new StringBuilder(input.length());
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
buf.append(ch);
if (ch == '!')
buf.append(ch).append(ch);
else if (Character.isLetter(ch))
buf.append(ch);
}
return buf.toString();
}
Test
System.out.println(transform("abc234&#!ff"));
System.out.println(transform("He said: \"You can't do that!\""));
Output from Ideone
aabbcc234&#!!!ffff
HHee ssaaiidd: "YYoouu ccaann'tt ddoo tthhaatt!!!"
Very Simply you can do it like this: Use regex, no need to any kind of loop.
Just Edit this line:
String answer = myStr.replaceAll("(\\p{Alpha}|(!))", "$1$1$2");
Usage:
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a line of text.");
String myStr = scan.nextLine();
if (myStr.length()>0){
String answer = myStr.replaceAll("(\\p{Alpha}|(!))", "$1$1$2");
System.out.println(answer);
}
else {
System.out.println("Please enter a string longer than 0 characters");
}
}
And the result: It is just what you want.
Input: abc234&#!ff
Output: aabbcc234&#!!!ffff

java program to count the number of words that starts with capital letters

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

Replacing a character in a scanner string

So for an assignment I'm supposed to create a program that doubles every letter and triples every exclamation mark of a phrase that is inputted into a scanner. Here is what I got so far:
import java.util.Scanner;
public class DoubleLetters{
public static void main(String[]args){
Scanner scan = new Scanner(System.in);
System.out.println("Enter a statement");
String x = scan.nextLine();
String y = x.replace("! ","!!! ");
for(int j=0; j< x.length(); j++){
System.out.print(y.charAt(j));
System.out.print(y.charAt(j));
}
}
}
Doubling the letters work, but not tripling the exclamation marks. I tried to use the replace method and it did not work. Please, any help is appreciated.
Just add if statement inside a loop
if(y.charAt(j) == '!') {
System.out.print(y.charAt(j));
}
and remove empty spaces in replace method
String y = x.replace("!","!!!");
try this
String y = x.replace("!","!!!");
or this
for (char c : x.toCharArray()) {
System.out.print(c);
System.out.print(c);
if (c == '!') {
System.out.print(c);
}
}
Convert String into char array than do double and triplet and display . Start reading from left hand side and move to right hand side using double and triplet condition update char array and finally display result(char array) .
You could go over all the characters and append them to a StringBuilder:
String str = /* recieved from scanner */
StringBuidler builder = new StringBuilder();
for (char c : str.toCharArray()) {
// Any character needs to be included at least once:
builder.append(c);
// If it's a letter, you need another copy (total of 2)
if (Character.isLetter(c)) {
builder.append(c);
// If it's an excalmation mark, you need another two copies (total of 3)
} else if (c == '!') {
builder.append(c);
builder.append(c);
}
}
System.out.println(builder);
System.out.print(y.charAt(j));
System.out.print(y.charAt(j));
}
Try the follwing code, it will work efficiently as you like,
import java.util.Scanner;
public class DoubleLetters
{
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a statement");
String x = scan.nextLine();
for(int j=0; j< x.length(); j++)
{
if(y.charAt(j)=='!')
System.out.println("!!!");
else
{
System.out.print(y.charAt(j));
System.out.print(y.charAt(j));
}
}
}
}
As u havn't succeeded to replace '!' . so for a another approach instead of replace you can tokenize your string using StringTokenizer as this piece of code. and by this u can add what u want as for your case at the end of each ! u can add 2 more !!. code as.
System.out.println("---- Split by comma '!' ------");
String s = "My Name !is !Manmohan"; //scanner string
System.out.println("---- Split by comma ',' ------");
StringTokenizer st2 = new StringTokenizer(s, "!");
String now = "";
while (st2.hasMoreElements()) {
now += st2.nextElement() + "!!!";
}
System.out.println(now.substring(0, now.length() - 3));
//op ... My Name !!!is !!!Manmohan

Categories

Resources