I'm prompting the user to enter their first and last name but I can't figure out how to show just their first and last initials
import javax.swing.*;
//import java.awt.*;
public class Lab2Program2 {
public static void main (String [] args) {
String firstName;
String lastName;
firstName = JOptionPane.showInputDialog(null, "What is your first name?");
lastName = JOptionPane.showInputDialog(null, "What is your last name?");
JOptionPane.showMessageDialog(null, " Your initials are " +
firstName + " " + lastName);
}
}
If you want to show a message box like you were doing before, this should work:
JOptionPane.showMessageDialog(null,
"Your initials are " + firstName.substring(0, 1) + " " + lastName.substring(0, 1));
You can use chatAt() method.
JOptionPane.showMessageDialog(null,
"Your initials are " + firstName.charAt(0) + " " + lastName.charAt(0));
firstName.charAt(0) returns the char value at the 0 index. That is the first letter of your firstName String.
Related
I have tried many methods but still did not works. I tried to catch if there is a number in JTextfield it will make the string text turn to red and pop up the JOption. But my code only catches if there are numbers in both of my JTextfield. I want to my JTextField have only characters and space.
(jtf2 and jtf3 are JTextField)
if(ae.getSource() == bcreate) // create
{
String firstname;
String lastname;
String id;
firstname = jtf2.getText();
lastname = jtf3.getText();
try
{
Integer.parseInt(jtf2.getText());
jtf2.setForeground(Color.RED);
Integer.parseInt(jtf3.getText());
jtf3.setForeground(Color.RED);
JOptionPane.showMessageDialog(null, "Please enter valid character","ERROR",JOptionPane.ERROR_MESSAGE);
}
catch(NumberFormatException w)
{
create(firstname, lastname);
jtf3.setForeground(Color.black);
jtf2.setForeground(Color.black);
id = Integer.toString(e.length);
current = Integer.parseInt(id);
jta.setText("Employee #" + id + " " + firstname + " " + lastname + " was created.");
}
}
This not the correct way to check for numbers in code. Exception is for exception condition. And here we are exploiting it and running main code in exception. Rather you should use regex to check if, text contains any number or not. As below :
String firstname = jtf2.getText();
String lastname = jtf3.getText();
String id;
boolean isInvalidText = false;
if(firstname.matches(".*\\d.*")) {
jtf2.setForeground(Color.RED);
isInvalidText = true;
}
if(lastname.matches(".*\\d.*")) {
jtf3.setForeground(Color.RED);
isInvalidText = true;
}
if(isInvalidText) {
JOptionPane.showMessageDialog(null, "Please enter valid character","ERROR",JOptionPane.ERROR_MESSAGE);
} else {
create(firstname, lastname);
jtf3.setForeground(Color.black);
jtf2.setForeground(Color.black);
id = Integer.toString(e.length);
current = Integer.parseInt(id);
jta.setText("Employee #" + id + " " + firstname + " " + lastname + " was created.");
}
int lastSpace = fullName.lastIndexOf(" ");
here all the code
import java.util.Scanner;
public class java_13 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your full name");
String fullName = input.nextLine();
int firstSpace = fullName.indexOf(" ");
String firstName = fullName.substring(0, firstSpace);
int lastSpace = fullName.lastIndexOf(" ");
String lastName = fullName.substring(lastSpace + 1);
System.out.println("\n" + lastName + ", " + firstName);
also why we use ( +1 )
here
String lastName = fullName.substring(lastSpace + 1);
Because the space divides firstName and lastName.
The input is supposed to look like "firstName lastName". If you take the position of the " " space from it, then the "lastName" part begins on the next character, hence the +1 to the position for getting the substring.
In Java, the index starts with 0.
For example :
String name = "Moataz Mohamed";
name[0]='M';
name[1]='o';
...
name[6]=' '; //Space
Space separates First name and Last name.
Hence,
0 to index[" "]-1 is First name
index[" "]+1 to length() is Second name
Hope its clear now.
Here the full name is composed of a first name and the last name, this code search the first blank space in order to separate the first name from the last name
But I recommend allowing the user to enter both of the last and the first name instead of the full name because it is impossible to know how much words compose the first name and the same thing for the last name.
As #0x01 mentioned, you get the index of the space, but in last name is beginning at position with index +1, that is the reason, just check this outputs
{...}
public static final String NAME1 = "Julian Papadopulos";
public static final String NAME2 = "John von Bahnhof";
public static final char SPLITCHAR = ' ';
{...}
public static void splitNamesBySpaceIndex() {
// name1
int firstSpace = NAME1.indexOf(" ");
int lastSpace = NAME1.lastIndexOf(" ");
String firstName = NAME1.substring(0, firstSpace);
String lastName = NAME1.substring(lastSpace + 1);
System.out.println("lastname: \'" + lastName + "\', firstname: \'" + firstName + "\'");
lastName = NAME1.substring(lastSpace);
System.out.println("lastname: \'" + lastName + "\', firstname: \'" + firstName + "\'");
}
Output looks like:
lastname: 'Papadopulos', firstname: 'Julian'
lastname: ' Papadopulos', firstname: 'Julian'
As you can see, in the second case you will parse last name like ' Papadopulos', which is not correct, its caused by taking start index the index of the space- this is the reason, why you need position with index +1.
This is like this...
FIRSTNAME LASTNAME
012345678901234567
FIRSTNAME Starts from 0
Index of " " is 9
LASTNAME Starts from 10
That is why you need to add (+1) here
indexOf(" ") {9} but you have to start with LASTNAME which is at 10
If you do not add (+1) then Output will be " LASTNAME"
I'm new to programming and logical errors; I've looked for a similar problem but nothing quite matches mine. We have an assignment to make a program where the user enters their first and last name--if the names are the same, it returns "your first and last name are the same" and if the names are different, it returns "your first and last name are different".
My problem is that it keeps returning BOTH answers no matter what names are typed in. If you run it and try your own name in it, you'll see what I mean.
Here's my code (we have to use scanner):
import java.util.Scanner;
public class NameAssignment
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
String firstName;
System.out.print("Enter your first name: ");
firstName = stdIn.nextLine();
String lastName;
System.out.print("Enter your last name: ");
lastName = stdIn.nextLine();
if (firstName == lastName);
System.out.println("Hello " + firstName + " " + lastName + "," + " " + "your first name and last name are the same.");
if (firstName != lastName);
System.out.println("Hello " + firstName + " " + lastName + "," + " " + "your first name and last name are different.");
} // end main
} // end class NameAssignment
UPDATE
I tried correcting it with the suggestions below, and here's what it looks like now:
import java.util.Scanner;
public class NameAssignment
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
String firstName;
System.out.print("Enter your first name: ");
firstName = stdIn.nextLine();
String lastName;
System.out.print("Enter your last name: ");
lastName = stdIn.nextLine();
if (firstName.equals(lastName))
System.out.println("Hello " + firstName + " " + lastName + "," + " " + "your first name and last name are the same.");
else (!firstName.equals(lastName)
System.out.println("Hello " + firstName + " " + lastName + "," + " " + "your first name and last name are different.");
} // end main
} // end class NameAssignment
I ran it in terminal, and it gave me this:
NameAssignment.java:16: error: ')' expected
else (!firstName.equals(lastName)
^
NameAssignment.java:16: error: not a statement
else (!firstName.equals(lastName)
^
NameAssignment.java:17: error: illegal start of expression
System.out.println("Hello " + firstName + " " + lastName + "," + " " + "your first name and last name are different.");
^
NameAssignment.java:17: error: ';' expected
System.out.println("Hello " + firstName + " " + lastName + "," + " " + "your first name and last name are different.");
^
4 errors
To compare 2 Strings in java, you must use if (firstName.equals(lastName)) because in Java == operator checks 2 String objects and .equals() checks String values.
Also, you must remove the semicolon ; after the if statement or else that wont execute your if condition.
Your else clause is wrong. Just replace your else clause with the following else clause:
else
System.out.println("Hello " + firstName + " " + lastName + "," + " " + "your first name and last name are different.");
That's it. else doesn't need a condition. That's why else (!firstName.equals(lastName)) is wrong.
you were missing the ) which i added and removed the "," + " " because it was un-efficient and it should just be included in the same string which i fixed. Just replace your code with that and it should work
if (firstName.equals(lastName)){
System.out.println("Hello " + firstName + " " + lastName + ", your first name and last name are the same.");
}
else (!firstName.equals(lastName)){
System.out.println("Hello " + firstName + " " + lastName + ", your first name and last name are different.");
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I have tried so many variations of this code and I can't seem to get it correct.
I get an array out of bounds issue for the second if statement if I try something only with two parts. However, it works fine if there are 3 parts in the name.
import java.util.Scanner;
public class testArray
{
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);
String fullName = input.nextLine();
fullName = fullName + " " + " ";
System.out.println(fullName);
String [] parts = fullName.split(" ");
String firstName = parts[0];
String middleName = parts[1];
String lastName = parts[2];
String firstNameInitial = firstName.substring(0,1).toUpperCase(); //capitalizes first initial
String middleNameInitial = middleName.substring(0,1).toUpperCase(); //capitalizes second initial
String lastNameInitial = lastName.substring(0,1).toUpperCase(); //capitalizes third initial
String initials = firstNameInitial + middleNameInitial + lastNameInitial; //Combines initials of name in capital form
if (parts.length == 3)
{
System.out.println(initials);
System.out.println(lastName.toUpperCase() + ", " + firstNameInitial+firstName.substring(1,parts[0].length()) + " " + lastNameInitial + ".");
System.out.println(lastNameInitial + lastName.substring(1,parts[2].length()) + ", " + firstNameInitial+firstName.substring(1,parts[0].length()) + " " + middleNameInitial + middleName.substring(1,parts[1].length()));
}
if (parts.length == 2)
{
System.out.println("error");
}
}
}
That's because the way you initialize your variables:
String firstName = parts[0];
String middleName = parts[1];
String lastName = parts[2];
Here, if parts only has index 0 and 1 (a length of 2) you will get an exception because there is no parts[2] (it's index is out of bounds).
Modify that to something like this:
String firstName = parts[0];
String middleName = null;
String lastName = parts[1];
if (parts.length > 2) {
middleName = parts[1];
lastName = parts[2];
}
With this code, middleName will only be set if parts has a length greater than 2, which means that the index 2 will exist. Otherwise, middleName will be null (or you could change this to be an empty string or whatever you would like)
You are trying to access the 3rd object in the array before you check how long the array is.
try this instead:
import java.util.Scanner;
public class testArray
{
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);
String fullName = input.nextLine();
fullName = fullName + " " + " ";
System.out.println(fullName);
String [] parts = fullName.split(" ");
if(parts.length == 3)
{
String firstName = parts[0];
String middleName = parts[1];
String lastName = parts[2];
String firstNameInitial = firstName.substring(0,1).toUpperCase(); //capitalizes first initial
String middleNameInitial = middleName.substring(0,1).toUpperCase(); //capitalizes second initial
String lastNameInitial = lastName.substring(0,1).toUpperCase(); //capitalizes third initial
String initials = firstNameInitial + middleNameInitial + lastNameInitial; //Combines initials of name in capital form
System.out.println(initials);
System.out.println(lastName.toUpperCase() + ", " + firstNameInitial+firstName.substring(1,parts[0].length()) + " " + lastNameInitial + ".");
System.out.println(lastNameInitial + lastName.substring(1,parts[2].length()) + ", " + firstNameInitial+firstName.substring(1,parts[0].length()) + " " + middleNameInitial + middleName.substring(1,parts[1].length()));
}else{
System.out.println("error");
}
}
}
i think these line you want to put just after calling split:
String [] parts = fullName.split(" ");
if (parts.length == 2)
{
System.out.println("error");
return;
}
so the code would look like:
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
String fullName = input.nextLine();
fullName = fullName + " " + " ";
System.out.println(fullName);
String [] parts = fullName.split(" ");
if (parts.length == 2)
{
System.out.println("error");
} else if(parts.length == 3) {
String firstName = parts[0];
String middleName = parts[1];
String lastName = parts[2];
String firstNameInitial = firstName.substring(0,1).toUpperCase(); //capitalizes first initial
String middleNameInitial = middleName.substring(0,1).toUpperCase(); //capitalizes second initial
String lastNameInitial = lastName.substring(0,1).toUpperCase(); //capitalizes third initial
String initials = firstNameInitial + middleNameInitial + lastNameInitial; //Combines initials of name in capital form
System.out.println(initials);
System.out.println(lastName.toUpperCase() + ", " + firstNameInitial+firstName.substring(1,parts[0].length()) + " " + lastNameInitial + ".");
System.out.println(lastNameInitial + lastName.substring(1,parts[2].length()) + ", " + firstNameInitial+firstName.substring(1,parts[0].length()) + " " + middleNameInitial + middleName.substring(1,parts[1].length()));
}
}
i might suggest splitting on white space rather that " "
so for example
String [] parts = fullName.split("\\s+");
also why are you adding spaces (fullName = fullName + " " + " ";)
also you might not get to your parts comparison because you will hit the String extraction from the array first, put your if check (if(parts.length == 3)) straight after the splitting (String [] parts = fullName.split("\\s+");)
The error comes from here:
Scanner input = new Scanner(System.in);
String fullName = input.nextLine();
fullName = fullName + " " + " ";
System.out.println(fullName);
String [] parts = fullName.split(" ");
String firstName = parts[0];
String middleName = parts[1];
String lastName = parts[2];
If someone enters text that is less than 3 words long, you get an ArrayIndexOutOfBoundsException. You have to add something like:
Scanner input = new Scanner(System.in);
String [] parts = null;
while (input.hasNext()) {
System.out.println("Please enter first middle and last name");
String fullName = input.nextLine();
fullName = fullName + " " + " ";
System.out.println(fullName);
parts = fullName.split(" ");
if (parts.length == 3)
break;
}
String firstName = parts[0];
String middleName = parts[1];
String lastName = parts[2];
Which will prompt the user for three words until you get the right amount.
Issue is here
String middleName = parts[1];
String lastName = parts[2];
You are appending two white spaces for fullName fullName = fullName + " " + " "; but actually these spaces won't append as there is no text after fullName, hence parts consists only one element at 0 position. and you are calling 1st position of parts array which is not available String middleName = parts[1]; So you are seeing ArrayIndexOutOfBoundsException
0,1,2,3,4 >> these are indexed till 4 but the total components or length is 5 .
So In
firstName.substring(1,parts[0].length())
Here, "parts[0].length()" should be replaced by "parts[0].length()-1" because the previous is increasing the size by 1 and hence array is out of bound..
The same error u will get in next line.
So replace every .length with .length-1 ..
And remove this line
fullName = fullName + " " + " "; because it increases the length of variable path to 5 and hence it dosent goes in the if statements
I am writing a program for a class that is very simple. All it requires of me is to print a grade sheet, and be able to input 3 pieces of information (here represented by Strings studentName, idNumber, and assignmentTitle). The grade sheet has to be stored in a single string. Ok so this to me appears as though it should work but for whatever reason it outputs null values where the inputted studentName, idNumber, and assignmentTitle should appear. Very simple problem I'm sure, any ideas? Here is my code.
import java.util.Scanner;
class GradingForm
{
static String studentName;
static String idNumber;
static String assignmentTitle;
static String gradeSheet = "********************************* \n\n" +
assignmentTitle + "\n\n" +
studentName + " " + idNumber + "\n\n" +
"Grade Summary:\n\n" +
"Program Correctness: Quality of Style:\n" +
"Late Deduction: Overall Score:\n" +
"Comments:";
public static void gradeFormValues()
{
Scanner inData;
inData = new Scanner(System.in);
System.out.println("Enter student's name: ");
studentName = inData.nextLine();
System.out.println("Enter student ID number: ");
idNumber = inData.nextLine();
System.out.println("Enter Assignment title: ");
assignmentTitle = inData.nextLine();
}
public static void printGradeSheet()
{
System.out.println(gradeSheet);
}
public static void main(String[] args)
{
gradeFormValues();
printGradeSheet();
}
}
Your problem is that you use those variables before assigning values to them:
static String gradeSheet = "********************************* \n\n" +
assignmentTitle + "\n\n" +
studentName + " " + idNumber + "\n\n" +
"Grade Summary:\n\n" +
"Program Correctness: Quality of Style:\n" +
"Late Deduction: Overall Score:\n" +
"Comments:";
You need to build the string only after you assign values to them for example:
public static void printGradeSheet()
{
gradeSheet = "********************************* \n\n" +
assignmentTitle + "\n\n" +
studentName + " " + idNumber + "\n\n" +
"Grade Summary:\n\n" +
"Program Correctness: Quality of Style:\n" +
"Late Deduction: Overall Score:\n" +
"Comments:";
System.out.println(gradeSheet);
}
Your problem is how your class is instantiated. This is what happens:
studentName is set to null
idNumber is set to null
assignmentTitle is set to null
gradeSheet is set using the current values of studentName etc (null).
After that you read your data and set the variables, but this does not change the value of gradeSheet already set.
You're problem is the order in which you initialize your variables.
When you initialize gradeSheet (the line with static String gradeSheet =...), assignmentTitle, studentName, and idNumber are null.
You should instead initialize gradeSheet after you have finished accepting input from the user.