So , im having a piece of trouble here , tried with tutorials to fix it but nothing really helped me out saw something about printout string 0,1 etc but didnt work eather.
What the program does atm : Asks user for first/last name and prints it out first +last name
what i want it to do is print out the intisials of the users first and last name, any ideas how to fix this? Please help , Thanks in advance!
My code looks like this atm
package com.example.sträng.main;
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
String firstName,
lastName;
//Create scanner to obtain user input
Scanner scanner1 = new Scanner( System.in );
//obtain user input
System.out.print("Enter your first name: ");
firstName = scanner1.nextLine();
System.out.print("Enter your last name: ");
lastName = scanner1.nextLine();
//output information
System.out.print("Your first name is " + firstName + " and your last name is "+ lastName);
}
}
You get the 21st character from a String using String.charAt(21).
How to get the initials, I leave as an excercise for you.
Please note, that char is a strange datatype in Java. It represents a character, but works like a number, that's why you get a strange number if you "concatenate" two chars. If you want to create a String out of chars, you have some options, such as:
char c1;
char c2;
String str = "" + c1 + c2;
or
char c1;
char c2;
String str = new String(new char[] {c1, c2});
String firstInitial = firstName.substring(0,1);
String secondInitial = lastName.substring(0,1);
Related
example of output should be
please help thank you in advance!!
the output of the code in username should be the 2 letter in firt name and 3 in last name and date number
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Enter Fullname:");
String fullname = sc.nextLine();
System.out.println("Enter Birthday : ");
String bday = sc.nextLine();
System.out.println("Your Login Details");
System.out.println("Enter Fullname:" + fullname);
System.out.println("Enter Birthday : " + bday);
System.out.println("Enter Username: " + );
}
}
Assuming the input will always be in the format you provided, you can use String.split() and String.substring() to extract the required information from the input as shown below.
String[] splitName = fullName.split(" ");
String firstName = splitName[0];
String lastName = splitName[1];
String day = bday.split("-")[1];
String username = firstName.substring(0, 2) + lastName.substring(0, 3) + day;
You can use this code to achieve the expected result. The name should always be in this format FirstName LastName, otherwise, you may encounter NullPointerException more frequently. There are split and substring methods in the string class. Follow these steps to get started
Full name should be split into two strings, the first is for the first name and another is for the last name, for this we will use the split method which returns String[].
After splitting the full name, the substring method comes into the picture, substring method takes two parameters first and the last index. We can use this method with both strings received by the split method.
String[] firstLastName = fullname.split(" ");
System.out.println("Enter Username: " + firstLastName[0].substring(0, 2) + firstLastName[1].substring(0, 3) + bday.split("-")[1]);
Syntax
Public String [] split ( String regex, int limit)
public String substring(int begIndex, int endIndex)
I am working through a piece of self study, Essentially I am to ask the User for a string input such as "John, Doe" IF the string doesnt have a comma, I am to display an error, and prompt the user until the string does indeed have a comma (Fixed.). Once this is achieved I need to parse the string from the comma, and any combination of comma that can occur (i.e. John, doe or John , doe or John ,doe) then using the Scanner class I need to grab John doe, and split them up to be separately printed later.
So far I know how to use the scanner class to grab certain amounts of string up to a whitespace, however what I want is to grab the "," but I haven't found a way to do this yet, I figured using the .next(pattern) of the scanner class would be what I need, as the way it was written should do exactly that. however im getting an exception InputMismatchException doing so.
Here is the code im working with:
while (!userInput.contains(",")) {
System.out.print("Enter a string seperated by a comma: ");
userInput = scnr.nextLine();
if (!userInput.contains(",")) {
System.out.println("Error, no comma present");
}
else {
String string1;
String string2;
Scanner inSS = new Scanner(userInput);
String commaHold;
commaHold = inSS. //FIXME this is where the problem is
string1 = inSS.next();
string2 = inSS.next();
System.out.println(string1 + " " + string2);
}
}
This can be achieved simply by splitting and checking that the result is an array of two Strings
String input = scnr.nextLine();
String [] names = input.split (",");
while (names.length != 2) {
System.out.println ("Enter with one comma");
input = scnr.nextLine();
names = input.split (",");
}
// now you can use names[0] and names[1]
edit
As you can see the code for inputting the data is duplicated and so could be refactored
So I am trying to make the program ask the user the following and get the following answer:
For example:
Type a 2nd Sentence Below:
This is a book (user inputs this)
Choose what string of characters do you want to replace:
book (user inputs this)
Choose what new string will be used in the replacement:
car (user inputs this)
The text after the replacement is: This is a car.
import java.util.*;
import java.util.Scanner;
public class StringManipulation {
public static void main(String[]args) {
/*This is where the user can type a second sentence*/
System.out.println("Type a 2nd Sentence Below:");
Scanner sd = new Scanner(System.in);
String typingtwo = sd.nextLine();
String sending;
/*Here the program will tell the user a message*/
System.out.println("This is your sentence in capital letters:");
sending = typingtwo.toUpperCase();
System.out.println(sending);
/*Here the program will tell the user another message*/
System.out.println("This is your sentence in lower letters:");
sending = typingtwo.toLowerCase();
System.out.println(sending);
System.out.print("Your Token Count:");
int FrequencyTwo = new StringTokenizer(sending, " ").countTokens();
System.out.println(FrequencyTwo);
String charactertwo = new String(typingtwo);
System.out.print("Your Character Length:");
System.out.println(charactertwo.length());
String repWords;
String newWord;
String nwords;
String twords;
System.out.println("Choose what string of characters do you want to
replace");
repWords = sd.next();
System.out.println("Choose what new string will be used in the replacement");
nwords = sc.next();
twords = typingtwo.replace(repWords,nwords);
System.out.printf("The text after the replacement is: %s \n",nwords);
}
}
I have tried everything but for some reason I keep getting the word that they chose at the end only. Pleas help!
try using Scanner.nextLine instead of Scanner.next
refer to the Java API documentation to understand the difference between the two
Here is another problem:
twords = typingtwo.replace(repWords,nwords);
System.out.printf("The text after the replacement is: %s \n",nwords);
You are printing nwords instead of twords.
Two errors i could see.
nwords = sc.next(); here it should give compilation error as scanner instance name is sd.
You are trying to print nwords at the end. it should be "twords".
I'm writing out a piece of a code that where I am trying to split up the user's input into 3 different arrays, by using the spaces in-between the values the user has entered. However, everytime i run the code i get the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Substring.main(Substring.java:18)
Java Result: 1
I have tried to use a different delimiter when entering the text and it has worked fine, e.g. using a / split the exact same input normally, and did what i wanted it to do thus far.
Any help would be appreciated!
Here's my code if needed
import java.util.Scanner;
public class Substring{
public static void main(String[]args){
Scanner user_input = new Scanner(System.in);
String fullname = ""; //declaring a variable so the user can enter their full name
String[] NameSplit = new String[2];
String FirstName;
String MiddleName;
String LastName;
System.out.println("Enter your full name (First Middle Last): ");
fullname = user_input.next(); //saving the user's name in the string fullname
NameSplit = fullname.split(" ");//We are splitting up the value of fullname every time there is a space between words
FirstName = NameSplit[0]; //Putting the values that are in the array into seperate string values, so they are easier to handle
MiddleName = NameSplit[1];
LastName = NameSplit[2];
System.out.println(fullname); //outputting the user's orginal input
System.out.println(LastName+ ", "+ FirstName +" "+ MiddleName);//outputting the last name first, then the first name, then the middle name
new StringBuilder(FirstName).reverse().toString();
System.out.println(FirstName);
}
}
Split is a regular expression, you can look for one or more spaces (" +") instead of just one space (" ").
String[] array = s.split(" +");
Or you can use Strint Tokenizer
String message = "MY name is ";
String delim = " \n\r\t,.;"; //insert here all delimitators
StringTokenizer st = new StringTokenizer(message,delim);
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
You have made mistakes at following places:
fullname = user_input.next();
It should be nextLine() instead of just next() since you want to read the complete line from the Scanner.
String[] NameSplit = new String[2];
There is no need for this step as you are doing NameSplit = user_input.split(...) later but it should be new String[3] instead of new String[2] since you are storing three entries i.e. First Name, Middle Name and the Last Name.
Here is the correct program:
class Substring {
public static void main (String[] args) throws java.lang.Exception {
Scanner user_input = new Scanner(System.in);
String[] NameSplit = new String[3];
String FirstName;
String MiddleName;
String LastName;
System.out.println("Enter your full name (First Middle Last): ");
String fullname = user_input.nextLine();
NameSplit = fullname.split(" ");
FirstName = NameSplit[0];
MiddleName = NameSplit[1];
LastName = NameSplit[2];
System.out.println(fullname);
System.out.println(LastName+ ", "+ FirstName +" "+ MiddleName);
new StringBuilder(FirstName).reverse().toString();
System.out.println(FirstName);
}
}
Output:
Enter your full name (First Middle Last): John Mayer Smith
Smith, John Mayer
John
java.util.Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
hence even though you entered 'Elvis John Presley' only 'Elvis' is stored in the fullName variable.
You can use BufferedReader to read full line:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
fullname = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
or you can change the default behavior of scanner by using:
user_input.useDelimiter("\n"); method.
The exception clearly tells that you are exceeding the array's length. The index 2 in LastName = NameSplit[2] is out of array's bounds. To get rid of the error you must:
1- Change String[] NameSplit = new String[2] to String[] NameSplit = new String[3] because the array length should be 3.
Read more here: [ How do I declare and initialize an array in Java? ]
Up to here the error is gone but the solution is not correct yet since NameSplit[1] and NameSplit[2] are null, because user_input.next(); reads only the first word (*basically until a whitespace (or '\n' if only one word) is detected). So:
2- Change user_input.next(); to user_input.nextLine(); because the nextLine() reads the entire line (*basically until a '\n' is detected)
Read more here: [ http://www.cs.utexas.edu/users/ndale/Scanner.html ]
The purpose of the program is to take the user input of his full name then break it down into his first name and last name(besides doing a few additional things).
It is supposed to split the String in half in between the whitespace, but I can only reference the first value of the split array, otherwise I get:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at FirstNameLastName.main(FirstNameLastName.java:41)
Here is the current code, any help would be appreciated:
import java.util.Scanner;
public class FirstNameLastName {
public static void main(String[] args) {
String fullName; //the users full name as he enters it
String fname; //the users first name
int fnameCount; //number of characters in fname
String lname; //the users last name;
int lnameCount; // counts amount of characters in lname
String init; //initials of the user, combination of first and last name
Scanner input = new Scanner(System.in);
System.out.println("Please input your first and last name with a space inbetween them");
fullName = input.next();
String[] parts = fullName.split("\\s+"); // creates an array within which the two split String values are stored
fname = parts [0];
lname = parts [1];
fnameCount = fname.length();
lnameCount = lname.length();
System.out.println(fname);
System.out.println(lname);
System.out.printf("Your first name is %s , which has %d characters" , fname , fnameChar);
System.out.println();
System.out.printf("Your last name is %s , which has %d characters" , lname , lnameChar);
System.out.println();
System.out.printf("Your initials are %c%c", fname.charAt(0),lname.charAt(0));
}
}
Your problem is
fullName = input.next();
which reads only a single word. You want it to be
fullName = input.nextLine();
which will read an entire line.