why we use here (int) with (space)? - java

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"

Related

How to format an output?

(In Java) Write a program that accepts names and formats them as follows: If the input is:
John Anthony Brown
Then the output must be:
Brown, John A.
Here is what I have
int mn;
String input3;
int fn;
int ln;
String firstName;
String lastName;
String middleName;
Scanner scnr = new Scanner(System.in);
String input = scnr.nextLine();
fn = input.indexOf(" ");
firstName = input.substring(0, fn);
middleName = input.substring(fn+1, input.length());
mn = middleName.indexOf(" ");
lastName = input.substring(mn+1, input.length());
System.out.println(lastName + ", " + mn + " " + firstName + ".");
}
I keep trying different things and get weird outputs such as "ry A Lee, 1 Mary." for the input "Marry A Lee"
This topic was never covered in my class and I am very confused.
Because this is homework, I’ll give code fragments:
Firstly, use split() to break up the text into words:
String[] names = input.split(" ");
Then build up your result:
String result = names[2] + ", " + names[0] + ", " + names[1].charAt(0) + ".";
There are more elegant ways of doing it, but this way is arguably the easiest to understand.
You could get fancier by catering for varying numbers of names.
Try something like this:
String[] items = input.split(" ");
//if there are three item in items, then it is the pattern you mentioned
if (items.length == 3) {
System.out.println(items[2] + "," + items[0] + items[1].charAt(0) + ".");
}

Why my indexOf value is not returning the right result?

I am writing this little section for a program I'm gonna write for initials of a name in java, and I need to determine the position of each space in it to be able to choose the initials. I'm testing it to make sure the spaces are been seen in the right position in the line, but for some reason, the position always comes wrong! Please help me.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("please enter full name:");
String name = in.nextLine();
int space = name.indexOf(" ");
int space1 = name.indexOf(" ", space) + space+1;
int space2 = name.indexOf(" ", space1) + space1+1;
int space3 = name.indexOf(" ", space2) + space2+1;
int space4 = name.indexOf(" ", space3) + space3+1;
int space5 = name.indexOf(" ", space4) + space4+1;
System.out.println(space + " " + space1 + " " + space2 + " " + space3 + " " + space4);
}
}
My idea using this line was to count up to each part of the line space that shows up after the last one and add 1 because java starts counting at 0.
(" ", space1) + space1+1;
Basically, if the name is "Jeff Luiz Jeff Luiz" the first space is at 4 and the next one is at 9, so it would the 4, then proceed to count after this space, starting at 0, which would find 4 again(because Luiz has the same amount of letters), sum up with the last space number to keep track of the real position(then it would be 8), and finally sum up with 1 because of how java works, and so on. When I ran these 4 words I found the result 4 9 19 19 19. Does anyone know what is the problem with my code?
Replace
int space1 = name.indexOf(" ", space) + space+1;
with
int space1 = name.indexOf(" ", space + 1);
because String#indexOf(String str, int fromIndex) returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
Demo:
public class Main {
public static void main(String[] args) {
String name = "Arvind Kumar Avinash";
int space = name.indexOf(" ");
int space1 = name.indexOf(" ", space + 1);
System.out.println(space + ", " + space1);
}
}
Output:
6, 12

Name Reversing in strings

Write a method lastNameFirst that takes a string containing a name such as "Harry Smith" or "Mary Jane Lee", and that returns the string with the last name first, such as "Smith, Harry" or "Lee, Mary Jane".
im supposed to check it against
http://wiley.code-check.org/codecheck/files?repo=bjlo2&problem=05_02
i post this
String firstName = name.substring(0, name.indexOf(" "));
String lastName = name.substring(name.indexOf(" "));
String cName = lastName + ", " + firstName;
if ( lastName == " " )
{
cName = firstName;
}
return cName;
I get 0/4 everytime please help im completely lost.
It might be simpler to create an array using the split function of the String class, then join them:
String cName = String.join(", ", Collections.reverse(Arrays.asList(name.split(" "))));
String.join is only in Java 8 I believe, if you're not using 8 you can use something like the following:
String[] names = name.split(" ");
String cName = names[1] + ", " + names[0];
You should also be using the equals method for comparing String and other objects:
String[] names = name.split(" ");
String cName = names[1].equals(" ") ? names[0] : names[1] + ", " + names[0];
Please try this code
String first = name.substring(name.lastIndexOf(" "));
String last = name.substring(0, name.lastIndexOf(" "));
String result = first + "," + last;
Your solution is very close. Here's 2 hints to get to the right solution:
What separates the first and last name is the last, not the first space (consider using str.lastIndexOf(" ")).
As mentioned in the comments, when comparing strings, you can't use str1 == str2, you have to use str1.equals(str2)
You only need the last space in your name, which you can get with String.lastIndexOf(int). Then you test if that is less then 0, if so return the input name. Otherwise, concatenate and return your name in the desired format. Using a ternary (or conditional operator ? :) that might look something like,
int p = name.lastIndexOf(' ');
return (p < 0) ? name : name.substring(p + 1) + ", " + name.substring(0, p);
I put this for that Question and it passed all 4 tests they had.
public static String lastNameFirst(String name)
{
String LastToFirst = "";
if(!name.contains(" ")){
return name;
}
int index = name.indexOf(" ");
int secondIndex = name.indexOf(" ", index + 1);
// exclusive of last index
if(secondIndex != -1) {
LastToFirst += name.substring(secondIndex+1,name.length())+", ";
LastToFirst += name.substring(0,secondIndex);
}
else {
LastToFirst += name.substring(index +1,name.length()) + ", ";
LastToFirst += name.substring(0, index);
return LastToFirst;
}
A better solution for this would be to use an array, and store the characters in there and for the spacing one should add an index variable for where you want the splitting to happen- the string of interest. The solutions above do a good example of expalining this better, they consider cases where it is not a white space, but other symbols making the method more robust. Hope this helps.
I tried this code and all the four arguement works. Hope this helps!!
{
String[] names = name.split(" ");
String cName = "";
if(names.length > 2){
cName = names[2].equals(" ") ? names[0] : names[2] + ", " + names[0] + " " + names[1];
}
else if(names.length == 1){
cName = names[0]
}
else{
cName = names[1].equals(" ") ? names[0] : names[1] + ", " + names[0];
}
return cName;
}
}
public class Names
{
/**
Changes a name so that the last name comes first.
#param name a name such as "Mary Jane Lee"
#return the reversed name, such as "Lee, Mary Jane".
If name has no spaces, it is returned without change.
*/
public static String lastNameFirst(String name)
{
String result = "";
if(!name.contains(" "))
{
String firstOnly = name.substring(0);
return firstOnly;
}
else
{
String first = name.substring(name.lastIndexOf(" ")+1);
String last = name.substring(0, name.lastIndexOf(" "));
result = first + ", " + last;
return result;
}
}
}
This is the correct answer that will get you 4/4.

Beginner Programmer: Java String Manipulation

Can someone tell me what I am doing wrong here? I'm trying to display the position of asterisks but i keep getting 1 in return.
package proj2;
import java.util.Scanner;
/**
* <p> Title: Project 2: String Manipulation </p>
* <p> Description: Ask the user to enter a URL and it will display
* the protocol, domain name and file name specified. </p>
* #author Mario Mendoza
*
*/
public class Project2 {
/**
*
* #param args arguments
*/
public static void main(String[] args ) {
Scanner s = new Scanner(System.in );
String sentence;
String word1;
String word2;
String word3;
String word4;
String asterisks1 = "*";
String asterisks2 = "*";
String asterisks3 = "*";
int firstWord;
int secondWord;
int thirdWord;
int fouthWord;
int wordLength1;
int wordLength2;
int wordLength3;
int wordLength4;
int positionOfAsterisks1;
int positionOfAsterisks2;
int positionOfAsterisks3;
char firstLetter;
int total;
word1 = s.next();
word2 = s.next();
word3 = s.next();
word4 = s.next();
System.out.println("You typed " + word1 + asterisks1 + word2 + asterisks2 + word3 + asterisks3 + word4);
sentence = new String(word1 + asterisks1 + word2 + asterisks2 + word3 + asterisks3 + word4);
wordLength1 = word1.length();
System.out.println(word1 + " has length " + wordLength1);
wordLength2 = word2.length();
System.out.println(word2 + " has length " + wordLength2);
wordLength3 = word3.length();
System.out.println(word3 + " has length " + wordLength3);
wordLength4 = word4.length();
System.out.println(word4 + " has length " + wordLength4);
positionOfAsterisks1 = sentence.indexOf(asterisks1);
positionOfAsterisks2 = sentence.indexOf(asterisks2);
positionOfAsterisks3 = sentence.indexOf(asterisks3);
System.out.println("The asterisks were found at position " + positionOfAsterisks1 + ", " + positionOfAsterisks2 + ", and " + positionOfAsterisks3);
}
}
Have your program perform the following tasks:
Prompt the user to enter a String containing exactly four words, separated only
by asterisks. The input string should not have any spaces. An example of the kind
of input this program will receive is I*love*computer*science. Display the
user’s input (as a confirmation to the user that the program understood the input).
Store each of the four words separately.
Display each word with its length. For example:
I has length 1.
love has length 4.
computer has length 8.
science has length 7.
Display the position of the asterisks in the original string. For example:
The asterisks were found at positions 1, 6, and 15.
Display the last letter of the first word.
Display the total aggregate length of the four words.
In addition, be sure to include a JavaDoc comment at the top of the file, that include’s the
program’s title, description, and author’s name.
4 Sample Run
You typed I*love*computer*science.
I has length 1.
love has length 4.
computer has length 8.
science has length 7.
The asterisks were found at positions 1, 6, and 15.
The last letter of the first word is I.
The total aggregate length of the four words is 20 letters.
public static void main(String[] args ) {
Scanner s = new Scanner(System.in );
String sentence;
String word1;
String word2;
String word3;
String word4;
word1 = s.next();
word2 = s.next();
word3 = s.next();
word4 = s.next();
System.out.println("You typed " + word1 + "*" + word2 + "*" + word3 + "*" + word4);
sentence = new String(word1 + "*" + word2 + "*" + word3 + "*" + word4);
System.out.println(word1 + " has length " + word1.length());
System.out.println(word2 + " has length " + word2.length());
System.out.println(word3 + " has length " + word3.length());
System.out.println(word4 + " has length " + word4.length());
System.out.print("The asterisks were found at position ");
// get the position of * and store the position index
int i = 0;
String positionOfAsterisks = "";
while (i < sentence.length()){
if (sentence.charAt(i) == '*')
positionOfAsterisks += i + ", ";
i++;
}
// remove the last comma and empty space then add in full stop
positionOfAsterisks = positionOfAsterisks.substring(0, positionOfAsterisks.length()-2);
positionOfAsterisks += "." ;
System.out.print(positionOfAsterisks);
}
Instead of using indexOf, I use a loop to iterate through your 'sentence'. Also, I removed the declaration of useless variables.
IndexOf will return just the index it found from the first index (if it's not stated in the 2nd arg of the method). And IndexOf method return the first position as 1 instead of 0.
The problem is that you are always searching in the given string for the same value, which is *. It doesn't matter what you name the variable, you are essentially running this line 3 times:
positionOfAsterisks1 = sentence.indexOf('*'); using 3 different variables, but each time it will always return 1. This is because each time it starts over, hits the first asterisk, and returns true.
What you need to do is make use of the second argument, which is the position to start from.
positionOfAsterisks1 = sentence.indexOf(asterisks1);
int temp = positionOfAsterisks1 + 1;
positionOfAsterisks2 = sentence.indexOf(asterisks1,temp);
temp = positionOfAsterisks2 + 1;
positionOfAsterisks3 = sentence.indexOf(asterisks1,temp);
What this does
The first line returns a value of 1. The next line sets temp to 2. Now the search starts from the third position (since array indices start at 0), and will thus not include the first asterisk. It will then hit the 7th character which is * and return 6. Again temp is set to 7, and again the search starts from the 8th character, and goes on till it hits the asterisk again at 15.
Note
You do not need to use 3 separate variables to hold the same *, it is only a waste of space. I would recommend using the same variable and eliminating the other two!

Array issue out of bounds [closed]

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

Categories