How to collect names in a loop then use StringBuilder? - java

Have been up for hours trying to figure out how to add in these in a string array using user input and StringBuilder.
I have to in a loop collect names from user input (scanner).
when they enter a blank name stop looping. Then iterate over the attendee list to create the output string using StringBuilder.
only 1 name = Name .
2 names = Name 1 and name 2 . more then 2 names = name 1, name2, and name 3 . output should exactly match the way these are formatted with spaces, commas, and the "and".
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
sb.append("You have invited: ");
System.out.println("enter names.");
String attendee = keyboard.nextLine();
// receiving input
while (attendee != "") {
sb.append(attendee);
if (attendee == "") break;
}
System.out.println(sb);
for (int i = 0; i > sb.length(); i++) {
if (i == 0) {
keyboard.nextLine(); //consuming the <enter> from input above
sb.append(keyboard.nextLine());
i++;
} else if (i == 1) {
sb.append(keyboard.nextLine() + " and " + keyboard.nextLine());
System.out.println(sb);
} else if (i > 1) {
sb.append(keyboard.nextLine() + ", " + keyboard.nextLine() + ", and " + keyboard.nextLine());
System.out.println(sb);
}
}
}

There is a lot of errors in your code
you don't ask again in the while loop for a new value, so either you never get in (first empty string) or never get out (first not empty) also that isn't how you compare a string, that is an object, use .equals()
you may not call keyboard.nextLine() (getting input) in the loop where you build the output
names shouldn't be joined in the StringBuilder, then how would you build the output
So, make a nice loop that populates a list of String, then nicely concatenate the different parts to make the output
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
List<String> names = new ArrayList<>();
System.out.print("enter name: ");
String attendee = keyboard.nextLine();
while (!attendee.equals("")) {
names.add(attendee);
System.out.print("enter name: ");
attendee = keyboard.nextLine();
}
System.out.println(namesToString(names));
}
static String namesToString(List<String> names) {
List<String> firsts = names.subList(0, names.size() - 1);
String last = names.get(names.size() - 1);
if (names.size() == 1)
return "You have invited: " + last;
return "You have invited: " + String.join(", ", firsts) + " and " + last;
}
enter name: Patrick
enter name: Pierre
enter name: James
enter name: John
enter name:
You have invited: Patrick, Pierre, James and John
Full possibilities of outputs
System.out.println(namesToString(Arrays.asList("pierre")));
// You have invited: pierre
System.out.println(namesToString(Arrays.asList("pierre", "jean")));
// You have invited: pierre and jean
System.out.println(namesToString(Arrays.asList("pierre", "jean", "eude")));
// You have invited: pierre, jean and eude
System.out.println(namesToString(Arrays.asList("pierre", "jean", "eude", "john", "james")));
// You have invited: pierre, jean, eude, john and james

Related

Sting manipulation won't print full output to input

I have code for string manipulation but the output only generates the first name and not the rest of the input. I don't get any errors so I'm not sure what I'm doing wrong. Can someone show point out what I'm doing wrong if so and help me fix it so the output shows everything?
The expected input and output is for first name, last name, full name, upper case full name, lower case full name, number of vowels, number of consonants, and a few sentences plus the date.
Here is the code -
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class StringManipulation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter first name: Bk ");
String fName = input.next();
System.out.println("Enter last name: Codeman");
String lName = input.next();
String UserFullName = fName.concat(" ").concat(lName);
System.out.println("\nHello " + UserFullName);
System.out.println("Length of name: " + UserFullName.length());
UserFullName = UserFullName.toUpperCase();
System.out.println("\nIn Upper Case: " + UserFullName);
UserFullName = UserFullName.toLowerCase();
System.out.println("In Lower Case: " + UserFullName);
//Counter variable to store the count of vowels and consonant
int vCount = 0, cCount = 0;
for(int i = 0; i < UserFullName.length(); i++) {
//Checks whether a character is a vowel
if(UserFullName.charAt(i) == 'a' || UserFullName.charAt(i) == 'e' || UserFullName.charAt(i) == 'i' || UserFullName.charAt(i) == 'o' || UserFullName.charAt(i) == 'u') {
//Increments the vowel counter
vCount++;
}
//Checks whether a character is a consonant
else if(UserFullName.charAt(i) >= 'a' && UserFullName.charAt(i)<='z') {
//Increments the consonant counter
cCount++;
}
}
System.out.println("\nNumber of vowels: " + vCount);
System.out.println("Number of consonants: " + cCount);
String text = "I am a very good student who works hard";
System.out.println("\nText: " + text);
System.out.println("At Position 10 of Text: " + text.charAt(10));
System.out.println("good starts at position: " + text.indexOf("good"));
System.out.println("good ends at position: " + (text.indexOf("good") + "good".length()-1));
System.out.println("\nEnter the word Excellent");
String word = input.next();
while(!word.equals("Excellent")) {
System.out.println("Incorrect, enter again");
word = input.next();
}
System.out.println("Good job");
Date date = new Date();
SimpleDateFormat formatter;
String strDate;
System.out.println("\nCurrent Date and Time");
formatter = new SimpleDateFormat("MMMM dd, yyyy");
strDate = formatter.format(date);
System.out.println(strDate);
formatter = new SimpleDateFormat("h:mm a");
strDate = formatter.format(date);
System.out.println(strDate);
input.close();
}
}
I happen to run your program and i have no errors and also the desired output was obtained can you check again or please inform if this ain't the output you seek
Enter first name: Bk
Stannars
Enter last name: Codeman
Jose
Hello Stannars Jose
Length of name: 13
In Upper Case: STANNARS JOSE
In Lower Case: stannars jose
Number of vowels: 4
Number of consonants: 8
Text: I am a very good student who works hard
At Position 10 of Text: y
good starts at position: 12
good ends at position: 15
Enter the word Excellent
Excellent
Good job
Current Date and Time
May 31, 2021
11:19 AM

Removing whitespace from strings

I'm working on a parsing assignment, and I'm supposed to take the input and turn it into two separate strings and output the strings. If there is no comma, I give an error message. If the choice is "q", then end the loop. Here is my code:
import java.util.Scanner;
import java.lang.*;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
/* Type your code here. */
String name;
String first;
String last;
int commaIndex;
int size;
boolean quit = false;
while (!quit)
{
System.out.println("Enter input string:");
name = scnr.nextLine();
commaIndex = name.indexOf(',');
size = name.length();
// get q case
if (name.equals("q"))
{
quit = true;
}
// if no comma, give error message
else if (commaIndex == -1)
{
System.out.println("Error: No comma in string.");
System.out.println();
}
else
{
first = name.substring(0, commaIndex);
last = name.substring(commaIndex + 1, size);
// re do, but without spaces
first = first.replaceAll(" ", "");
last = last.replaceAll(" ", "");
commaIndex = name.indexOf(',');
first = name.substring(0, commaIndex);
last = name.substring(commaIndex + 1, size);
System.out.println("First word: " + first);
System.out.println("Second word: " + last);
System.out.println();
}
}
}
}
And the input is this:
Jill, Allen
Golden , Monkey
Washington,DC
q
I'm not getting the points because of the space after the word "Golden " and before " Monkey"
try this
/* Type your code here. */
String name;
String first;
String last;
while (true)
{
System.out.println("Enter input string:");
name = scnr.nextLine();
// get q case
if (name.equals("q"))
{
//You can avoid to use quit flag, you can break the loop
break;
}
else
{
//Separate the input with split by the comma character
string [] arr = name.split(",");
// if no comma, give error message in other words if you array is empty
if(arr.length==0){
System.out.println("Error: No comma in string.");
System.out.println();
}
//check if you have more than 2 words
if(arr.length>1){
//the trim function will remove all white spaces at the start and end of the string
first = arr[0].trim();
last = arr[1].trim();
System.out.println("First word: " + first);
System.out.println("Second word: " + last);
System.out.println();
}else{
first =arr[0].trim();
System.out.println("First word: " + first);
System.out.println();
}
}
}
Use String.split(String) it takes a regular expression. Split on optional whitespace and comma. Like,
String[] tokens = name.trim().split("\\s*,\\s*");
String first = tokens[0];
String last = tokens[tokens.length - 1];

Char count of each token in Tokenized String, Java

I'm trying to figure out if I can count the characters of each token and display that information such as:
day is tokenized and my output would be: "Day has 3 characters." and continue to do that for each token.
My last loop to print out the # of characters in each token never prints:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> tokenizedInput = new ArrayList<>();
String sentenceRetrieved;
// getting the sentence from the user
System.out.println("Please type a sentence containing at least 4 words, with a maximum of 8 words: ");
sentenceRetrieved = sc.nextLine();
StringTokenizer strTokenizer = new StringTokenizer(sentenceRetrieved);
// checking to ensure the string has 4-8 words
while (strTokenizer.hasMoreTokens()) {
if (strTokenizer.countTokens() > 8) {
System.out.println("Please re-enter a sentence with at least 4 words, and a maximum of 8");
break;
} else {
while (strTokenizer.hasMoreTokens()) {
tokenizedInput.add(strTokenizer.nextToken());
}
System.out.println("Thank you.");
break;
}
}
// printing out the sentence
System.out.println("You entered: ");
System.out.println(sentenceRetrieved);
// print out each word given
System.out.println("Each word in your sentence is: " + tokenizedInput);
// count the characters in each word
// doesn't seem to run
int totalLength = 0;
while (strTokenizer.hasMoreTokens()) {
String token;
token = sentenceRetrieved;
token = strTokenizer.nextToken();
totalLength += token.length();
System.out.println("Word: " + token + " Length:" + token.length());
}
}
}
Example of Console:
Please type a sentence containing at least 4 words, with a maximum of 8 words:
Hello there this is a test
Thank you.
You entered:
Hello there this is a test
Each word in your sentence is: [Hello, there, this, is, a, test]
First off, I have added the necessary imports and built a class around this main method. This should compile.
import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;
public class SOQ_20200913_1
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> tokenizedInput = new ArrayList<>();
String sentenceRetrieved;
// getting the sentence from the user
System.out.println("Please type a sentence containing at least 4 words, with a maximum of 8 words: ");
sentenceRetrieved = sc.nextLine();
StringTokenizer strTokenizer = new StringTokenizer(sentenceRetrieved);
// checking to ensure the string has 4-8 words
while (strTokenizer.hasMoreTokens()) {
if (strTokenizer.countTokens() > 8) {
System.out.println("Please re-enter a sentence with at least 4 words, and a maximum of 8");
break;
} else {
while (strTokenizer.hasMoreTokens()) {
tokenizedInput.add(strTokenizer.nextToken());
}
System.out.println("Thank you.");
break;
}
}
// printing out the sentence
System.out.println("You entered: ");
System.out.println(sentenceRetrieved);
// print out each word given
System.out.println("Each word in your sentence is: " + tokenizedInput);
// count the characters in each word
// doesn't seem to run
int totalLength = 0;
while (strTokenizer.hasMoreTokens()) {
String token;
token = sentenceRetrieved;
token = strTokenizer.nextToken();
totalLength += token.length();
System.out.println("Word: " + token + " Length:" + token.length());
}
}
}
Next, let's look at this working example. It seems like everything up until your final while loop (the one that counts character length) works just fine. But if you notice, the while loop before the final one will continue looping until it has no more tokens to fetch. So, after it has finished gathering all of the tokens and has no more tokens to gather, you try and create the final while loop, asking it to gather more tokens. It would not have reached the while loop until it ran out of tokens to gather!
Finally, in order to solve this, you can simply go through the list that you added to in the second to last while loop, and simply cycle through that for your final loop!
For example:
int totalLength = 0;
for (String each : tokenizedInput) {
totalLength += each.length();
System.out.println("Word: " + each + " Length:" + each.length());
}

Finding max/min entry in arraylist element

My program allows the user to repeatedly enter match results until the user enters 'stop', then the results are displayed. I just need to find the highest input value in my 'stats[2]' arraylist, which is the 'hometeam score'. So if the user enter 3 inputs, "Manchester City : Manchester United : 2 : 1 ...
Chelsea : Arsenal : 0 : 1 ...
Everton : Liverpool : 1 : 1" then it should display the number '2' as it's the highest value in that array. if that makes sense? I've set up the line at the bottom where I need it to be displayed.
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
ArrayList<String[]> stats = new ArrayList<>(); // initialize a container
// to hold all the stats
System.out.println("please enter match results:");
int matchesPlayed = 0;
int invalidEntry = 0;
while (sc.hasNextLine()) {
String input = sc.nextLine();
String[] results = input.split("\\s*:\\s*");
if (results.length == 4) {
stats.add(results);
matchesPlayed++;
}
else if (input.equals("stop")) {
break;
}
} // end of while
for (int i = 0; i < stats.size(); i++) {
if (stats.get(i)[0].trim().isEmpty()) {
System.out
.println("no home team name entered on the following line:");
invalidEntry++;
matchesPlayed--;
}
else if (stats.get(i)[1].trim().isEmpty()) {
System.out
.println("no away team name entered on the following line:");
invalidEntry++;
matchesPlayed--;
}
else if (stats.get(i)[2].trim().isEmpty()) {
System.out.println("no home score entered on this line");
invalidEntry++;
matchesPlayed--;
}
else if (stats.get(i)[3].trim().isEmpty()) {
System.out.println("no away score entered on this line");
invalidEntry++;
matchesPlayed--;
}
try {
System.out.println(String.valueOf(stats.get(i)[0]) + " ["
+ Integer.valueOf(stats.get(i)[2]) + "] " + " | "
+ (String.valueOf(stats.get(i)[1])
+ " [" + Integer.valueOf(stats.get(i)[3]) + "] "));
} catch (Exception e) {
// do nothing with any invalid input
}
}
System.out.println(" ");
System.out.println("Totals");
System.out.println("-------------------------");
System.out.println("total number of matches: " + matchesPlayed);
System.out.println("total number of invalid entries: " + invalidEntry);
System.out.println("highest home score: ");
}
Just loop through it, set a variable equal to the first element, and in the loop if there is an element that is higher than the variable currently is, change the variable's value to that. Then print the variable at the end

To take input a sentence and check if it contains any word input by the user, also print the count

I am working on a program in java the output should be something like below :
Input the sentence
hello how how are you
enter code here
Input the word that has to be searched
how
Output :
the string is present and the count of the string how is : 2
I have written a program but i am not able to count the search string can anyone please help me on this and below is the code
I think there is a problem with the looping as well i am able to find the string present in the sentence but not able to count.
boolean contains = false;
/*Inputting the sentence*/
java.util.Scanner scn = new java.util.Scanner(System.in);
System.out.println("Input the sentence");
String s = scn.nextLine();
String[] lstarr = s.split(" ");
/*Inputting the string*/
java.util.Scanner scn2 = new java.util.Scanner(System.in);
System.out.println("Input the word to be searched");
String s2 = scn.nextLine();
String[] explst = s2.split(" ");
/*searching the input word */
if(s.contains(s2)){
contains = true;
System.out.println("Input word is present : " + s2);
}
else{
System.out.println("String " + s2 + "is not present");
}
ArrayList<String> lst = new ArrayList<String>();
Collections.addAll(lst, lstarr);
for(String str : lst) {
System.out.println(str + " " + Collections.frequency(lst, str));
}
}
Try the following code :
public static void main(String[] args) {
System.out.println("Input the sentence");
Scanner s = new Scanner(System.in);
String input = s.nextLine();
System.out.println("Input the word that has to be searched");
String word = s.nextLine();
String str = "";
int occurance = 0;
for(char c : input.toCharArray()) {
str += c;
if(str.length() == word.length()) {
if(str.equals(word)) {
occurance ++;
}
str = str.substring(1);
}
}
if(occurance > 0)
System.out.println("the string is present and the count of the given string is : " + occurance);
else
System.out.println("The string is not present");
}
There's no need to use Collections.addAll:
This will give you the frequency of all the words in the input sentence.
List<String> input = Arrays.asList(lstarr);
for(String str : input) {
System.out.println(str + " " + Collections.frequency(input , str));
}
Of course, if you only want the frequency of the searched word, you need :
System.out.println(s2 + " " + Collections.frequency(input, s2));
So, your basic problem revoles around the desire to convert an array (of Strings) to a List of Strings
You can add an array of values to a collection in at least three ways...
You could use Arrays.asList...
List<String> lst = Arrays.asList(lstarr);
which returns a non-mutable List, which would suit your needs, but you can also use...
ArrayList<String> lst = new ArrayList<String>(Arrays.asList(lstarr));
or
ArrayList<String> lst = new ArrayList<String>();
lst.addAll(Arrays.asList(lstarr));
Which will give you a mutable list...
You can then check for the frequency of the work simply by using Collections.frequency directly...
System.out.println(s2 + " " + Collections.frequency(lst, s2));
Multiple word search...(for some reason)
String text = "how hello how how are you";
String query = "how hello";
String[] words = text.split(" ");
List<String> wordsList = Arrays.asList(words);
String[] matches = query.split(" ");
for (String match : matches) {
System.out.println(match + " occurs " + Collections.frequency(wordsList, match) + " times");
}
Which, based on my input, outputs
how occurs 3 times
hello occurs 1 times
You could even use a regular expression...
for (String match : matches) {
Pattern p = Pattern.compile(match);
Matcher m = p.matcher(text);
int count = 0;
while (m.find()) {
count++;
}
System.out.println(match + " occurs " + count + " times");
}
You could even use a temporary list and simple remove all the occurrences of the given word from it and calculate the difference in size...
List<String> check = new ArrayList<>(25);
for (String match : matches) {
check.addAll(wordsList);
int startSize = check.size();
check.removeAll(Arrays.asList(new String[]{match}));
int endSize = check.size();
System.out.println(match + " occurs " + (startSize - endSize) + " times");
check.clear();
}
But I think that goes "way" beyond what is been asked...
use following code-
java.util.Scanner scn = new java.util.Scanner(System.in);
System.out.println("Input the sentence");
String s1 = scn.nextLine();
System.out.println("Input the word or combination-of-words to be searched");
String s2 = scn.nextLine();
/*searching the input word */
int count=0;
while(s1.contains(s2)){
s1=s1.substring(s1.indexOf(s2)+s2.length(), s1.length()-1);
count++;
}
if(count>0){
System.out.println("String "+s2+" exists, occures "+count +" times.");
}else{
System.out.println("String "+s2+" does not exists.");
}
Just create your collection before you check the existence of input.
Inside if print the frequency of input using Collections.frequency(lst, s2)
Get rid of the code after if/else
...
ArrayList<String> lst = new ArrayList<String>();
Collections.addAll(lst, lstarr);
if(lst.contains(s2)){
System.out.println("Input word is present and the count of the string "+s2+" is :" + Collections.frequency(lst, s2));
}
...

Categories