So my goal is to rearrange a string that is inputted into the program so that it outputs the same info but in a different order. The input order is firstName middleName, lastName, emailAddress and the intended output is lastName, firstName first letter of middleName .
For example the input
John Jack,Brown,JJB#yahoo.com
would output
Brown, John J .
Here's what I have so far
import java.util.Scanner;
public class NameRearranged {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a name like D2L shows them: ");
String entireLine = keyboard.nextLine();
String[] fml = entireLine.split(",");
String newName = fml[0].substring(7);
String newLine = fml[1] + "," + newName + ".";
System.out.println(newLine);
}
public String substring(int endIndex) {
return null;
}
}
I can't figure out how to separate the firstName and middleName so I can substring() the first letter of the middleName followed by a .
This meets your required output.
import java.util.Scanner;
public class NameRearranged {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a name like D2L shows them: ");
String entireLine = keyboard.nextLine();
String[] fml = entireLine.split(","); //seperate the string by commas
String[] newName = fml[0].split(" "); //seperates the first element into
//a new array by spaces to hold first and middle name
//this will display the last name (fml[1]) then the first element in
//newName array and finally the first char of the second element in
//newName array to get your desired results.
String newLine = fml[1] + ", " + newName[0] + " "+newName[1].charAt(0)+".";
System.out.println(newLine);
}
}
Check this.
public class NameRearranged {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a name like D2L shows them: ");
System.out.println(rearrangeName(keyboard.nextLine()));
}
public static String rearrangeName(String inputName) {
String[] fml = inputName.split(" |,"); // Separate by space and ,
return fml[2] + ", " + fml[0] + " " + fml[1].charAt(0) + ".";
}
}
You need to delimit the string for spaces as well. And don't forget the alternate "|" character. Try the following.
String[] fml = entireLine.split(" |, ");
Related
I'm new to Java and I'm having a bit of trouble trying to call a variable (firstName) from another method to my main. Here is my code:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter full name: ");
String fullName = reader.nextLine();
System.out.print("Enter graduation year: ");
int gradYear = reader.nextInt();
System.out.print("Greetings, " + firstName + ", your initials are ");
}
public static void getFirstName(String fullName) {
Scanner reader = new Scanner(System.in);
String firstName = fullName.substring(0,1).toUpperCase() + fullName.substring(1).toLowerCase();
}
}
First of note that after using nextInt() the following nextLine() won't work.
I guess, this is what you are trying to do.
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter full name: ");
String fullName = reader.nextLine();
System.out.print("Enter graduation year: ");
int gradYear = reader.nextInt();
System.out.print("Greetings, " + getFirstName(fullName) + " your initial is, " + getInitial(fullName));
reader.close();
}
private static String getInitial(String fullName) {
return fullName.substring(0,1).toUpperCase();
}
public static String getFirstName(String fullName) {
return fullName.substring(1).toLowerCase();
}
You can return that value from a method and assign to a variable.
Let me show you.
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter full name: ");
String fullName = reader.nextLine();
System.out.print("Enter graduation year: ");
int gradYear = reader.nextInt();
String firstName = getFirstName(fullName);
System.out.print("Greetings, " + firstName + ", your initials are ");
}
public static String getFirstName(String fullName) {
// Scanner reader = new Scanner(System.in);
String firstName = fullName.substring(1).toLowerCase(); // assuming first letter is the initials; best would be to substring by space or similar
return firstName;
}
The purpose of my code is to ask the user for a string, but the user has to use the number "2" to replace the word "to". Then, in my method useProperGrammar, the program should replace the number "2" for the word "to". The method returns the corrected sentence along with the number of errors fixed, which indicates the purpose of the variable counter. However, when I execute my code, the corrected code nor the number of grammar mistakes is displayed, what is the problem with my method? I know I can use the static method ".replace()", but I wanted to know if there were any other ways to solve this problem.
import java.util.Scanner;
public class Grammar
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a sentence (replace \"to\" for the number \"2\")");
String begin = input.nextLine();
System.out.println(useProperGrammar(begin));
}
public static String useProperGrammar(String sentence)
{
int counter = 0;
for(int i = 0; i<sentence.length(); i++)
{
String character = sentence.substring(i, i+1);
if(character.equals("2"));
{
String front = sentence.substring(0, i);
String back = sentence.substring(i+1);
sentence = front + " to " + back;
counter++;
}
}
return sentence + "\nFixed " + counter + "grammatical errors:";
}
}
you need to remove the ; after if(character.equals("2"))
import java.util.Scanner;
public class Grammar
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a sentence (replace \"to\" for the number \"2\")");
String begin = input.nextLine();
System.out.println(useProperGrammar(begin));
}
public static String useProperGrammar(String sentence)
{
int counter = 0;
for(int i = 0; i<sentence.length(); i++)
{
String character = sentence.substring(i, i+1);
if(character.equals("2"))
{
String front = sentence.substring(0, i);
String back = sentence.substring(i+1);
sentence = front + " to " + back;
counter++;
}
}
return sentence + "\nFixed " + counter + "grammatical errors:";
}
}
I am asked to take input from a user, their first and last name in one string.
Then output their name, with their last name first then their first name.
I have finished everything but the part I am stuck on is how to show their first name then their last name, please help.
This is my code so far as requested
package chapter2Codes;
import java.util.Scanner;
public class StPrac1 {
public static void main(String[] args) {
String name;
System.out.println("Please your full name");
Scanner kbd = new Scanner( System.in );
name = kbd.nextLine();
System.out.print(name.substring(5,8) + (", ") + name.substring(0,));
}
}
If Firstname and Lastname are seperated by white-space then try this
var fullname = "Firstname Surname";
var fname = fullname.Split(" ")[0];
var sname = fullname.Split(" ")[1];
string output = sname + ", " + fname;
OR if you want to Avoid middle name
string fullName = "Firstname MidName LastName";
string[] names = fullName.Split(' ');
string fname = names.First();
string lname = names.Last();
string output = lname + ", " + fname;
OR use your delimeter in .Split('addyourdelimeterhere')
AS per your Code
public class StPrac1 {
public static void main(String[] args) {
String name;
System.out.println("Please your full name");
Scanner kbd = new Scanner( System.in );
name = kbd.nextLine();
string fname = name.Split(" ")[0];
string sname = name.Split(" ")[1];
string output = sname + ", " + fname;
System.out.print(output);
}
}
This is just an example not a perfect solution, It will be easy to help you if you can Post more detail
I have a tag maker class that needs to print out two tags. one needs to print out the user input, and then I have to clear the scanner buffer and print out an empty tag right afterwards. as of now, I get two tags that print the original user input.
package stupidtag;
import java.util.Scanner;
public class StupidTag {
String first;
String last;
String org;
String s;
Scanner scanMe = new Scanner(System.in);
public void setFirst(String first){
this.first = first;
}
public void setLast(String last){
this.last = last;
}
public void setOrganization(String org){
this.org = org;
}
void tagMaker() {
s = ("———————NAME TAG———————" + "\n" + "Name: " +
last + ", " + first + "\n" + "Organization: " + org +
"\n"+ "---------------------");
if((first.equals(first)) || (last.equals(last)) || (org.equals(org)))
{
System.out.println(s);
}
else{
System.out.println("Invalid input. Please try again.");
scanMe.nextLine(); // -->important
System.out.println();
}
scanMe.reset();
System.out.println(s);
}
}
}
and here's the tester:
import java.util.Scanner;
public class stupidTagTester {
public static void main(String args[]){
Scanner scanMe = new Scanner( System.in );
StupidTag tag = new StupidTag();
System.out.print("This program will print out a name tag");
System.out.println("for each delegate.");
System.out.println("Please enter first name:");
tag.first = scanMe.nextLine();
System.out.println("Please enter last name:");
tag.last = scanMe.next();
System.out.println("Please enter organization or affilation:");
tag.org = scanMe.next();
tag.tagMaker();
}
}
You are only resetting the scanner. Once you do that, add some code that will clear the fields added as well.
Example:
...
scanMe.reset();
first = "";
last = "";
org = "";
System.out.println(s);
}
My program is supposed to print out the initials of the name and print the last name.
Eg. if the name entered is Mohan Das Karamchand Gandhi, the output must be MDK Gandhi. Although I get a "String index out of range" exception.
import java.util.Scanner;
public class name {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("Enter a string");
String w=s.nextLine();
int l=w.length();
char ch=0; int space=0;int spacel = 0;
for(int i=0;i<l;i++){
ch=w.charAt(i);
if(ch==32||ch==' '){
space+=1;
spacel=i+1;
System.out.print(w.charAt(spacel) + " ");
}
}
System.out.println(w.substring(spacel,l+1));
}
This is the culprit:
spacel=i+1;
System.out.print(w.charAt(spacel) + " ");
When i is equal to l - 1, then space1 is going to be equal to l or w.length(), which is beyond the end of the string.
This can be easily achieved using String's split() method or using StringTokenizer.
First split string using space as delimiter. Then according to your format last string would be Last Name and iterate over other string objects to get initial characters.
String name = "Mohan Das Karamchand Gandhi";
String broken[] = name.split(" ");
int len = broken.length;
char initials[] = new char[len-1];
for(int i=0;i<len-1;i++) {
initials[i] = broken[i].charAt(0);
}
String finalAns = new String(initials)+" "+broken[len-1];
import java.util.Scanner;
public class name
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("Enter a string");
String w=s.nextLine();
int l=w.length();
char ch=0; int space=0;int spacel = 0;
System.out.print(w.charAt(0) + " ");
for(int i=0;i<l;i++)
{
ch=w.charAt(i);
if(ch==32||ch==' ')
{
space+=1;
spacel=i+1;
System.out.print(w.charAt(spacel) + " ");
}
}
System.out.println("\b\b"+w.substring(spacel,l));
}
}