need help understanding, converting toCharArray() to a string - java

im fairly sure the mistake I am making within this code is short sighted.
so this program starts by getting the first name and last name of the user and storing them as independent strings. the next part is for the program to manipulate that value into getting the first initial of the first name, which is where im having my problem (I have little experience with the CharArray function and have spent enough independent research time for me to opt to asking here lmao)
import java.util.Scanner; //Needed for the Scanner class
public class NumericTypes {
public static void main (String [] args) {
//TASK #2 Create a Scanner object here
//Reading from system.in
Scanner keyboard = new Scanner(System.in);
//prompt user for first name
System.out.println("Enter your first name: ");
//scans the next input as a double
String firstName = keyboard.nextLine();
//prompt user for last name
System.out.println("Enter your last name: ");
//scans the next input as a double
String lastName = keyboard.nextLine();
//concatenate the user's first and last names
String fullName = (firstName + " " + lastName);
//print out the user's full name
System.out.println(fullName);
//task 3 starts here
//get first initial from variable 'fullName'
String firstinitial = fullName.CharAt(0);
System.out.println("the first initial is: " + firstinitial);
}
}
my desired output is for the last set of lines to display the first initial of the first name (user input). any help would be greatly, greatly appreciated

This can be done in two ways -:
1.) Replace String firstinitial with char firstinitial
2.) Wrap fullName.charAt(0) with String.valueOf like this:
String firstinitial = String.valueOf(fullName.charAt(0));
Both will work just fine.

Related

Replace variable later in code? (this is the kind of topic I dont know how to search for)

First off here is the code with the appropriate descriptions for each command. (Note: the last line is what gives the code error and what I need help fixing).
What is happening on the last line of the code pertains to my question. how is the 'fullName' variable going to be changed to uppercase when it already has an input inside it. how do I go about replacing it later in the code? Thank you
import java.util.Scanner; // Needed for the Scanner class
public class NumericTypes {
public static void main (String [] args) {
//TASK #2 Create a Scanner object here
//Reading from system.in
Scanner keyboard = new Scanner(System.in);
//prompt user for first name
System.out.println("Enter your first name: ");
//scans the next input as a double
String firstName = keyboard.nextLine();
//prompt user for last name
System.out.println("Enter your last name: ");
//scans the next input as a double
String lastName = keyboard.nextLine();
//concatenate the user's first and last names
String fullName = (firstName + " " + lastName);
//print out the user's full name
System.out.println(fullName);
//task 3 starts here
//get first initial from variable 'fullName'
char firstinitial = fullName.charAt(0);
System.out.println("the first initial is: " + firstinitial);
//use the 'toUpperCase' method to change fullName variable to caps
// and store into the fullName variable
String fullName = fullName.toUpperCase()
}
}
You are trying to create the variable fullName which already exists. Change the variable name to something else.
String upperFullName = fullName.toUpperCase();
or omit the declaration
fullName = fullName.toUpperCase();
If you are getting an error, change
String fullName = fullName.toUpperCase()
to
fullName = fullName.toUpperCase();
First off, you didn't write a semicolon ; at the end of the statement.
Second, you can't declare two variables with the same name, which you were doing here. Removing String from this sentence changes the value of the variable fullName.

I want the use to be able to input their first and last name. Then I want to change their input so that it will come out as last, first [duplicate]

This question already has answers here:
Prompt user to enter name on one line and print it out as "Last, First"
(4 answers)
Closed 6 years ago.
So far I have the following code:
import java.util.*;
public class Names {
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = input.next();
changeNameFormat(name);
}
public static void changeNameFormat(String name) {
System.out.println(name.substring(0,20));
}
}
I am not sure, but I think I need to use an array, however I am unsure of how to go about this seeing as I will not know what the user input will be every time.
Example of what I want to happen:
User inputs:
John Smith
I want the program to output it as this:
Smith, John
Lets suppose you ask the user to enter the first name and last name with a comma separation.
For example: FirstName,LastName
In this case you can use comma as the delimiter for identifying first name and last name.
public static void changeNameFormat(String name) {
String [] splitName = name.split(",");
//splitName[0] holds first name and splitName[1] holds last name
System.out.println(splitName[1] + ", " + splitName[2]);
}
An easier way without manipulating / splitting one String is to use the Scanner's default delimiter (whitespace):
Scanner input = new Scanner(System.in);
System.out.println("Enter your name: ");
// assuming the input consists in name surname[return]
String name = input.next();
String surname = input.nextLine();
System.out.printf("%s, %s%n", surname.trim(), name.trim());
input.close();
You can do the following in the changeNameFormat
System.out.println(name.replaceAll("^(\\w+)\\s+(\\w+)$", "$2, $1"));
Also, remember to change the input.next() to input.nextLine() to be able to read multiple words in one line. For more detail on the regex, please refer to the following link:
https://regex101.com/r/sA4xJ5/2

How to use the Scanner class properly?

I'm doing an assignment for class. For some reason the program completely skips the part where the variable name is supposed to be typed in by the user. I can't think of any reason why it's behaving this way, since the rest of my code that is after the cardType part (which asks for things such as String and int types work fine and in order.
System.out.println("Enter the card information for wallet #" +
(n+1) + ":\n---\n");
System.out.println("Enter your name:");
String name = scan.nextLine();
name = capitalOf(name);
System.out.println("Enter card type");
String cardType = scan.nextLine();
cardType = capitalOf(cardType);
You probably need to consume the end of the last line you read prior to trying to get the user name :
scan.nextLine(); // add this
System.out.println("Enter the card information for wallet #" +
(n+1) + ":\n---\n");
System.out.println("Enter your name:");
String name = scan.nextLine();
name = capitalOf(name);
System.out.println("Enter card type");
String cardType = scan.nextLine();
cardType = capitalOf(cardType);
It is behaving this way because I am quite sure you used the same scanner object to scan for integers/double values before you used it to scan for name.
Having said that does not mean you have to create multiple scanner objects. (You should never do that).
One simple way to over come this problem is by scanning for strings even if you are expecting integers/doubles and cast it back.
Scanner scn = new Scanner(System.in);
int numbers = scn.nextInt(); //If you do this, and it skips the next input
scn.nextLine(); //do this to prevent skipping
//I prefer this way
int numbers = Integer.toString(scn.nextLine());
String str = scn.nextLine(); //No more problems

How do I call from a list of names?

I've only been learning java for a few weeks so I'm still a noob. I want the next line to print "mr/miss." + firstname + lastname;
however, i don't want to type the gender of the person in. I want there to be a list of male names (long list over 1000 names) and the program to detect if the firstname input is one of those male names. The program can then assign the correct title (mr/ms.)
How do I do this without making a normal arraylist and typing out each name individually (which'll take agessss).
Thanks in advance!
public static void main (String [] args){
Scanner scanner = new Scanner(System.in);
System.out.println("Hello, will you be checking out today? (Y/N)");
String CheckOutYesOrNo = scanner.nextLine();
if (CheckOutYesOrNo.equalsIgnoreCase("y")) { x();}
else if (CheckOutYesOrNo.equalsIgnoreCase("n")) {System.out.println("Okay then. Enjoy the rest of your stay at the Rizty Hotel!");}
}
public static void x(){
System.out.println("Sure, would you mind telling me your last name?");
Scanner scanner = new Scanner(System.in); //how can I avoid making a new scanner?
String lastname = scanner.nextLine();
System.out.println("And your first name?");
String firstname= scanner.nextLine();
}
}
Sounds like a typical mapping. You could read all your names into a Map where the key is the name and the gender is the value. To resolve the gender just do something like genderMap.get(name).

Java - Skipping a line when reading user input into an array (for loop)

Here's my code - The objective is to enter some basic info (age, name, gender) for x number of patients.
public static void main(String[] args) {
int numPatients = 2;
int[] age = new int[numPatients];
String[] gender = new String[numPatients];
String[] name = new String[numPatients];
Scanner in = new Scanner(System.in);
/*
* Obtaining patients details: name, gender, age
* First create a Scanner input variable to read the data
*/
for (int i = 0; i < numPatients; i++)
{
System.out.println("Enter name of patient " + (i+1));
name[i] = in.nextLine();
System.out.println("Enter gender (male/female) of patient " + (i+1));
gender[i] = in.nextLine();
System.out.println("Enter age of patient " + (i+1));
age[i] = in.nextInt();
}
The issue I'm having is when the loop goes to the 2nd variable, i.e. I'm not able to enter a value for the name of the patient. It seems to skip taking the input there and goes directly to the next input, which is gender.
Enter name of patient 1
Mark
Enter gender (male/female) of patient 1
Male
Enter age of patient 1
34
Enter name of patient 2 //Skipped. Could not enter input here
Enter gender (male/female) of patient 2
Jenna
Any idea why that happens? Is it better to use BufferedReader instead?
If you must use Scanner, then always use nextLine(). The problem is that nextInt() reads only the integer part of the input and stops before it reads the Enter keypress. Then the next call to nextLine() sees the Enter keypress in the buffer and things you entered an empty name.
So you can do something like:
age[i] = Integer.parseInt(in.nextLine());
and be prepared to handle the exception that will happen if the user types something other than a number.
If you are assured that name will be a single word (not an issue for male or female)then you can modify the scanner input to just get the string;
in.next();
this works fine (only if name's a single word ).

Categories

Resources