I am trying to write a static method named longestName that reads names typed by the user and prints the longest name (the name that contains the most characters).
The longest name should be printed with its first letter capitalized and all subsequent letters in lowercase, regardless of the capitalization the user used when typing in the name. If there is a tie for longest between two or more names, use the tied name that was typed earliest. Also print a message saying that there was a tie, as in the right log below.
In the event some of shorter names tie in length, such as DANE and Erik ; but don't print a message unless the tie is between the longest names.
public static void longestName(Scanner console, int n) {
String name = "";
String longest= "";
boolean areTies = false;
for(int i=1; i<=n; i++) {
System.out.print("Enter name #" + i + ":");
name = console.next();
if(name.length( ) > longest.length( )) {
longest = name;
areTies = false;
}
if(name.length( ) == longest.length( ) ) {
areTies = true;
}
}
// now change name to all lower case, then change the first letter
longest = longest.toLowerCase( );
longest = Character.toUpperCase (longest.charAt( 0 ) ) + longest.substring(1);
System.out.println(longest + "'s name is longest");
if(areTies==true) {
System.out.println(" (There was a tie! ) " );
}else{
System.out.println();
}
}
My output is :
Enter name #1:roy
Enter name #2:DANE
Enter name #3:Erik
Enter name #4:sTeFaNiE
Enter name #5:LaurA
Stefanie's name is longest
(There was a tie! )
It will just print there was a tie for every invokation.I have no idea why.
Secondly,
longest = longest.toLowerCase( );
longest = Character.toUpperCase (longest.charAt( 0 ) ) + longest.substring(1);
My friend taught me to use this to retrieve the word but i still dont understand.Is there other way of doing it?It is very complicated for me.
You have a problem with your logic. When you find a new longest name (first if statement), you set longest to be name. Then the second if executes. Because at this point longest refers to the same object as name, of course their lengths are equal. To avoid this, just insert an else.
else if(name.length( ) == longest.length( ) ) {
Let's break down how it's changed to first character uppercase, rest lowercase.
longest = longest.toLowerCase( );
Now longest is all lowercased.
Character.toUpperCase (longest.charAt( 0 ) )
This takes the first character and uppercases it.
longest.substring(1);
This takes the substring starting at index 1 (the second character) through the end of the string, which is concatenated with the uppercased character.
import java.util.*;
public class Longest {
public static void main(String[] args)
{ Scanner input = new Scanner(System.in);
System.out.print("Enter the number of names you wanna enter? ");
int n = input.nextInt(); // takes number of names
longestName(input,n); // function call
}
public static void longestName(Scanner input, int n)
{
String name = ""; // First assign name to the empty string
String longest = ""; // First assign longest to the empty string
boolean areTies = false; // Assume there are no ties at first place
for(int i = 1; i <= n; i++) // run a loop n times
{
System.out.print("Enter name #"+i+":");
name = input.next(); // takes ith name
if(name.length() > longest.length()) /*if length of the entered new string is greater than current longest*/
{
longest = name;
areTies = false; // no tie
}
else if(name.length() == longest.length()) /*if both strings are of same length*/
areTies = true; // so boolean value of areTies is true
}
// now change the name to the lower case and then change only first letter to the upper case
longest = longest.toLowerCase(); // changes entire string to lowercase
longest = Character.toUpperCase(longest.charAt(0)) + longest.substring(1); /* first char to upper and rest remains as it is and concatenate char and remaining string from index 1 to rest*/
System.out.println(longest + "'s name is longest");
if(areTies==true) {
System.out.println(" (There was a tie! ) " );
}else{
System.out.println();
}
}
}
public static void longestName(Scanner console, int names) {
String longest = "";
boolean tie = false;
for ( int i = 1; i <= names; i++){
System.out.print("name #" + i + "? ");
String name = console.nextLine();
if (name.length() == longest.length()){
tie = true;
}
if (name.length() > longest.length()){
longest = name;
tie = false;
}
}
longest = longest.toLowerCase();
System.out.print(longest.substring(0,1).toUpperCase());
System.out.println(longest.substring(1) + "'s name is longest");
if (tie){
System.out.println("(There was a tie!)");
}
}
Related
This project is used to identify whether or not a user's input is a palindrome, and if it's not, identifies how many characters don't match and their positions in the string (i.e characters 2 and 4 don't match). I've been able to figure out how to identify whether or not a string is a palindrome, but I'm struggling with how to specifically identify the characters that don't match in a non-palindrome. Here's my code so far:
import java.util.Scanner;
public class Palindrome
{
public static void main(String[] args)
{
String stringInput = "";
String inputReverse = "";
boolean isPalindrome = true;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a string: ");
stringInput = keyboard.nextLine();
int stringLength = stringInput.length();
for(int i = stringLength - 1; i >=0; i--)
{
inputReverse = inputReverse + stringInput.charAt(i);
}
if(stringInput.equals(inputReverse))
{
System.out.println(stringInput + " is a valid palindrome.");
}
else
{
System.out.println(stringInput + " is not a valid palindrome.");
}
}
}
the output I want for when a string is not a palindrome is:
"The characters at index 0 and 3 do not match.
goop is not a valid palindrome.
number of invalid character matches: 1 "
I tried to use stringInput.charAt(0) but the user input is unpredictable, so I wouldn't be able to use char 0,1,2,3 etc forever. Any help?
Iterate from both ends of the string, moving toward the center and checking the corresponding characters each time.
int nomatch = 0;
for (int i = 0, j = stringLength - 1; i < j; i++, j--) {
if (stringInput.charAt(i) != stringInput.charAt(j)) {
++nomatch;
System.out.format("The characters at index %d and %d do not match.%n", i, j);
}
}
if (nomatch == 0) System.out.println(stringInput + " is a palindrome.");
else System.out.println(stringInput + " is not a palindrome. Number of invalid character matches: " + nomatch);
As this is home work, I'll only give general hints:
an easy way to reverse a string is inputReverse = new StringBuilder(stringInput).reverse().toString();
you only need to compare each character of the first half of the input with its reverse
use a for loop of int from 0 to half the length and pass it to charAt() for both strings and compare using ==
store the indexes of differences in a List<Integer>
I want to print a letter instead of the index position using the indexOf(); method.
The requirement is that: Inputs a second string from the user. Outputs the character after the first instance of the string in the phrase. If the string is not in the phrase, outputs a statement to that effect. For example, the input is 3, upside down, d. The output should be "e", I got part of it working where it inputs an integer rather than a string of that particular position. How would I output a string?
else if (option == 3){
int first = 0;
String letter = keyboard.next();
first = phrase.indexOf(letter,1);
if (first == -1){
System.out.print("'"+letter+"' is not in '"+phrase+"'");
}
else {
System.out.print(first + 1);
}
}
String.charAt(index)
You can access a single character, or a letter, by caling método charAt() from String class
Example
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String phrase = keyboard.nextLine();
char firstLetter = phrase.charAt(0);
System.out.println("First Letter : " + firstLetter);
}
So, running this code, assuming the input is StackOverFlow, the output will be S
In your code I think doing the follow will work:
Your Code
String letter = keyboard.next();
first = letter.charAt(0);
That might help!
Based on those comments
So, what you want is print the first letter based on a letter the user
has input? For example, for the word Keyboard, and user inputs letter
'a' the first letter might be 'R'. Is that it? – Guerino Rodella
Yes, I have to combine both the indexOf(): method and the charAt():
method – Hussain123
The idea is get next letter based on user input letter.
I'm not sure I wunderstood it, but this is my shot
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String phrase = "keyboard";
String userInput = keyboard.nextLine();
boolean notContainsInputValue = !phrase.contains(userInput);
if (notContainsInputValue) {
System.out.println("The input value doesn't exists");
return;
}
char firstLetter = userInput.charAt(0);
int desiredIndex = 0;
for (int i = 0; i < phrase.length(); i++) {
if (phrase.charAt(i) == firstLetter) {
desiredIndex = i;
break;
}
}
System.out.println("The index for your input letter is: " + desiredIndex);
System.out.println("Next letter based on input value is: " + phrase.charAt(desiredIndex + 1));
}
The Output
The index for your input letter is: 5
Next letter based on input value is: r
Hope that helps you.
I am quite new to programming and I am writing this code to count a string (length) to a point when I encounter a space. The aim is - when the user enters his/her name AND surname, the program should split the name from surname and count how many letters/characters were there in the name (and surname).
My code doesn't seem to reach/execute the "if-statement", if I enter two strings (name & surname) separated by space (output: Your name is: (empty space) and it has 0 letters. However, if I enter only one string, the if-statement, it gets executed.
What I am doing wrong?
My example code:
public class Initials {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String nameAndSurname, nameOnly;
int c = 0, count = 0;
System.out.println("Enter your full name please:");
nameAndSurname = scan.nextLine();
int space = nameAndSurname.indexOf(' ');
for(int x = 0; x<=nameAndSurname.length()-1; x++) {
c++;
if(nameAndSurname.indexOf(x) == space) //if there is a space
{
count = c; //how many characters/letters was there before space
System.out.println(count);
}
}
nameOnly = nameAndSurname.substring(0, count);
System.out.println("Your name is: " + nameOnly.toUpperCase() + " and it has " + count + " letters");
scan.close();
}
Why bother with all that code? Just skip the for-loop, have an
if (space != -1) nameOnly = nameAndSurname.substring(0,space);
and if you really want to know the amount of letters, it is
space+1
No need for all that complicated stuff.
if(nameAndSurname.indexOf(x) == space)
This line isn't doing what you think it is doing.
It's getting a char (character) from the index of x, and comparing it to the value of space. Space is an integer, so you are comparing the character at position x to the integer position of the first space. In this case, the letter at position x is cast into an integer, and then compared to the actual number value of the first space!
To fix the program, replace your entire if statement with this.
if (nameAndSurname.charAt(x) == ' ') //if there is a space
{
count = c-1; //how many characters/letters was there before space
System.out.println(count);
}
Extra:
Since the way you've solved this problem is a bit overkill, I've posted another solution below which solves it in a way that is easier to read. Also it won't break if you put in more or less than 1 space.
Scanner scan = new Scanner(System.in);
String nameAndSurname;
System.out.println("Enter your full name please:");
nameAndSurname = scan.nextLine().trim();
int indexOfFirstSpace = nameAndSurname.indexOf(' ');
if (indexOfFirstSpace > -1) {
String firstName = nameAndSurname.substring(0, indexOfFirstSpace);
System.out.println("Your first name is " + firstName.toUpperCase());
System.out.println("It is " + firstName.length() + " characters long.");
}
You can verify if your string has space before start the loop, something like this:
public class Initials {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String nameAndSurname, nameOnly;
int c = 0, count = 0;
System.out.println("Enter your full name please:");
nameAndSurname = scan.nextLine();
int space = nameAndSurname.indexOf(' ');
if(space == -1) {
System.out.println("Your name has no spaces");
} else {
for(int x = 0; x<nameAndSurname.length(); x++) {
c++;
if(nameAndSurname.indexOf(x) == space) //if there is a space
{
count = c; //how many characters/letters was there before space
System.out.println(count);
}
}
nameOnly = nameAndSurname.substring(0, count);
System.out.println("Your name is: " + nameOnly.toUpperCase() + " and it has " + count + " letters");
}
scan.close();
}
I am writing my very first java program, I finally got it all written but on the assignment I need to add a function (other than main). My program counts the number of letter in first name, so I was thinking maybe I could add a function that reads how many letters are uppercase? Any ideas?
public class NameLetters{
public static void main(String []args){
Scanner in = new Scanner(System.in);
String firstName; //Asks for the users first name
int count=0; //Count the letters passing through loop
System.out.print("Hello, this program will ask for your first name and then output the number of letters in your name.");
System.out.print("Please enter your first name:");
String firstName = input.NextLine();
for (int i=0; i<firstName.length(); i++) {
if (firstName.charAt(i) != ' ')
Count ++;
}
system.out.print("There are "+Count+" s in the first name "+firstName+" , Thank you for participating. Goodbye!");
}
}
String s = "NaMe";
int upper = 0;
int lower = 0;
for(int i = 0; i<s.length();i++ ) {
int charASCII= (int)s.charAt(i);
if (charASCII <91 && charASCII > 64){
upper ++;
}
if (charASCII <123 && charASCII > 96){
lower ++;
}
}
System.out.print("Given name string contains "+upper+ " uppercase letters & "+lower + " lowercase letters");
I am new to java and I have been trying to solve a problem which I feel might have a simpler answer than my code.The problem was to print the initials of a user input name of any length along with the full surname.But this has to be done without any String.split() or arrays.I tried getting the user to input his name one word at a time, but is there any there a possible way to get the whole name at once and do as required.
My code is as follows:
import java.io.*;
public class Initials {
public static void main(String[]args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number of words your name contains");
int n=Integer.parseInt(br.readLine());
String str="";
for(int x=1;x<=n-1;x++){
System.out.println("Enter your name's word number:"+" "+x);
String s=br.readLine();
String st=s.toUpperCase();
char ch=st.charAt(0);
str=str+ch+".";
}
System.out.println("Enter your surname");
String sur=br.readLine();
str=str+" "+sur.toUpperCase();
System.out.println(str);
}
}
Use a regular expression (namely (?<=\w)\w+(?=\s)):
String name = "John Paul Jones"; // read this from the user
System.out.println(name.replaceAll("(?<=\\w)\\w+(?=\\s)", "."));
J. P. Jones
No split(), no arrays :)
A little explanation: We essentially want to replace all letters of each word that is followed by a whitespace character except the first letter, with a . character. To match such words, we use (?<=\w)\w+(?=\s):
(?<=\w) is a positive lookbehind; it checks that a word-character exists at the start of the match but does not include it in the match itself. We have this component because we don't want to match the first character of each name, but rather all but the first (except for the last name, which we'll deal with shortly).
\w+ matches any continuous string of word characters; we use this to match the rest of the name.
(?=\s) is a positive lookahead; it checks that our match is followed by a whitespace character, but does not include it in the match itself. We include this component because we don't want to replace anything on the last name, which should not be followed by a whitespace character and hence should not match the regular expression.
Another way around---
import java.util.Scanner;
//a class that will print your output
class Initial {
public void Initials() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Full name:");
String name = sc.nextLine();
int l = name.length();
int pos = 0;
for (int i = l - 1; i >= 0; i--) {
char ch = name.charAt(i);
if (ch == ' ') {
pos = i; //getting the last space before Surname
break;
}
}
System.out.print("The initials are: ");
System.out.print(name.charAt(0) + ".");//prints first name initial
// with dot
for (int x = 1; x < pos; x++) //finds midname initial
{
char ch = name.charAt(x);
if (ch == ' ') {
System.out.print(name.charAt(x + 1) + ".");
}
}
for (int i = pos; i < l; i++) { //for printing Surname
System.out.print(name.charAt(i));
}
}
}
public class Str {
public static void main(String[] args) {
Initial i = new Initial();
i.Initials();
}
}
//This code will work for any no. of words in the name
class Surnam {
public static void main(String name) {
name = " " + name;
int l=name.length(), p=0, m=0, r=0;
char y;
String word=" ", words=" ";
for(int i = 0; i = 0; i--) {
y=name.charAt(i);
if(y==' ') {
r=name.lastIndexOf(y); //extracting the last space of the string
word=name.substring(i,l); //extracting the surname
words=name.replace(word," "); //removing the surname break;
}
}
for (int i = 0; i <= r - 1; i++) {
char x=words.charAt(i);
if (x == ' ') {
System.out.print(words.charAt(i + 1) + "."); //Printing all initials before the surname with a dot
}
}
for (int i = l - 1; i >= 0; i--) {
char x=name.charAt(i);
if(x==' ') {
m=i;
name=name.substring(m,l); //extracting the surname
name=name.trim(); //removing all the spaces before the surname
System.out.print(name);
break;
}
}
}
}