Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
In Java, I am creating a program that asks the user to think of someone they know.
Then, my program asks that they enter the first letter of their first name, and the last letter of their last name, with no spaces.
I want my program to then look through an array of whole names, find the one whose first letter matches the first letter of user input, with the corresponding last letter of their last name.
here is my program so far:
import java.util.* ;
public class Guesser
{
public static void main(String[] args)
{
Scanner UserInput = new Scanner(System.in);
String [] names = {"firstname lastname " + "etc"}; //example name array
System.out.print( "Hello! I am a robot. I might be smart, but I don't know. Please play a game with me to help me see if I am smart." + "\n" + "What I want you to do is think of someone you know." + "\n" + "Enter the first letter of their first name, and the last letter of their last name. Please no spaces. Then, press enter. " );
String TheirGuess = UserInput.nextLine(); //get their input, assign a string to it
System.out.println("You entered: " + TheirGuess);
char FirstChar = TheirGuess.charAt(0); // get the the first char
char SecondChar = TheirGuess.charAt(1); // get the second char
System.out.println("I will now think of someone whose first name starts with " + FirstChar + " and last name ends with " + SecondChar );
UserInput.close();
}
}
How would I search in my string array for a name that has FirstChar as the first character and SecondChar as the last char?
This can be done in 1 line of code.
// Assuming you have populated a Set (actually any Collection) of names
Set<String> names;
List<String> matchedNames = names.stream()
.filter(s -> s.matches(userInput.replaceAll("^.", "$0.*")))
.collect(Collectors.toList());
If you just want to print the matches, it's even simpler:
names.stream()
.filter(s -> s.matches(userInput.replaceAll("^.", "$0.*")))
.forEach(System.out::println);
This code recognises that you can have multiple matches.
Although this may seem like spoon feeding, value to you of this answer is figuring out how it works.
The efficient way to do this would be to use two TreeSet objects. One contains Names and the other contains Last names. Then you can use subSet() method to get entries. So, example:
TreeSet<String> names = new TreeSet<>();
names.add("Antonio");
names.add("Bernard");
names.add("Peter");
names.add("Zack");
Set<String> bNames = names.subSet("B", "C");
Note, that this implementation is case sensitive. But with few adjustments you can fix it - I'm leaving this to you.
Havn't written in Java for a while, but it should go something like this:
String names[] = new String[] { "AAA BBB", "CCC DDD", "EEE FFF" };
Scanner input = new Scanner(System.in);
String userInput = input.nextLine().toLowerCase();
String result = "None";
for (String name : names) {
String[] nameSplitted = name.toLowerCase().split(" ");
if (nameSplitted[0].charAt(0) == userInput.charAt(0) &&
nameSplitted[1].charAt(0) == userInput.charAt(1)
) {
result = name;
break;
}
}
System.out.println("Result is: " + result);
Related
How do I print only the first letter of the first word and the whole word of the last? for example,
I will request username input like "Enter your first and last name" and then if I type my name like "Peter Griffin", I want to print only "P and Griffin". I hope this question make sense. Please, help. I'm a complete beginner as you can tell.
Here is my code:
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.println("Enter your first and last name");
String fname=scan.next();
}
The String methods trim, substring, indexof, lastindexof, and maybe split should get you going.
This should do the work (typed directly here, so syntax errors might be there)
String fname=scan.nextLine(); // or however you would read whole line
String parts=fname.split(" ");
System.out.printf("%s %s",parts[0].substring(0,1),parts[parts.length-1]);
What you have to do next:
Check if there actually at least 2 elements in parts array
Check if first element is actually at least 1 char (no empty parts)
Check if there is actually line to read
Do your next homework yourself, otherwise you will not anything
I recommand you to watch subString(1, x) and indexOf(" ") to cut from index 1 to first space.
or here a other exemple, dealing with lower and multi name :
String s = "peter griffin foobar";
String[] splitted = s.toLowerCase().split(" ");
StringBuilder results = new StringBuilder();
results.append(String.valueOf(splitted[0].charAt(0)).toUpperCase() + " ");
for (int i = 1; i < splitted.length; i++) {
results.append(splitted[i].substring(0, 1).toUpperCase() + splitted[i].substring(1)+" ");
}
System.out.println(results.toString());
I want the user to input a String, lets say his or her name. The name can be Jessica or Steve. I want the program to recognize the string but only output the first three letters. It can really be any number of letters I decide I want to output (in this case 3), and yes, I have tried
charAt();
However, I do not want to hard code a string in the program, I want a user input. So it throws me an error. The code below is what I have.
public static void main(String args[]){
Scanner Name = new Scanner(System.in);
System.out.print("Insert Name here ");
System.out.print(Name.nextLine());
System.out.println();
for(int i=0; i<=2; i++){
System.out.println(Name.next(i));
}
}
the error occurs at
System.out.println(Name.next(i)); it underlines the .next area and it gives me an error that states,
"The Method next(String) in the type Scanner is not applicable for arguments (int)"
Now I know my output is supposed to be a of a string type for every iteration it should be a int, such that 0 is the first index of the string 1 should be the second and 2 should be the third index, but its a char creating a string and I get confused.
System.out.println("Enter string");
Scanner name = new Scanner(System.in);
String str= name.next();
System.out.println("Enter number of chars to be displayed");
Scanner chars = new Scanner(System.in);
int a = chars.nextInt();
System.out.println(str.substring(0, Math.min(str.length(), a)));
The char type has been essentially broken since Java 2, and legacy since Java 5. As a 16-bit value, char is physically incapable of representing most characters.
Instead, use code point integer numbers to work with individual characters.
Call String#codePoints to get an IntStream of the code point for each character.
Truncate the stream by calling limit while passing the number of characters you want.
Build a new String with resulting text by passing references to methods found on the StringBuilder class.
int limit = 3 ; // How many characters to pull from each name.
String output =
"Jessica"
.codePoints()
.limit( limit )
.collect(
StringBuilder::new,
StringBuilder::appendCodePoint,
StringBuilder::append
)
.toString()
;
Jes
When you take entry from a User it's always a good idea to validate the input to ensure it will meet the rules of your code so as not to initiate Exceptions (errors). If the entry by the User is found to be invalid then provide the opportunity for the User to enter a correct response, for example:
Scanner userInput = new Scanner(System.in);
String name = "";
// Prompt loop....
while (name.isEmpty()) {
System.out.print("Please enter Name here: --> ");
/* Get the name entry from User and trim the entry
of any possible leading or triling whitespaces. */
name = userInput.nextLine().trim();
/* Validate Entry...
If the entry is blank, just one or more whitespaces,
or is less than 3 characters in length then inform
the User of an invalid entry an to try again. */
if (name.isEmpty() || name.length() < 3) {
System.out.println("Invalid Entry (" + name + ")!\n"
+ "Name must be at least 3 characters in length!\n"
+ "Try Again...\n");
name = "";
}
}
/* If we get to this point then the entry meets our
validation rules. Now we get the first three
characters from the input name and display it. */
String shortName = name.substring(0, 3);
System.out.println();
System.out.println("Name supplied: --> " + name);
System.out.println("Short Name: --> " + shortName);
As you can see in the code above the String#substring() method is used to get the first three characters of the string (name) entered by the User.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am trying to compare string_1 to string_2 to see if it is equal to each other, and I am trying to make an individual string be completely capitalized or under-cased.
import java.util.Scanner;
public class StringMethods
{
public static void main (String [] args)
{
Scanner s=new Scanner (System.in);
String string_1= s.next();
String string_2= s.next();
System.out.println ("a) Determine the length of string_1: " +string_1.length()+ "/t b) Determine the length of string_2: " +string_2.length()+"/tc) Concatenate both strings: " +string_1.concat(string_2)+"/td) Check if the two strings have same set of characters with regard to case: ");
if (string_1.equaltoIgnoreCase(string_2))
{
System.out.print ("equal.");
}
if ((string_1.comparetoIgnoreCase(string_2)>0)||(string_1.comparetoIgnoreCase(string_2)<0))
{
System.out.print ("They are not equal.");
}
System.out.println ("e) Convert string_1 to upper case: " +string_1.toUpperCase()+"/tf) Convert string_2 to lower case: " +string_2.toUnderCase()+"/tg) Extract a valid sub-string of multiple characters from string_1: " +string_1.substring(0,string_1.length));
}}
You have a lot of spelling and punctuation errors throughout your code. I would highly suggest using an IDE like IntelliJ to prevent this. I went ahead and fixed the typo's, but it looks like you will need to do some work as far as the way the program is currently running. For instance, the program is asking for input before the user even knows WHAT to input.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String string_1 = s.next();
String string_2 = s.next();
System.out.println("a) Determine the length of string_1: " +
string_1.length() + "/t b) Determine the length of " +
"string_2: " + string_2.length() + "/tc) Concatenate both
strings: " + string_1.concat(string_2) + "/td) " +
"Check if the two strings have same set of characters
with regard to case: ");
if (string_1.equalsIgnoreCase(string_2)) {
System.out.print("equal.");`enter code here`
}
if ((string_1.compareToIgnoreCase(string_2) > 0) ||
(string_1.compareToIgnoreCase(string_2) < 0)) {
System.out.print("They are not equal.");
}
System.out.println("e) Convert string_1 to upper case: " +
string_1.toUpperCase() + "/tf) Convert string_2 to " +
"lower case: " + string_2.toLowerCase() + "/tg) Extract a
valid sub-string of multiple characters from string_1: " +
string_1.substring(0, string_1.length()));
}
}
Edit Thanks for the help guys got it working now.
So I had a question to do to ask a user for first name and last name which I have done no problem but then I thought it's be good to expand the program so that if someone entered a surname like McCabe it would print T McC instead of TM. I'm just not sure about how to compare the first two letters of the secondname string to see if they are "mc".
public class InitialsAlt {
public static void main(String [] args){
Scanner keyboardIn = new Scanner (System.in);
String firstname = new String();
System.out.print (" Enter your first name ");
firstname = keyboardIn.nextLine();
String secondname = new String();
System.out.print (" Enter your second name ");
secondname = keyboardIn.nextLine();
if(secondname.charAt(0, 1)== "mc" ) {
System.out.print("Your initals are " + firstname.charAt(0)+ secondname.charAt(0,1,2));
}
else {
System.out.print("Your initals are " + firstname.charAt(0)+ secondname.charAt(0));
}
}
}
if (secondName.toLowerCase().startsWith("mc")) {
The easiest way is to use String.startsWith:
yourString.toLowerCase().startsWith("mc")
If you want to avoid lowercasing the entire string or creating a new object, only to check the first two characters:
yourString.length() >= 2
&& Character.toLowerCase(yourString.charAt(0)) == 'm'
&& Character.toLowerCase(yourString.charAt(1)) == 'c'
However, I would use the former solution as it is far more readable, and the performance hit from lowercasing the entire string is almost certainly negligible, unless you are doing this on quite large strings.
Use yourString.toLowerCase().indexOf("mc")==0. This will involve creation of a new String only once (Since indexOf() doesn't create a new one, using indexOf() would be better than using subString() here)
Use substring to get the first two letters, then convert to lowercase, then check to see if it equals:
String someString = "McElroy";
if (someString.subString(0,2).toLowerCase().equals("mc")) {
//do something
}
If its case insensitive you could use the Apache Commons Lang library:
if(StringUtils.startsWithIgnoreCase(secondname, "mc") {
// Do nice stuff
}
Otherwise, you can use:
if(StringUtils.startsWith(secondname.toLowerCase(), "mc") {
// Do nice stuff
}
having problems doing something for a class I'm taking, since I missed a class or two. (I know it's looked down on to 'do someone's homework,' but I'm not looking for that.)
The assignment is as follows:
Write a program to do the following:
Prompt for input of someone's first, middle, and last name as a single string (using any combination of upper and lowercase letters).
Check to make sure the name was entered in the correct format (3 names separated by spaces). If the input is not correct, continue to request the input again until the format is correct.
Capitalize only the first letters of each part of the name, and print out the revised name.
Print out the initials for that name.
Print out the name in the format of: Lastname, Firstname, MI.
The major problem I'm having is the second part of the assignment; I got the first part, and I'm fairly sure I can manage through the rest, after I get the second set up.
import java.util.*;
public class TestStrings
{
public static void main(String[] args)
{
Scanner key = new Scanner(System.in);
String name;
System.out.print("Enter your name as 'First Middle Last': ");
name = key.nextLine();
}
}
From what I've gathered, I need to use the string.split? I'm not sure how to go about this, though, since I need to check to make sure there are three spaces, that aren't just right next to each other or something, such as "John(three spaces)Doe". I assume it's going to be some kind of loop to check through the input for the name.
The catch 22, is that I can't use arrays, or StringTokenizer. I must use the substring method.
Any help would be appreciated. Thanks. :D
To point you in the right direction to find the first name(since you cant use arrays):
String firstName = input.substring(0, input.indexOf(" "));
This will get you a substring from the start to the first space. If you research the indexOf and substring methods you should be able to go from there.
Look at the matches method if you know how to use regex. If not think about indexOf and substring methods.
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html
You can use the substring and the indexOf functions of String class to get what you need.
String#indexOf: Get's the position of a String inside a String.
String#substring: Get's a substring contained in a String.
String s = "Luiggi Mendoza J.";
String x;
while(s.indexOf(" ") > 0) {
x = s.substring(0, s.indexOf(" "));
System.out.println(x);
s = s.substring(s.indexOf(" ") + 1);
}
x = s;
System.out.println(x);
The program output will be:
Luiggi
Mendoza
J.
Use a while loop to continuously check whether user entered a string that consists of 3 parts which are seperated via a single space character ' ', then use split() function to verify 3 parts of string. By using substring() as demonstrated here you can get names seperately:
public static void main ( String [] args )
{
String name = "";
boolean ok = false;
Scanner key = new Scanner( System.in );
while ( !ok )
{
System.out.print( "Enter your name as 'First Middle Last': " );
name = key.nextLine();
try
{
if ( name.split( " " ).length == 3 )
ok = true;
}
catch ( Exception e ){ }
}
if ( ok )
{
String firstName = name.substring(0, name.indexOf(" "));
String middleName = name.substring(firstName.length()+1,
name.lastIndexOf(" "));
String surname = name.substring(middleName.length()+firstName.length()+2,
name.length());
}
}
This works using Pattern/Matcher and regexs. Also guards against strings of length 1 when adjusting case.
private static String properCase(String str) {
return str.substring(0, 1).toUpperCase()
+ (str.length() >= 1 ? str.substring(1).toLowerCase() : "");
}
public static void main(String[] args) {
boolean found = false;
do {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name as 'First Middle Last': ");
Pattern p = Pattern.compile("\\s*(\\w+?)\\s(\\w+?)\\s(\\w+)+\\s*");
Matcher m = p.matcher(scanner.nextLine());
found = m.find();
if (found) {
String first = m.group(1);
String middle = m.group(2);
String last = m.group(3);
String revised = properCase(first) + " " + properCase(middle)
+ " " + properCase(last);
System.out.println(revised);
System.out
.printf("%s %s %s.\n", properCase(last),
properCase(first), middle.substring(0, 1)
.toUpperCase());
}
} while (!found);
}