Sting manipulation won't print full output to input - java

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

Related

How to collect names in a loop then use StringBuilder?

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

Beginning coder (Java) - validating String input and ending a loop once correct input has been entered

The idea with this question is that the user knows to input the sentence "Robin came to Montreal, Canada in 2009.". From there, the code should spit back "Robin stays in Montreal, for 11 years. Montreal is in Canada. Please enter the input sentence (press q to exit):".
I've managed to get a loop going so that as long as the user is inputting the sentence correctly the program will also spit back the correct phrase. The part that I'm struggling with is ending the loop - getting "q" to terminate the program. Instead I get an error. Please let me know what I can do.
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class MiniTranslator {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String sentence;
do {
System.out.println("Please enter the input sentence (press q to exit)");
sentence = scan.nextLine();
int i = sentence.indexOf(' ');
String word = sentence.substring(0, i);
String sentence2 = sentence.substring(i + 9, sentence.length());
int j = sentence2.indexOf(' ');
String word2 = sentence2.substring(0, j);
Matcher matcher = Pattern.compile("\\d+").matcher(sentence);
matcher.find();
int k = Integer.valueOf(matcher.group());
String sentence3 = sentence2.substring(j + 1, sentence2.length());
int l = sentence3.indexOf(' ');
String word3 = sentence3.substring(0, l);
System.out.println(word + " stays in " + word2 + " for " + (2020 - k) + " years. " + word2 + " is in " + word3 + ".");
System.out.println(" ");
} while (!"q".equals(sentence));
do {
System.out.println("Thanks for using the translator program.");
System.out.println(" ");
System.out.println("The program is now terminated");
} while ("q".equals(sentence));
First of all you should probably share you error message so community members can better understand your problem. But nonetheless your code should be while(!sentence.equals("q")), since you basically want to call the .equals() method, and you need to create a type String Object for that. "q" is just a String expression that can be passed into the .equals() method.
The part that I'm struggling with is ending the loop - getting "q" to terminate the program. Instead I get an error. Please let me know what I can do.
I have solved the part where you were struggling, but your program logic is incorrect and you need to work on that. For that learn about String class and its functions.
Anyway, here is your program press q to exit code
Scanner scan = new Scanner(System.in);
String sentence;
boolean doAgain = true;
do
{
System.out.println("Please enter the input sentence (press q to exit)");
sentence = scan.nextLine();
if("q".equals(sentence))
{
doAgain = false;
}
else
{
//your program logic in here
int i = sentence.indexOf(' ');
String word = sentence.substring(0, i);
String sentence2 = sentence.substring(i + 9, sentence.length());
int j = sentence2.indexOf(' ');
String word2 = sentence2.substring(0, j);
Matcher matcher = Pattern.compile("\\d+").matcher(sentence);
matcher.find();
int k = Integer.valueOf(matcher.group());
String sentence3 = sentence2.substring(j + 1, sentence2.length());
int l = sentence3.indexOf(' ');
String word3 = sentence3.substring(0, l);
System.out.println(word + " stays in " + word2 + " for " + (2020 - k) + " years. " + word2 + " is in " + word3 + ".");
System.out.println(" ");
}
} while (doAgain);
System.out.println("Thanks for using the translator program.");
System.out.println(" ");
System.out.println("The program is now terminated");

Java String Concatenation error in output

I'm a beginner in Java and got this school problem:
The authority of XYZ gated residential colony wants its residents' name datum Should be stored in the following format - residents' name his/her father's name. Write a program to concat the father's name to the residents' name. The name should be validated,on validation the name should contain only alphabets and space is allowed. If the name is not valid display the message "Invalid name". If valid string then convert it to uppercase and print it
Sample Input 1:
Inmate's name:Aron
Inmate's father's name:Terby
Sample Output 1:
ARON TERBY
Error: It prints out "Invalid Input" whenever I enter a two-letter Inmate's name like- Aron Kumar otherwise for a single word string input code works alright.
This was the code I wrote:
Scanner sc=new Scanner(System.in);
System.out.println("Inmate's name:"); //if I enter 2 word string,output-"Invalid name1"//
String name=sc.nextLine();
System.out.println("Inmate's father's name:");
String fname=sc.nextLine();
String s3=name.toUpperCase();
String s4=fname.toUpperCase();
char[] a1= s3.toCharArray();
char[] a2= s4.toCharArray();
for(int i=0;i<a1.length;i++)
{
if(a1[i]>='A' && a1[i]<='Z')
count=1;
else {
System.out.print("Invalid name1");
count=0;
break; }
}
if(count==1)
{
for(int i=0;i<a2.length;i++)
{
if(a2[i]>='A' && a2[i]<='Z')
count=2;
else {
System.out.print("Invalid name");
break; }
}
}
if(count==2) {
System.out.print(s3+" "+s4);
}
}
}
The problem is that you are not checking for a space character. Check it as follows:
if (a1[i] >= 'A' && a1[i] <= 'Z' || a1[i] == ' ')
Another problem with your code is changing the value of count to 1 and 2 in each iteration whereas it should be changed when the loop terminates. Given below is the corrected code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int count = 0, i;
Scanner sc = new Scanner(System.in);
System.out.println("Inmate's name:");
String name = sc.nextLine();
System.out.println("Inmate's father's name:");
String fname = sc.nextLine();
String s3 = name.toUpperCase();
String s4 = fname.toUpperCase();
char[] a1 = s3.toCharArray();
char[] a2 = s4.toCharArray();
for (i = 0; i < a1.length; i++) {
if (!(a1[i] >= 'A' && a1[i] <= 'Z' || a1[i] == ' ')) {
System.out.print("Invalid name1");
count = 0;
break;
}
}
// If 'i' reached a1.length, it means no invalid character was found
if (i == a1.length) {
count = 1;
}
if (count == 1) {
for (i = 0; i < a2.length; i++) {
if (!(a2[i] >= 'A' && a2[i] <= 'Z' || a2[i] == ' ')) {
System.out.print("Invalid name");
break;
}
}
// If 'i' reached a2.length, it means no invalid character was found
if (i == a2.length) {
count = 2;
}
}
if (count == 2) {
System.out.print(s3 + " " + s4);
}
}
}
Additional note:
You can make your code much shorter by using regex as follows:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Inmate's name: ");
String name = sc.nextLine();
System.out.print("Inmate's father's name: ");
String fname = sc.nextLine();
if (name.matches("[A-Za-z\\s]+") && fname.matches(("[A-Za-z\\s]+"))) {
System.out.println(name.toUpperCase() + " " + fname.toUpperCase());
} else if (!name.matches("[A-Za-z\\s]+")) {
System.out.println("Inmate's name is invalid");
} else if (!fname.matches(("[A-Za-z\\s]+"))) {
System.out.println("Inmate's father's name is invalid");
}
}
}
The explanation of the regex, [A-Za-z\\s]+:
A-Za-z is for alphabets.
\\s is for space.
The + at the end of [A-Za-z\\s]+ means more than one occurrences are allowed.
A sample run:
Inmate's name: Ram Kumar
Inmate's father's name: Raj Kumar
RAM KUMAR RAJ KUMAR
Another sample run:
Inmate's name: Ram5 Kumar
Inmate's father's name: Raj Kumar
Inmate's name is invalid
Another sample run:
Inmate's name: Ram Kumar
Inmate's father's name: Raj5 Kumar
Inmate's father's name is invalid
When you compare char values in Java, you're relying on the ASCII value of that char. The ASCII value of A is 65, whereas the ASCII value of Z is 90.
Your current code is simply evaluating each char in the character array to make sure it's in the range of 65 to 90, inclusive. The ASCII value of the space char, however, is 32, falling well outside of that range.
Rewrite your code to accept capital letters or spaces (as dictated by the problem description) like so:
if((a1[i]>='A' && a1[i]<='Z') || (a1[i] == 32))
It happens because here
if(a1[i]>='A' && a1[i]<='Z') count=1;
You asking "if char in array is between A and Z, then count = 1"
But in case with name "Aron Kumar" You have a space symbol between two words and this space symbol is not between A and Z, so count don't equals 1 and output is "Invalid Input".
You have to check char array for space too.
You can take the answer of MarsAtomic as a good example.
import java.util.Scanner;
import java.util.regex.*;
public class Authority{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Inmate's name:");
String Inmate = s.nextLine();
System.out.println("Inmate's father's name:");
String father = s.nextLine();
if(!Pattern.matches("^[a-zA-Z\\s]+",Inmate))
{
System.out.println("Invalid name");
}
else if(!Pattern.matches("^[a-zA-Z\\s]+",father))
{
System.out.println("Invalid name");
}
else
{
String k = Inmate +" "+ father;
System.out.println(k.toUpperCase());
}
}
}

Java not showing last letter of string correctly?

So I have this little program and all it needs to do is check if the last letter of the last name is an "s". And if it is an "s" itll change the last name to plural.
Ex.
Smith = Smith's
Smiths = Smiths'
Changes the last name to plural. Simple right? Seems so, but my if statement isnt detecting if the last letter is an "s"
Here's some code
import javax.swing.JOptionPane;
public class Lastname {
public static void main(String[] args) {
String messageText = null;
String title = null;
int messageType = 0;
String lastName = "";
String pluralLastName = "";
Input input;
input = new Input();
messageText = "Please enter a last name. I'll make it plural.";
title = "Plural Last Names";
messageType = 3;
lastName = input.getString(messageText,title,messageType);
int intLength = lastName.length();
String lastLetter = lastName.substring(intLength- 1);
System.out.println("The last letter is: " + lastLetter);
if (lastLetter.equals('s'))
JOptionPane.showMessageDialog(null, "The last name entered as plural is " + lastName + "'" );
else
JOptionPane.showMessageDialog(null, "The last name entered as plural is " + lastName + "'s" );
}}
The if statement always just adds an "'s" to everything.
You need to use double quotes to represent a String literal.
if (lastLetter.equals("s"))
Otherwise you are comparing a String with a Character which will always return false.
Instead of comparing Strings, you can compare chars:
char lastLetter = lastName.charAt(intLength- 1);
System.out.println("The last letter is: " + lastLetter);
if (lastLetter == 's')
Right now, you are comparing Strings to chars.

NumberFormatException for Input String Java

I am writing an appointment program in Java and am coming across an error which is
Exception in thread "main" java.lang.NumberFormatException: For input string : ""
for the following lines :
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:470)
at java.lang.Integer.parseInt(Integer.java:499)
at AppointmentNew.main(AppointmentNew.java:24)
The program is going through once, but once it gets to the end of its first run it gives me those errors.... For instance when I run the program as follows : I make the choice of "1" to make a new appointment, I then enter the date of my new appointment "mm/dd/yyyy", then I add an appointment description, and lastly I enter the type "Once, Daily, or Monthly". After that finishes it should start back over with the very first line of "Make Choice (1: New, 2: Print Range, 3: Print All, quit):" But instead it gives me the errors I described above...
Here is my code I have.
import java.util.*;
public class AppointmentNew
{
public static void main (String[] args)
{
ArrayList<String> list = new ArrayList<String>();
Scanner stdin = new Scanner(System.in);
String choice = "";
int choiceNum = 0;
String date = "";
String descrip = "";
int type = 0;
String typeChose = "";
System.out.println("Welcome to Appointment App!\n");
System.out.println("\t============================\n");
do
{
System.out.print("\tMake Choice ( 1: New, 2: Print Range, 3: Print All, quit): ");
choice = stdin.nextLine();
choiceNum = Integer.parseInt(choice);
if (choiceNum == 1)
{
System.out.print("\n\n\tEnter New Appointment Date in mm/dd/yyyy format: ");
date = stdin.nextLine();
System.out.print("\n\n\tEnter New Appointment Description: ");
descrip = stdin.nextLine();
System.out.print("\n\n\tEnter Type (1 = Once, 2 = Daily, 3 = Monthly): ");
type = stdin.nextInt();
if (type == 1)
{
Once once = new Once(date, descrip);
typeChose = "One-Time";
}
else if (type == 2)
{
Daily daily = new Daily(date, descrip);
typeChose = "Daily";
}
else
{
Monthly monthly = new Monthly(date, descrip);
typeChose = "Monthly";
}
String stringToAdd = "";
stringToAdd = ("\n\n\tNew " + typeChose + " Appointment Added for " + date + "\n");
list.add(stringToAdd);
System.out.println(stringToAdd);
System.out.println("\t============================\n");
}
if (choiceNum == 2)
{
System.out.print("\n\n\tEnter START Date in mm/dd/yyyy format: ");
String lowDate = stdin.nextLine();
System.out.print("\n\n\tEnter END Date in mm/dd/yyyy format: ");
String highDate = stdin.nextLine();
for(int i = 0; i < list.size(); i++)
{
int dateSpot = list.get(i).indexOf(" ");
if (list.get(i).compareTo(lowDate) <= 0 && list.get(i).compareTo(highDate) >= 0)
{
System.out.println(list.get(i));
}}
}
if (choiceNum == 3)
{
for(int i = 0; i < list.size(); i++)
{
System.out.println(list.get(i));
}
}
}while (choice != "quit");
}
}
Any help would be great!
You need to add another call to nextLine() after this statement here:
type = stdin.nextInt();
// ED: stdin.nextLine();
This is because, when you grab an int from the Scanner, it doesn't consume the '\n' character that gets put on the input stream when the user hits enter.
Thus, when stdin.nextLine() is called again, the String "" is returned (everything not yet processed up to the next '\n' character), and Integer.parseInt doesn't know how to handle that, so you get an error.
Surround the code with an if statement to check if the value is not quit before trying to Parse it.

Categories