Issue with output of java program involving string - java

class Blue_ManTest{
public static void main(String[] args){
String name = "I LOVE JAVAWORLD";
int index1 = name.indexOf(" ");
int index2 = name.lastIndexOf(" ");
String str1 = name.substring(0, index1);
String str2 = name.substring(index1 + 1, index1+ 5);
String str3 = name.substring(index2 + 5);
System.out.println(str3 + ", " + str1 + " " + str2 + ".");
}
}
I am having trouble figuring out what would be the output of this program I think I know it but I am not sure.
I did this I Love JavaWorld with 0 corresponding to j and 15 to D with 1 being the space between.
for str1 I get I
for str2 I get Love
but for str3 I get avaWorld
But str3 seems wrong to me as it would print out.
avaWorld, I Love.

Your str3 variable is taking a substring that starts at index2 + 5 where index2 is the index of the last space in your input string:
int index2 = name.lastIndexOf(" ");
That is, index2 is 6. And of course 6 + 5 is 11.

Related

how to get index by keyword in a string?

if I have a String:
String str = "Hello, World!";
how can I get index of a key word:
int begin_index = str.GetKeywordIndex("World").GetBeginIndex();
int end_index = str.GetkeyWordIndex("World").GetEndIndex();
System.out.println("keyword World begin at:" + begin_index + "end: " + end_index);
// keyword World begin at: 7, end: 11
ps: I don't want to use for loop iterate String, because it's too slow
int begin_index = str.undexOf("World");
int end_index = begin_index+"World".length();
System.out.println("keyword World begin at:" + begin_index + "end: " + end_index);

Beginner Java - Changing String from First Middle Last to Last, First Middle

Trying to work out a homework problem that demands:
Changes a name so that the last name comes first.
Example: "Mary Jane Lee" will return "Lee, Mary Jane".
If name has no spaces, it is returned without change.
After doing some research it seems I can do this with the Split method, but we've not learned that yet.
The thing is I've worked out the code and it seems to work when spaces
and a full name is entered, but when there's no middle name or no spaces to separate the character, I get the error:
when the name entered is simply: Harry Smith
java.lang.StringIndexOutOfBoundsException: String index out of range: -7
and
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
when the name is Sarah
This is my code, but I'm not sure how to fix it:
public class Names {
public static String lastNameFirst(String name) {
int firstIndex = name.indexOf(" ");
int secondIndex = name.indexOf(" ", firstIndex + 1);
String firstName = name.substring(0, name.indexOf(" "));
String middleName = name.substring(firstIndex + 1, secondIndex);
String lastName = name.substring(secondIndex + 1);
String result = "";
result = lastName + ", " + firstName + " " + middleName;
return result;
}
}
Thanks in advance!!
using split and a switch would be a lot easier
String name = "Mary Jane Lee";
String arr[] = name.split (" ");
switch (arr.length) {
case 1:
System.out.println(name);
break;
case 2:
System.out.println(arr[1] + ", " + arr[0]);
break;
default:
System.out.println(arr[2] + ", " + arr[0] + " " + arr[1]);
}
A more robust way is to use lastIndexOf to find the last space:
int lastSpace = name.lastIndexOf(' ');
if (lastSpace != -1) {
String lastName = name.substring(lastSpace + 1);
String partBeforeLastName = name.substring(0, lastSpace);
return lastName + ", " + partBeforeLastName;
} else {
return name;
}
You don't actually really care about the other space (if it's there at all), since the first and middle names stay in the same relative order.
(Generally, there are lots of falsehoods that programmers believe about names; but let's put those aside for the purpose of the exercise.)
Your code assumes that the input String contains at least two spaces. When that assumption is wrong (as in the inputs "Harry Smith" and "Sarah"), you get an exception.
You must check whether firstIndex and secondIndex are positive before using their values.
The problem is that your code excepts that there are 3 names. It does not handle when there are less names.
public static String lastNameFirst(String name)
{
int firstIndex = name.indexOf(" ");
if ( firstIndex >= 0 )
{
int secondIndex = name.indexOf(" ", firstIndex + 1 );
String firstName = name.substring(0, firstIndex);
if ( secondIndex >= 0 ) // we have 3 names
{
String middleName = name.substring(firstIndex + 1, secondIndex);
String lastName = name.substring(secondIndex + 1);
return lastName + ", " + firstName + " " + middleName;
}
else // we have 2 names
{
String lastName = name.substring(firstIndex + 1);
return lastName + ", " + firstName;
}
}
else // have only one name
return name;
}
Should worth trying lastIndexOf(), too:
public static String lastNameFirst(String name)
{
int lastIndex = name.lastIndexOf(" ");
if ( lastIndex >= 0 ) // have at least 2 names
{
String firstNames = name.substring(0,lastIndex);
String lastName = name.substring(lastIndex + 1);
return lastName + ", " + firstNames;
}
}
else // have only one name
return name;
}
Also, could try a different approach, split the name into an array, something like this:
public static String lastNameFirst(String name)
{
String[] parts = name.split(" ");
switch ( parts.length )
{
case 1:
return name;
case 2:
return parts[1] + ", " + parts[0];
case 3:
return parts[2] + ", " + parts[0] + " " + parts[1];
}
}

String method output not understanding

From the below question I din't understand how the output has come. Could someone please explain me how did it come ?
public class mystery{
public static void main(String[] args) {
System.out.println(serios("DELIVER"));
}
public static String serios(String s)
{
String s1 = s.substring(0,1);
System.out.println(s1);
String s2 = s.substring(1, s.length() - 1);
System.out.println(s2);
String s3 = s.substring(s.length() - 1);
System.out.println(s3);
if (s.length() <= 3)
return s3 + s2 + s1;
else
return s1 + serios(s2) + s3;
}
}
Output:
D
ELIVE
R
E
LIV
E
L
I
V
DEVILER
Thanks !!
For this chunk of code
String s1 = s.substring(0,1);//this initializes s1 = D as Substring reads up to right before the ending index which is 1.
System.out.println(s1);//print s1
This chunk
String s2 = s.substring(1, s.length() - 1);//Starts where the previous chunk left off, ends right before the ending initializing s2 = ELIVE
System.out.println(s2);//print s2
Final Chunk
String s3 = s.substring(s.length() - 1);//This chunk starts from the end and captures R
System.out.println(s3);//print s3
These three chunks and their print statements will give you
D ELIVE R
Now let's move on.
The final return statement returns s1 + serios(s2) + s3. This is recursion, a function called within itself.
This recursion will run until the if condition is met. Finally printing out DELIVER
You can see a pattern to understand better.
DELIVER when run through the code is printed out like this D ELIVE R. The first and last letters are separated from the center of the word.
return s1 + serios(s2) + s3;
since s2 = ELIVE it will become equal to s. It will be split apart using substring just like DELIVER to become E LIV E setting
LIV = s2
s will now equal LIV, and be split apart and printed out as
L I V
Finally the length of s is equal to 3, so the if condition will run and print out DEVILER
apart of what subString is doing, I think your problem is about recursive behavior of the series method.
at first call u send "DELIVER".
at the following line you can see if the input param is grater than 3 the method call itself agin this time with s2. for the first iteration s2 = ELIVE.
if (s.length() <= 3)
return s3 + s2 + s1;
else
return s1 + serios(s2) + s3;
you can think about running series("ELIVE"); and for the same process you will see this time s2 will get "LIV" which the recursion do not happen again and if part will run.
if (s.length() <= 3)
return s3 + s2 + s1;
I hope this help you.
For this type of tasks, it helps to trace the method calls
public class mystery {
public static void main(String[] args)
{
serios("DELIVER", "");
}
public static String serios(String s, String indentation)
{
String s1 = s.substring(0, 1);
System.out.println(indentation + "\"" + s1 + "\" is the substring of \"" + s + "\" at 0");
String s2 = s.substring(1, s.length() - 1);
System.out.println(indentation + "\"" +s2 + "\" is the substring of \"" + s + "\" from 1 to " + (s.length() - 2));
String s3 = s.substring(s.length() - 1);
System.out.println(indentation + "\"" + s3 + "\" is the substring of \"" + s + "\" at " + (s.length() - 1));
if (s.length() <= 3)
return s3 + s2 + s1;
else
{
indentation += " ";
return s1 + serios(s2, indentation) + s3;
}
}
}
Output:
"D" is the substring of "DELIVER" at 0
"ELIVE" is the substring of "DELIVER" from 1 to 5
"R" is the substring of "DELIVER" at 6
"E" is the substring of "ELIVE" at 0
"LIV" is the substring of "ELIVE" from 1 to 3
"E" is the substring of "ELIVE" at 4
"L" is the substring of "LIV" at 0
"I" is the substring of "LIV" from 1 to 1
"V" is the substring of "LIV" at 2

Printing separate name variations in java?

I am making a programming to print the following
user inputs name like so --> first middle last
prints:
FML
Variation one: LAST, First M.
Variation two: Last, First Middle
Now, I need an if statement so that if just a first name is entered it says "error, incorrect input"
I coded this horribly and extremely unconventional, but hey, this is the first thing I've ever programmed before, so I guess we all start somewhere.
import java.util.Scanner;
public class name {
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);
String fullName = input.nextLine();
String firstName;
String middleName;
String lastName;
//Declares length of entire name
int nameLength = fullName.length();
//Declares int where first space is
int a = fullName.indexOf(" ");
//Declares int where second space is
int b = fullName.lastIndexOf(" ");
//If they equal each other, then there is only one space
if ( a == b )
{
firstName = fullName.substring(0,a);
lastName = fullName.substring(a+1,nameLength);
String firstNameInitial = firstName.substring(0,1);
String lastNameInitial = lastName.substring(0,1);
String upperCaseInitials = (firstNameInitial.toUpperCase() + lastNameInitial.toUpperCase());
firstName = fullName.substring(0,a);
lastName = fullName.substring(b+1,nameLength);
System.out.println("Your initials are: " + upperCaseInitials);
System.out.println("Variation One: " + lastName.toUpperCase() + ", " + firstNameInitial.toUpperCase() + firstName.substring(1,a));
System.out.println("Variation Two: " + lastNameInitial.toUpperCase() + lastName.substring(1,lastName.length()) + ", " + firstNameInitial.toUpperCase() + firstName.substring(1,a));
}
//If a < b then it will notice a middle name exists due to multiple spaces
else if ( a < b )
{
firstName = fullName.substring(0,a);
middleName = fullName.substring(a+1,b);
lastName = fullName.substring(b+1,nameLength);
String firstNameInitial = firstName.substring(0,1);
String middleNameInitial = middleName.substring(0,1);
String lastNameInitial = lastName.substring(0,1);
String upperCaseInitials = (firstNameInitial.toUpperCase() + middleNameInitial.toUpperCase() + lastNameInitial.toUpperCase());
//MNIC = Middle Name Initial Capitalized
String MNIC = middleNameInitial.toUpperCase();
//MNIMFC = Middle Name Initial Minus First Character
String MNIMFC = middleName.substring(1, middleName.length());
System.out.println("Your initials are: " + upperCaseInitials);
System.out.println("Variation One: " + lastName.toUpperCase() + ", " + firstNameInitial.toUpperCase() + firstName.substring(1,a) + " " + middleNameInitial.toUpperCase() + "." );
System.out.println("Variation Two: " + lastNameInitial.toUpperCase() + lastName.substring(1,lastName.length()) + ", " + firstNameInitial.toUpperCase() + firstName.substring(1,a) + " " + MNIC + MNIMFC);
}
}
}
You can use the String.split() function to split a String into its parts along a seperator.
In your case that would be the space (" ")
Try:
Scanner input = new Scanner(System.in);
String fullName = input.nextLine();
String firstName;
String middleName;
String lastName;
String[] parts = fullName.split(" ");
if(parts.length() == 3){
// 3 words were entered, so there is a middle name
}
// ...
You can just add this check
if(fullName.indexOf(" ")==-1 || (fullName.indexOf(" ") == fullName.lastIndexOf(" "))){
// The first check is to check if only firstname was given and the second check is to check if only first and middle names were given.
// If first + middle is a valid scenario, you can remove the second half of the if condition
System.out.println("error, incorrect input");
System.exit(0);
}
before the below statement in your code.
int nameLength = fullName.length();
You can simply check for a == -1. indexOf returns -1 if not found (as per the docs).
if (a == -1)
System.out.println("Error, invalid input!");
else if (a == b)
...
You can narrow down to the condition you stated by following these steps:
Trim the input String fullName before statement int a = fullName.indexOf(" ");
Next check if the index of whitespace (i.e. value of a and b variables) is -1, then you can assume that the input contains only a single word, presumably Firstname
Print the error message "error, incorrect input"
since it's your first attempt, I'll give you a modified version of your code:
public class name {
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);
String fullName = input.nextLine();
String firstName;
String middleName;
String lastName;
//Declares length of entire name
int nameLength = fullName.length();
//Declares int where first space is
int a = fullName.indexOf(" ");
//Declares int where second space is
int b = fullName.lastIndexOf(" ");
/*** Use the split function to split the names with spaces as delimiter **/
String[] n = fullName.split(' ');
firstName = n[0];
if( n.length == 2 ) {
lastName = n[1];
}
if( n.length > 3 ) {
lastName = n[1];
middleName = n[2];
}
String firstNameInitial = firstName.substring(0,1);
String middleNameInitial = middleName.substring(0,1);
String lastNameInitial = lastName.substring(0,1);
String upperCaseInitials = (firstNameInitial.toUpperCase() + middleNameInitial.toUpperCase() + lastNameInitial.toUpperCase());
//MNIC = Middle Name Initial Capitalized
String MNIC = middleNameInitial.toUpperCase();
//MNIMFC = Middle Name Initial Minus First Character
String MNIMFC = middleName.substring(1, middleName.length());
System.out.println("Your initials are: " + upperCaseInitials);
System.out.println("Variation One: " + lastName.toUpperCase() + ", " + firstNameInitial.toUpperCase() + firstName.substring(1,a) + " " + middleNameInitial.toUpperCase() + "." );
System.out.println("Variation Two: " + lastNameInitial.toUpperCase() + lastName.substring(1,lastName.length()) + ", " + firstNameInitial.toUpperCase() + firstName.substring(1,a) + " " + MNIC + MNIMFC);
}
}

Why can't I pass a variable as format string to System.out.printf (...) in java?

I was trying to pass a string object to System.out.printf(...) in Java, but I kept getting this error "java.util.FormatFlagsConversionMismatchException: Conversion = s, Flags = 0" which actually doesn't make a lot of sense to me.
String format = "%" + (3 * n) + "s"; // n is an int defined somewhere above, could be 0
System.out.printf(format, "My string");
Does anyone know if this is allowed?
Edit for more details:
int n = 0;
String fm = "%" + (3 * level) + "s";
String realFm = "%0s";
System.out.println("fm = " + fm);
System.out.println("realfm = " + realFm);
System.out.println("equals? " + (fm.equals(realFm)));
System.out.printf(fm, " ");
Here's the output:
fm = %0s
realfm = %0s
equals? true
java.util.FormatFlagsConversionMismatchException: Conversion = s, Flags = 0
Thanks
Yes it's allowed, but it won't work if n is 0. Is there a chance of this happening (looks like it from the error message)?
what if you add a line to your code to debug it:
// line added below for debugging. To remove later:
System.out.println("n is: " + n);
String format = "%" + (3 * n) + "s"; // n is an int defined somewhere above
System.out.printf(format, "My string");
Does it ever print n is: 0?
e.g.,
public static void main(String[] args) {
// try the for loop with n = 0 vs. n = 1
for (int n = 1; n <= 10; n++) {
// line added below for debugging. To remove later:
System.out.println("\nn is: " + n);
String format = "%" + (3 * n) + "s";
System.out.printf(format, "My string");
}
}

Categories

Resources