How to count count the number of names Java - java

Hi guys.
I'm new to Java, currently learning Strings.
I have a task to count the number of names, the length of the name must be at least two, the first letter of the name should start with upper case, the second with lower case.
The issue is that I don't know how to use the Character.isUpperCase(text.charAt(i)) and Character.isLowerCase(text.charAt(i + 1)) in the same if.
I would use some advice or hint.
class NameCounterTest {
public static void main(String[] args) {
// 1
System.out.println(new NameCounter().count("Mars is great planet"));
// 2
System.out.println(new NameCounter().count("Moon is near Earth"));
// 0
System.out.println(new NameCounter().count("SPACE IS GREAT"));
}
}
class NameCounter {
public int count(String text) {
String[] words = text.split(" ");
int wordLength = 0, counter = 0;
for (int i = 0; i < words.length; i++) {
String word = words[i];
wordLength = word.length();
if (wordLength >= 2 && Character.isUpperCase(text.charAt(i)))
counter++;
}
return counter;
}
}
Output:
1; //Should be 1;
1; //Should be 2;
3; //Should be 0;

You can use word.charAt(0) and word.charAt(1) to get the first and second character in each word in the loop.
class NameCounterTest {
public static void main(String[] args) {
// 1
System.out.println(new NameCounter().count("Mars is great planet"));
// 2
System.out.println(new NameCounter().count("Moon is near Earth"));
// 0
System.out.println(new NameCounter().count("SPACE IS GREAT"));
}
}
class NameCounter {
public int count(String text) {
String[] words = text.split(" ");
int wordLength = 0, counter = 0;
for (int i = 0; i < words.length; i++) {
String word = words[i];
wordLength = word.length();
if (wordLength >= 2 && Character.isUpperCase(word.charAt(0)) && Character.isLowerCase(word.charAt(1)))
counter++;
}
return counter;
}
}

Related

Method prints array elements way off line, and hyphens out of order

So I'm trying to print out an arrays contents created from user input (size has to be odd and between 3 and 11), which doubles as the columns and rows of the array. With characters in certain places to make patterns. Everything is fine except for the format. It prints out correctly but not in the right places. The characters are off and hyphens print in the wrong sequence for some reason. They're supposed to be printed before and after the array. The number of hyphens is correct, it's just that I'm supposed to be getting
-----------
*
*
*
*
*
-----------
but instead I get
*
*
*
*
*
-----------
-----------
I have no idea why the other hyphen line is so far out, It's almost comedic how off it is. Here is the code
public static void main (String [] args) {
// instance variables - replace the example below with your own
int dimension = findDimension();
char [] [] array2d = new char [dimension] [dimension];
char star = '*';
array2d = leftDiagonal(star, dimension);
print(array2d);
}
public static int findDimension() {
int dimension = 0;
Scanner keybd = new Scanner(System.in);
do {
System.out.print("Enter an odd integer between 3 and 11 please: ");
dimension = keybd.nextInt();
} while (dimension%2 == 0);
return dimension;
}
This is where the problem should be as it's the method that does all the printing but not sure. I put the print statements for the hyphens before and after the loop so I'm confused as to why it does this. Also there should be a space before every element is printed, which is why I put " " in the print statement but it doesn't seem to do anything.
public static void print(char [] [] arrayParam) {
for (int hyphen = 0; hyphen < (arrayParam.length*2)+1; hyphen++) {
System.out.print("-");
}
System.out.println();
for( int row = 0; row < arrayParam.length; row++) {
for (int column = 0; column < arrayParam.length; column++) {
System.out.print(" " + arrayParam[row][column]);
}
}
for (int hyphen = 0; hyphen < (arrayParam.length*2)+1; hyphen++) {
System.out.print("-");
}
}
Here is the rest of the code
public static char [] [] leftDiagonal(char starParam, int dimenParam) {
char [] [] leftD = new char [dimenParam] [dimenParam];
for (int i = 0; i < dimenParam; i++){
for (int j = 0; j < dimenParam; j++) {
if (i == j) {
System.out.print(starParam);
}
else {
System.out.print(' ');
}
}
System.out.println();
}
return leftD;
}
UPDATE: After taking into account what I've been told I've managed to get the right code. Here it is, thank you all again for the help.
public static void main (String [] args) {
int dimension = findDimension();
char [] [] array2d = new char [dimension] [dimension];
char star = '*';
array2d = leftDiagonal(star, dimension);
print(array2d);
array2d = rightDiagonal(star, dimension);
System.out.println();
print(array2d);
}
public static int findDimension() {
int dimension = 0;
Scanner keybd = new Scanner(System.in);
do {
System.out.print("Enter an odd integer between 3 and 11 please: ");
dimension = keybd.nextInt();
} while (dimension%2 == 0);
return dimension;
}
public static void print(char [] [] arrayParam) {
for (int hyphen = 0; hyphen < (arrayParam.length*2)+1; hyphen++) {
System.out.print("-");
}
System.out.println();
for(char[] row : arrayParam)
{
for(char c : row)
System.out.print(" " + c);
System.out.printf("\n");
}
for (int hyphen = 0; hyphen < (arrayParam.length*2)+1; hyphen++) {
System.out.print("-");
}
}
public static char [] [] leftDiagonal(char starParam, int dimenParam) {
char [] [] leftD = new char [dimenParam] [dimenParam];
for (int i = 0; i < dimenParam; i++){
for (int j = 0; j < dimenParam; j++) {
if (i == j)
leftD[i][j] = starParam;
else
leftD[i][j] = ' ';
}
}
return leftD;
}
There was several issues in your code, I have fixed them and mentioned them in code:
import java.util.Scanner;
public class PrintShape
{
public static void main (String [] args)
{
int dimension = findDimension();
char [] [] array2d = new char [dimension] [dimension];
char star = '*';
array2d = leftDiagonal(star, dimension);
print(array2d);
}
public static int findDimension()
{
int dimension = 0;
Scanner keybd = new Scanner(System.in);
do {
System.out.print("Enter an odd integer between 3 and 11 please: ");
dimension = keybd.nextInt();
} while (dimension%2 == 0);
return dimension;
}
public static void print(char [] [] arrayParam)
{
// i cant understand why are you printing so many hyphen "(arrayParam.length*2)+1"
// so i left it on you
for (int hyphen = 0; hyphen < (arrayParam.length*2)+1; hyphen++)
System.out.print("-");
System.out.println();
for(char[] row : arrayParam)
{
for(char c : row)
System.out.print(c);
System.out.printf("\n ");
}
//Problem:
// this "-" starts where the array printing end as you are not printing any newline ..
// it starts printing hyphen on the same line.. that why you get the second row of "-" so far
//Fixed:
System.out.printf("\n");
for (int hyphen = 0; hyphen < (arrayParam.length*2)+1; hyphen++)
System.out.print("-");
}
public static char [] [] leftDiagonal(char starParam, int dimenParam)
{
char [] [] leftD = new char [dimenParam] [dimenParam];
for (int i = 0; i < dimenParam; i++)
{
for (int j = 0; j < dimenParam; j++)
{
if (i == j)
{
// Probelm : you are just printing the "*"and no saving it in the array
// thats why you are getting only blank spaces in the "print()"
System.out.print(starParam);
leftD[i][j] = starParam;
}
else
System.out.print(' ');
// soution : save it in the array
}
System.out.println();
}
return leftD;
}
}
Do tell me if you find something difficult.

Find the word with the greatest numbers of repeated letters

For this challenge I need to find the word with the greatest numbers of repeated letters. For example, if I enter Hello world! the output should be Hello as it contains 2 characters of l, or No words and it should be -1.
I broke down the problem into:
1) Broke a sentence into the array of words
2) Went through each word in a loop
3) Went through each charcater in a loop
I'm stuck in how I should return if a word contains more letters than any other.
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
System.out.println("Enter any sentence or word combination: ");
String myString = kbd.nextLine();
String result = "";
int count = 0;
String[] words = myString.split("\\s+");
for(int i = 0; i < words.length; i++) {
for(int j = 0; j < words[i].length(); j++) {
for(int k = 1; k < words[i].length(); k++) {
char temp = words[i].charAt(k);
if(temp == words[i].charAt(k-1)) {
count++;
}
}
}
}
}
You almost did it and I suppose you're looking into something like this:
static int mostFreqCharCount(final String word) {
final int chars[] = new int[256];
int max = 0;
for (final char c : word.toCharArray()) {
chars[c]++;
if (chars[c] > chars[max]) // find most repetitive symbol in word
max = c;
}
return chars[max];
}
public static void main(final String[] args) {
System.out.println("Enter any sentence or word combination: ");
final Scanner kbd = new Scanner(System.in);
final String myString = kbd.nextLine();
kbd.close();
int maxC = 0;
String result = "";
final String[] words = myString.split("\\s+");
for (final String word : words) {
final int c = mostFreqCharCount(word);
if (c > maxC) {
maxC = c;
result = word;
}
}
if (maxC > 1) // any word has at least 1 symbol, so we should return only 2+
System.out.println(result);
}
the main idea - calculate number of most frequent symbol for each word and store only maximal one in variables maxC and result
You'll want to create an array of length = words.length, and store the highest value for each word in its relative index:
int counts[] = new int[words.length];
for(int i = 0; i < words.length; i++) {
for(int j = 0; j < words[i].length(); j++){
count = 0
for(int k = k+1; k < words[i].length(); k++){
if(words[i].charAt(j) == words[i].charAt(k)){
count++;
}
if(counts[i] < count)
counts[i] = count;
}
}
Then just scan through the array for the highest value, n, and return words[n]
If you just need the ONE word with the greatest count, you only need three variables, one for currentBestWord, one for currentLargestCount, and one to keep the count of characters in a word.
int currentLargestCount=0;
String currentBestWord="";
HashMap<String,Integer> characterCount=new HashMap<String,Integer>();
String[] words=myString.split("\\s+");
for(int i=0;i<words.length;i++){
String w=words[i];
characterCount=new HashMap<String,Integer>();
for(int j=0;j<w.length();j++){
String character=w.charAt(j).toString();
if(characterCount.containsKey(character)){
characterCount.put(character,characterCount.get(character)+1);
}else{
characterCount.put(character,1);
}
}
// Now get the largest count of this word
Iterator ir=characterCount.ValueSet().iterator();
int thiscount=0;
while(ir.hasNext()){
int thischaractercount=ir.next();
if(thiscount<thischaractercount) thiscount=thischaractercount;
}
if(thiscount>currentLargestCount){
currentLargestCount=thiscount;
currentBestWord=w;
}
}

Searching and sorting values

I try to scan the input one-by-one using charAt and sorting the letters of alphabet. If there is 2 'a's in the input the list array should start with 2. If there is 1 'b' in the input list[1] = 1. If c is used 3 times list[2] = 3. I want to have this for all letters in English.
For example if the input is "I bought a car."
The output should be 2 1 1 0 0 0 1 1 1 0 0 0 0 0 1 0 0 1 0 1 1 0 0 0 0
Note : The method is not case sensitive.
error: method sortInput in class sorting cannot be applied to given types; in line 24
What should I do?
UPDATE : Now I get an output but I get an 26-length array which all has 0's for 26 times.
import java.util.*;
public class sorting
{
public static void main(String[] args)
{
String input;
int i;
int[] list = new int[26];
Scanner scan = new Scanner(System.in);
System.out.println("Enter an input");
input = scan.nextLine();
for(i = 0; i <= list.length; i++)
{
System.out.print(Arrays.toString(sortInput(Integer.toString(list[i]))) + " ");
}
}
public static int[] sortInput(String input)
{
input = input.toLowerCase();
char k,l;
int i, j;
String alphabet;
alphabet = "abcdefghijklmnopqrstuvwxyz";
char[] letter = new char[26];
int[] list = new int[26];
j = 0;
for(i = 0; i <= alphabet.length() - 1; i++)
{
k = alphabet.charAt(i);
letter[i] = k;
}
for(i = 0; i <= input.length() - 1; i++)
{
l = input.charAt(i);
if(letter[i] == l)
{
for(i = 0; i <= input.length() - 1; i++)
{
if(letter[i] == l)
{
j = 0;
j++;
}
}
}
list[i] = j;
}
return list;
}
}
Your instance method sortInput(String) doesn't apply to sortInput(int).
This
sortInput(list[i])
could be something like
sortInput(Integer.toString(list[i]))
or change the method to take an int. Or maybe you wanted
sortInput(input)
but it will also need to be static (or you'll need an instance) as noted by #MikeKobit here.
Edit
Based on your comments. Pass in input and your method should look something like
public static int[] sortInput(String input) {
input = input.toLowerCase();
int[] list = new int[26];
for (char ch : input.toCharArray()) {
if (ch >= 'a' && ch <= 'z') {
list[ch - 'a']++;
}
}
return list;
}
public static void main(String[] args) {
String input = "I bought a car.";
int[] out = sortInput(input);
for (int i : out) {
System.out.print(i);
System.out.print(" ");
}
System.out.println();
}
Edit 2
Without toCharArray(),
public static int[] sortInput(String input) {
input = input.toLowerCase();
int[] list = new int[26];
for (int i = 0, len = input.length(); i < len; i++) {
char ch = input.charAt(i);
if (ch >= 'a' && ch <= 'z') {
list[ch - 'a']++;
}
}
return list;
}
Compare your
System.out.print(sortInput(list[i]) + " ");
with
public int[] sortInput(String input)
You are trying to call it with something else than it expects.
You are trying to call the method sortInput, which is an instance method, from a static context. You can either instantiate the class you are trying to call the method on or in this case it seems like you would want that method to be static.
public static int[] sortInput(String input)
You are also trying to call that method with the incorrect type parameter.
int[] list = new int[26];
...
sortInput(list[i])
You are currently trying to call your method with an int, not a String.

Alternating characters of two different inputs

I want to take two strings and alternate the characters into a new string using a for method.
Example: "two" and "one"
Result: "townoe"
This is what I have so far, and I really don't know how to finish it.
public class Alternator {
String alternate(String a, String b) {
String s = "";
for (int i = 0; i < a.length(); i++) {
s += i;
System.out.println(s);
}
return null;
}
}
public class Alternator{
public static String alternate(String a, String b){
String s = "";
int i = 0;
while (i < a.length() && i < b.length()){
s += a.charAt(i) +""+ b.charAt(i);
i++;
}
while (i < a.length() ){
s += a.charAt(i);
i++;
}
while (i < b.length()){
s += b.charAt(i);
i++;
}
return s;
}
public static void main(String[] args){
String a = "two", b = "one";
String s = Alternator.alternate(a,b);
System.out.println(s);
}
}
To use for loop instead of while loop, simply remove all while lines with for lines like the following, then remove the i++ line from each while loop
for(; i < a.length() && i < b.length(); i++){
//the inside of the loop MINUS THE LINE i++
}
for(; i < a.length(); i++){
//the inside of the loop MINUS THE LINE i++
}
for(; i < b.length(); i++){
//the inside of the loop MINUS THE LINE i++
}
Here is some compact way of doing that:
String alternate(String a, String b) {
StringBuilder builder = new StringBuilder();
int smallerStringLength = Math.min(a.length(), b.length());
for (int i = 0; i < smallerStringLength; i++) {
builder.append(a.charAt(i));
builder.append(b.charAt(i));
}
return builder.toString();
}
Or even more optimized:
String alternate(String first, String second) {
char[] firstChars = first.toCharArray();
char[] secondChars = second.toCharArray();
int smallerCharsCount = Math.min(firstChars.length, secondChars.length);
StringBuilder builder = new StringBuilder(smallerCharsCount * 2);
for (int i = 0; i < smallerCharsCount; i++) {
builder.append(firstChars[i]);
builder.append(secondChars[i]);
}
return builder.toString();
}
This will work if string are of same length or of the different lengths.
static void mergeStrings(String a, String b) {
StringBuilder mergedBuilder = new StringBuilder();
char[] aCharArr = a.toCharArray();
char[] bCharArr = b.toCharArray();
int minLength = aCharArr.length >= bCharArr.length ? bCharArr.length : aCharArr.length;
for (int i=0; i<minLength; i++) {
mergedBuilder.append(aCharArr[i]).append(bCharArr[i]);
}
if(minLength < aCharArr.length) {
mergedBuilder.append(a.substring(minLength));
}
else{
mergedBuilder.append(b.substring(minLength));
}
Systemout.println(mergedBuilder.toString());
}
Assuming that the two strings are the exact same length, you can do the following. If they are different length, then currently your prompt doesn't say how you want the resultant string to be set up.
public class Alternator {
String alternate(String a, String b) {
String s = "";
for (int i = 0; i < 2*a.length(); i++) {
if (i%2==0) // modular arithmetic to alternate
s += a.charAt(i/2); // Note the integer division
else
s += b.charAt(i/2);
}
System.out.println(s);
return s;
}
}
Alternatively, even easier, but the index i doesn't mark the length of your string s:
public class Alternator {
String alternate(String a, String b) {
String s = "";
for(int i = 0; i < a.length(); i++){
s += a.charAt(i);
s += b.charAt(i);
}
return s;
}
}
Use this:
String alternate(String a, String b){
StringBuilder builder = new StringBuilder();
final int greaterLength = a.length() > b.length() ? a.length() : b.length();
for(int i = 0; i < greaterLength; i++){
if (i < a.length()) {
builder.append(a.charAt(i));
}
if (i < b.length()) {
builder.append(b.charAt(i));
}
}
return builder.toString();
}
It uses the String.charAt method to obtain letters, and a StringBuilder to create the string.
(When given two strings of non-equal length, this returns an alternation of the first two chars, and then does just the remaining string. EG: Hello and Hi --> HHeillo)
According to the comments I've read, you are having trouble understanding for loops, and how to use them with strings.
For loops are most often used to iterate over arrays, or to perform a task a given number of times.
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
This would give the output
0
1
2
3
4
For loops start at the value of the initializer, the first thing you put in int i = 0;
They then check the expression, the second part of the for loop, and if it returns true, it executes all of the code inside the braces. i < 5;
Once it has done that, it runs the incrementor, the last part of the for loop. i++
After that, it checks the expression again. I guess you can see where this is going. Until the expression returns false, everything inside the curly braces of the for loop gets executed over and over again.
Strings can be iterated over with a for loop, but you can't reference it like an array using array[index]. You have to either convert it into an array, using .toCharArray() on your String, and return the result to an empty char array char[], or use the .charAt(index) method on your string.
This code will go over a string, and output each character, one by one:
for (int i = 0; i < myString.length(); i++) {
System.out.println(myString.charAt(i));
}
If the string had a value of "Hello", the output would be:
H
e
l
l
o
Using this, instead of outputting the characters using System.out.println();, we can put them into an empty string, using +=:
myOtherString += myString.charAt(i);
That means, if we want to go over two Strings at a time, and alternate them, like you do, we can iterate over two strings at the same time, and add them to a new string:
myAlternatedString += myString.charAt(i);
myAlternatedString += myOtherString.charAt(i);
if MyString was still "Hello" and myOtherString was "World", the new string would be:
Hweolrllod
following code reads 2 different inputs and merges into a single string.
public class PrintAlternnateCharacterString {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String a = in.next();
String b = in.next();
String mergedString = "";
int lenA = a.length();
int lenB = b.length();
if (lenA >= lenB) {
for (int i = 0; i < lenA; i++) {
if (i < lenB) {
mergedString += a.charAt(i) + "" + b.charAt(i);
} else {
mergedString += a.charAt(i);
}
}
}
if (lenB > lenA) {
for (int i = 0; i < lenB; i++) {
if (i < lenA) {
mergedString += a.charAt(i) + "" + b.charAt(i);
} else {
mergedString += b.charAt(i);
}
}
}
System.out.println("the merged string is-->" + mergedString);
}
}
public static String stringConcate(String str1,String str2){
String str3="";
if(str1!=null && str2!=null && !str1.isEmpty() && !str2.isEmpty()){
if(str1.length()==str2.length()){
for(int i=0;i<=str1.length()-1;i++){
str3+=str1.charAt(i);
str3+=str2.charAt(i);
}
}
if(str1.length()>str2.length()){
for(int i=0;i<=str1.length()-1;i++){
str3+=str1.charAt(i);
if(i<str2.length()){
str3+=str2.charAt(i);
}
}
}
if(str2.length()>str1.length()){
for(int i=0;i<=str2.length()-1;i++){
if(i<str1.length()){
str3+=str1.charAt(i);
}
str3+=str2.charAt(i);
}
}
}
return str3;
}
String str1 = "one"; String str2 = "two";
StringBuilder sb = new StringBuilder();
int i = 0;
for (; i < str1.length() && i < str2.length(); i++) {
sb.append(str1.charAt(i)).append(str2.charAt(i));
}
for(; i < str1.length(); i++) {
sb.append(str1.charAt(i));
}
for(; i < str2.length(); i++) {
sb.append(str2.charAt(i));
}
System.out.println("result = " + sb.toString());// otnweo
This will handle for different length too
This could be donw with very simple if...else.
public static void main(String... args) {
int[] one = { 1, 2, 3 };
int[] two = { 44, 55, 66, 77, 88 };
System.out.println(Arrays.toString(alternate(one, two)));
}
public static int[] alternate(int[] one, int[] two) {
int[] res = new int[one.length + two.length];
for (int i = 0, j = 0, k = 0; i < res.length; i++) {
if (i % 2 == 0)
res[i] = j < one.length ? one[j++] : two[k++];
else
res[i] = k < two.length ? two[k++] : one[j++];
}
return res;
}
Output:
[1, 44, 2, 55, 3, 66, 77, 88]

How can I print out an array list in a foursome fragmented list?

This is My Array code with given string numbers(0098765424100304643528):
public class Main
{
public static void main(String[] args)
{
String mynumbers = "0098765424100304643528";
int len = mynumbers.length();
char[] tempCharArray = new char[len];
for (int i = 0; i < len; i++)
{
tempCharArray[i] = mynumbers.charAt(i);
System.out.print(tempCharArray[i]+"->");
}
System.out.println();
}
}
this is the result after running :
0->0->9->8->7->6->5->4->2->4->1->0->0->3->0->4->6->4->3->5->2->8->
I want to change it such below (How can I fragment my array in foursome ?)
0098->7654->2410->0304->4352->8
System.out.println(StringUtils.join("0098765424100304643528".split("(?<=\\G.{4})"), "->"));
maybe you write the result is wrong as you say (foursome), if you just want the output foursome , you can do like that :
for (int i = 0; i < len; i++)
{
tempCharArray[i] = mynumbers.charAt(i);
System.out.print(tempCharArray[i]);
if((i+1)%4==0)
{
System.out.print("->");
}
}
We will check if value of i is not 0 and i is divisible by 4. If true, then print -> else print number without it.
public class Main
{
public static void main(String[] args)
{
String mynumbers = "0098765424100304643528";
int len = mynumbers.length();
char[] tempCharArray = new char[len];
for (int i = 0; i < len; i++)
{
tempCharArray[i] = mynumbers.charAt(i);
if(i > 0 && i%4 == 0)
System.out.print(tempCharArray[i]+"->");
else
System.out.print(tempCharArray[i]);
}
System.out.println();
}
}
You could check if i is dividable by 4, if it is add an arrow, otherwise just print the number. Ie:
public class Main
{
public static void main(String[] args)
{
String mynumbers = "0098765424100304643528";
int len = mynumbers.length();
char[] tempCharArray = new char[len];
for (int i = 0; i < len; i++)
{
tempCharArray[i] = mynumbers.charAt(i);
if((i % 4 == 0) && i > 0)
System.out.print(tempCharArray[i]+"->");
else
System.out.print(tempCharArray[i]);
}
System.out.println();
}
}
Here the % is the modulus operator, which tells us the remainder of something divided by something else, ie: 5 % 4 = 1 since 5 / 4 = 1 * 4 + 1

Categories