How do I output the string connected to it's Uppercase length - java

In this program I'm trying to create I have a method to take a string to count the amount of uppercase letters. At the end of the program I want to show the smallest amount associated with it's string and the max amount associated with its string which is where I'm having trouble. Is there a way to somehow connect or associate these together? Here is my code so far:
import java.util.Scanner;
import java.util.Arrays;
public class test {
public static void main(String[] args) {
System.out.println("Please input a string:");
Scanner input = new Scanner(System.in);
String s1 = input.nextLine();
String s2 = input.nextLine();
String s3 = input.nextLine();
int i1 = sumLetter(s1);
int i2 = sumLetter(s2);
int i3 = sumLetter(s3);
int[] array = new int[3];
array[0] = i1;
array[1] = i2;
array[2] = i3;
Arrays.sort(array);
System.out.println(s1 + " has a maximum number of uppercase: "+ array[2]);
System.out.println(s3 + " has a maximum number of uppercase: "+ array[0]);
}
public static int sumLetter(String m) {
int count = 0;
for(int i = 0; i < m.length();i++) {
if(Character.isUpperCase(m.charAt(i)))
count++;
}
return count;
}
}

You can use regex to handle this, like so:
public static void main(String[] args) {
String str = "This string has FIVE uppercase characters within itself.";
System.out.println(str.replaceAll("[^\\p{javaUpperCase}]","").length());
}
Output:
5
This is roughly equivalent to the following:
public static void main(String[] args) {
String str = "This string has FIVE uppercase characters within itself.";
int uppercases = 0;
for(char c : str.toCharArray()) {
uppercases += Character.isUpperCase(c) ? 1 : 0;
}
System.out.println(uppercases);
}
Output:
5
Now, assuming that you have this functionality (which you do) within some method:
public static int sumLetter(String m) { ... }
You want to associate the String with the uppercase length. Make a simple data class:
final class StringWithUppercaseSize {
public final String string;
public final int uppercaseLength;
public StringWithUppercaseSize(String string, int uppercaseLength) {
this.string = string;
this.uppercaseLength = uppercaseLength;
}
public int getUppercaseLength() {
return this.uppercaseLength;
}
}
Now, you make an array of these objects:
Scanner input = new Scanner(System.in);
String s1 = input.nextLine();
String s2 = input.nextLine();
String s3 = input.nextLine();
int i1 = sumLetter(s1);
int i2 = sumLetter(s2);
int i3 = sumLetter(s3);
StringWithUppercaseSize[] sizes = { new StringWithUppercaseSize(s1, i1), new StringWithUppercaseSize(s2, i2), new StringWithUppercaseSize(s3, i3) };
Sort the array, by the uppercase size:
Arrays.sort(sizes, Comparator.comparing(StringWithUppercaseSize::getUppercaseLength));
Output the minimum/maximum uppercase string/lengths:
System.out.println(sizes[0].string + " has a minimum number of uppercase: "+ sizes[0].uppercaseLength);
System.out.println(sizes[2].string + " has a maximum number of uppercase: "+ sizes[2].uppercaseLength);
Input:
Abc
abc
aBC
Output:
abc has a minimum number of uppercase: 0
aBC has a maximum number of uppercase: 2
Here's my full test code:
Main.java
class Main {
public static void main(String[] args) {
System.out.println("Please input a string:");
Scanner input = new Scanner(System.in);
String s1 = input.nextLine();
String s2 = input.nextLine();
String s3 = input.nextLine();
int i1 = sumLetter(s1);
int i2 = sumLetter(s2);
int i3 = sumLetter(s3);
StringWithUppercaseSize[] sizes = { new StringWithUppercaseSize(s1, i1), new StringWithUppercaseSize(s2, i2), new StringWithUppercaseSize(s3, i3) };
Arrays.sort(sizes, Comparator.comparing(StringWithUppercaseSize::getUppercaseLength));
System.out.println(sizes[0].string + " has a minimum number of uppercase: "+ sizes[0].uppercaseLength);
System.out.println(sizes[2].string + " has a maximum number of uppercase: "+ sizes[2].uppercaseLength);
}
public static int sumLetter(String m) {
int count = 0;
for(int i = 0; i < m.length();i++) {
if(Character.isUpperCase(m.charAt(i)))
count++;
}
return count;
}
}
StringWithUppercaseSize.java
final class StringWithUppercaseSize {
public final String string;
public final int uppercaseLength;
public StringWithUppercaseSize(String string, int uppercaseLength) {
this.string = string;
this.uppercaseLength = uppercaseLength;
}
public int getUppercaseLength() {
return this.uppercaseLength;
}
}
Finally, as a note, don't do this in code you intend to keep and maintain. There are plenty of ways to make things more readable and maintainable. For example, you can write actual getters/setters for your data class. You can make the public data members private to preserve information hiding. You can append user inputs into a List, and then use things like a for-each loop to create another List of uppercase sizes. You can go over both those lists with a for-each loop to create a List of StringWithUppercaseSizes. You can probably use a Stream with Collectors.maxBy to find the maximum elements instead of sorting, etc.

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

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

Adding numbers together from a String

I want to be able to separate a String of two numbers and then add them together, but I keep getting the int value of each character. If I enter "55" as a string I want the answer to be 10. How can I do that?
package org.eclipse.wb.swt;
import java.util.*;
public class ISBN13 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("enter a string");
String numbers = input.nextLine(); //String would be 55
int num1=numbers.charAt(0); //5
int num2=numbers.charAt(1); //5
System.out.println(num1+num2); //the answer should be 10
}
}
You are getting the ascii value of the characters; you can use Character.digit(char, int) to get the numeric value. Something like,
String numbers = "55";
int num1 = Character.digit(numbers.charAt(0), 10);
int num2 = Character.digit(numbers.charAt(1), 10);
System.out.println(num1 + num2);
Output is (as requested)
10
int x = Character.getNumericValue(element.charAt(0));
You can use string.toCharArray() method and then add them in a for loop
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) {
Scanner scan = null;
try {
scan = new Scanner(System.in);
String line = scan.nextLine();
char[] charArray = line.toCharArray();
int sum = 0;
for (char character : charArray) {
sum += Integer.parseInt(String.valueOf(character));
}
System.out.println(sum);
} finally {
scan.close();
}
}
}

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

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