Replacing characters in a String - java

import java.util.Scanner;
public class KBstrings1
{
public static void main (String []args)
{
Scanner scan=new Scanner(System.in);
String s1= scan.nextLine();
int num=0;
for(int i=0; i<s1.length();i++)
{
if(s1.charAt(i)=='a'){
num++;}
i++;
}
if(num>3)
{
System.out.println(s1.replace('a','#'));
}
else
{
System.out.println(s1.replace('a','#'));
}
}
}
I want to create a program that accepts user input of a sentence and replaces all the 'a' characters with '#' if there are 3 or less instances of 'a', and replace 'a' with '#' if there are more than 3 instances. I tried using the sentence "Computer science is no more about computers than astronomy is about telescopes." but my output replaced the 'a' with '#' when it should've replaced it with '#'. I do all my code in JCreator.

You are incrementing i twice.
for(int i=0; i<s1.length();i++)
and
i++;

Related

Java app to check anagram using for loop and if statement

I'm working on another coding task for university. I am having trouble using a for loop (with another for loop and an if statement) to take a String parameter, and reorder it in alphabetical order. The task then requires us to check two phrases against each other to check if the phrases are anagrams. The loop is the bit I am stuck with. My for loop should output the first phrase in alphabetical order, but my if statement is not functioning as intended. The boolean statement is incorrect but I am unsure what I should be checking the phrase.charAt(i) against to record the letter.
We are not permitted to use an array to complete this task.
import java.util.Scanner;
public class AnagramApp {
/**Method to reformat string in alphabetical order**/
public static String orderString(String phrase){
String output = "";
for (char alphabet = 'a'; alphabet <='z'; alphabet ++ ){
for (int i = 0; i < phrase.length(); i++){
if (phrase.charAt(i) == i){
output += phrase.charAt(i);
}
}
}
return (output);
}
public static void main(String [] args){
/**Setting scanner object to retrieve user input for both phrases **/
Scanner sc = new Scanner(System.in);
System.out.println("Enter first phrase");
String phrase1 = sc.nextLine();
System.out.println("Enter second phrase");
String phrase2 = sc.nextLine();
/**Send phrases to lower case for parsing to new string in char order**/
phrase1 = phrase1.toLowerCase();
phrase2 = phrase2.toLowerCase();
System.out.println(orderString(phrase1));
System.out.println(orderString(phrase2));
}
}
I think the problem is that you are comparing with the index of the inner loop, i, you want to compare with the index of the outer loop, alphabet.
if (phrase.charAt(i) == alphabet)
change condition in if statement to if (phrase.charAt(i) == alphabet)
or you can use below function to check two string anagram
boolean checkAnagram(String st1, String st2)
{ int arr[]=new int[26];
int l1=st1.length();
int l2=st2.length();
if(l1!=l2){
return false;
}
for(int i=0;i<l1;i++){
arr[st1.charAt(i)-97]+=1;
arr[st2.charAt(i)-97]-=1;
}
for(int i=0;i<25;i++){
if(arr[i]!=0) return false;
}
return true;
}

How to make arrayList read Strings only but not int?

Write a method called countWords that accepts an ArrayList of String as argument and
prints out the number of words (i.e. Strings) that start with ―A‖ or ―a‖ and prints all words longer than 5 characters on one line.
My solution is like
int count=0;
String[] st=null;
Scanner input=new Scanner(System.in);
ArrayList<String> array = new ArrayList<String>();
System.out.println("please input something");
while(input.hasNext()) {
String st1=input.next();
array.add(st1);
}
for(int i=0; i<array.size();i++) {
if(array.get(i).startsWith("a")||array.get(i).startsWith("A")) {
count++;
}
}
for(int j=0; j<array.size(); j++) {
if(array.get(j).length()>5)
st[j]=array.get(j);
}
System.out.println(count);
System.out.println(st);
}
but there will be no end for typing in Strings
As the last line of your question said
but there will be no end for typing in Strings
Well That is because you did not provided any way to end the while loop.
while(input.hasNext())
Will run forever and ever waiting for next user input. You have to break the while loop once the inputting is done.
AFTERWARDS
As the question said "prints out the number of words that start with A or a and prints all words longer than 5 characters on one line."
For this you can loop through the ArrayList and check for
if(array.get(i).startsWith("A") || array.get(i).startsWith("a")) count++;
if(array.get(i).length()>5) System.out.print(array.get(i)+" ");
and print the number of A or a Occurrence after the loop
System.out.println("\n Number of word with A or a:"+count);
Here is a working implementation of your code
public static void main(String[] args) {
int count=0;
String[] st=null;
Scanner input=new Scanner(System.in);
ArrayList<String> array = new ArrayList<String>();
System.out.println("please input something");
//System.out.println(input.hasNext());
while(input.hasNext()) {
String st1=input.next();
//System.out.println((int) st1.charAt(0));
if(st1.equals("exit")) break;
array.add(st1);
}
for(int i=0; i<array.size();i++) {
if(array.get(i).startsWith("A") || array.get(i).startsWith("a")){
count++;
}
if(array.get(i).length()>5) {
System.out.print(array.get(i)+" ");
}
}
System.out.println("\nNumber of word with A or a:"+count);
}
to end the loop you have to type exit.
Here is a solution to your problem..
import java.util.Arrays;
import java.util.List;
public class Test {
public static void main(String... args){
// Sample String sentence
String sentence = "This is the sentence with 5 words starting with
all like allwords alltogether also Allnotout allother and allofus.";
// Splitting above sentence to get each word separately and storing them into List
List<String> strings = Arrays.asList(sentence.split("\\s+"));
// calling a method named countWord() as per your assignment question.
Test.countWords(strings);
}
// implementing that method
static void countWords(List<String> input){
long count = input.stream().filter(word -> word.startsWith("all") || word.startsWith("All")).count();
System.out.print("Total words starting with all/All are : "+ count +"\t");
input.stream().filter(word -> word.length() > 5).forEach( word -> System.out.print(word + "\t"));
}
}

Program accept word as i/p, checks for each single character letter in word consonant/vowel. Condition Print error message if input is not letter

Output should be printing only once, but can't figure it out to get it out of loop once i find the VOWEL.
Go on by giving input 'a' once then 'aft'. You will know what i actually want...
package com.java;
import java.util.Scanner;
public class three {
#SuppressWarnings("resource")
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.println("Enter String");
String a = s.next();
char b[] = a.toCharArray();
///char c[] = {"a","e","i","o","u"};
String str = "aeiouAEIOU";
char[] c = str.toCharArray();
//char[] charArray = str.toCharArray();
if(a.matches(".*\\d+.*"))
{
System.out.println("WARNING!!!");
System.out.println("please input only string");
}
else
{
for(int i=0;i<b.length;i++)
{
for(int j=0;j<c.length;j++)
{
if(b[i]==c[j])
{
System.out.print(" VOWEL ");
}
else if(b[i]!=c[i])
{
System.out.print(" consonant ");
}
}
}
}
}
}
The issue
The problem is in your second for loop, you should not be printing vowel or consonant from within it. This inner loop is just there to decide if the character is a vowel or not, so you should update a boolean inside this loop and print out in the outer loop depending on the value of the boolean.
code corrected
Here is your code corrected (I changed variables names so it is easier to understand):
public static void main(String args[]) {
String vowels = "aeiouAEIOU";
char[] vowelsArray = vowels.toCharArray();
Scanner s = new Scanner(System.in);
System.out.println("Enter String");
String inputString = s.next();
char inputStringArray[] = inputString.toCharArray();
if(inputString.matches(".*\\d+.*")) {
System.out.println("WARNING!!!");
System.out.println("please input only string");
} else {
for(int i=0;i<inputStringArray.length;i++) {
// Declare a boolean to say if the character is a Vowel or not
boolean isVowel = false;
// Check the character and set the boolean value
for(int j=0;j<vowelsArray.length;j++) {
if(inputStringArray[i]==vowelsArray[j]) {
isVowel = true;
break;
}
}
// Then do the printing here, in the input characters loop
if(isVowel) {
System.out.print(" VOWEL ");
} else if(inputStringArray[i]!=vowelsArray[i]) {
System.out.print(" consonant ");
}
}
}
Note regarding the regular expression
You might prefer this regex if you only want accept letters.
if(!inputString.matches("[a-zA-Z]+"))
Your current regex, would accept hey!
An other way to code it
Here is an other way to do it:
Using the contains method of the List object.
Modified the regular expression test to only accept letters
Lower casing the input string so our vowels array can be lower case only
See inline comments for explanations:
public static void main(String args[]) {
// declare your vowels
List<Character> vowelsList = Arrays.asList('a', 'e', 'i', 'o', 'u', 'y');
// get the input string
Scanner s = new Scanner(System.in);
System.out.println("Enter String");
String inputString = s.next();
if(!inputString.matches("[a-zA-Z]+")) {
System.out.println("WARNING!!!");
System.out.println("please input only string");
} else {
// Transform your inputString to lower case
// (because we only have lower case in our vowels list)
String lowerCaseInputString = inputString.toLowerCase();
// Then for each character of the input string,
// check if it is in the vowels list or not
for(char c : lowerCaseInputString.toCharArray()) {
if(vowelsList.contains(c)) {
System.out.print(" VOWEL ");
} else {
System.out.print(" consonant ");
}
}
}
}
And finally, a lambda version
If you are using Java 8 and are willing to use a lambda, you can replace the whole else block with a lambda
...
} else {
inputString.toLowerCase().chars()
.mapToObj(c -> vowelsList.contains((char) c) ? " VOWEL " : " consonant ")
.forEach(System.out::print);
}
...

if a word has 5 letters print the word with one letter per line if not then just print the word?

import java.util.Scanner;
public class SeperateLetters
{
public static void main(String[] args)
{
Scanner scan= new Scanner(System.in);
System.out.println("Enter a word:");
String w= scan.nextLine();
for(int i=0; i<w.length();i++)
System.out.println(w.charAt(i));
}
}
This is what I have so far and I can't figure how to make it so that if the word is 5 letters or longer to print it one letter per line and if not to just print the word. So far it'll just print any word with one letter per line.
You are very close. The only thing missing is an if-else conditional statement, to check whether the word has a length of five. Without this check, you will always print the string one character per line, regardless of its length.
import java.util.Scanner;
public class SeperateLetters {
public static void main(String[] args) {
Scanner scan= new Scanner(System.in);
System.out.println("Enter a word:");
String w = scan.nextLine();
if (w.length() >= 5) { // print one char per line if length is 5
for (int i = 0; i < w.length(); i++)
System.out.println(w.charAt(i));
} else {
System.out.println(w); // otherwise, print the whole string
}
}
}
Use an if-else statment to check if w.length() == 5 or not.
public class SeperateLetters
{
public static void main(String[] args)
{
Scanner scan= new Scanner(System.in);
System.out.println("Enter a word:");
String w= scan.nextLine();
if( w.length() > 5)
{
for(int i=0; i<w.length();i++)
{
System.out.println(w.charAt(i));
}
}
}
}

count the frequency of letters in given word

I need help on writing a program about counting how many times a letter in a given word is repeated in alphabetical order. Lower and upper case letters are equals and it has to work for numbers as well. For example:
we have to use array and loops. also, it must not count the space if there is more than 1 word /number given and it should also prompt the user if they want to continue or not. If not then they should enter a dot '.' or when there's a dot '.' after the word, it should close the program after counting the letters.
University
e:1 i:2 n:1 r:1 s:1 t:1 u:1 y:1
import java.util.Scanner;
import java.lang.Character;
public class Array {
public static void main(String[] args) {
Scanner input=new Scanner (System.in);
int[] letters =new int [26];
String str= input.nextLine();
str=str.toLowerCase();
for (int i=0; i<str.length(); i++)
{
letters[i]=0;
}
System.out.println(str.length());
System.out.println(char2int('a'));
System.out.println(char2int ('D'));
}
public static int char2int (char c) {
return Character.toLowerCase(c)-(int)'a';
}
}
This comes out to, for example
me
2
0
3
I'm going to give you a big hint, what you need to do is call a method (say countLetters) that takes a word and a letter - so that would be,
// Count the "letter"(s) in the word.
public static int countLetters(String word, char letter) {
int count = 0;
if (word != null) {
char lc = Character.toLowerCase(letter);
for (char c : word.toCharArray()) {
if (lc == Character.toLowerCase(c)) {
count++;
}
}
}
System.out.printf("%s: %d\n",
String.valueOf(letter), count);
return count;
}
public static void main(String[] args) {
String test = "Universe";
countLetters(test, 'e');
countLetters(test, 'u');
}
Output is
e: 2
u: 1

Categories

Resources