Program Runs but No Output? - java

Sorry, I'm a bit clueless when it comes to this and I'm having a bit of trouble with this specific portion of my program.
The goal is, when someone inputs a three word string, to rearrange it in such a way that "Emma Charlotte Leonard" becomes " Leonard, Emma, C".
This is what I have so far for that specific method:
public String lastFirst (String str)
{
Scanner keyboard = new Scanner(System.in);
System.out.println ("Enter your name");
String lastFirst = keyboard.nextLine();
String middleAndLast = lastFirst.substring(lastFirst.indexOf(" ")+ 1);
String last = middleAndLast.substring(middleAndLast.indexOf(" ") + 1);
String first = lastFirst.substring(0, lastFirst.indexOf(" "));
String middle = middleAndLast.substring(0, middleAndLast.indexOf(" "));
char middleInitial = middle.charAt(0);
return("\"" + last + ", " + first + ", " + middleInitial + "\"");
}
Any help would be appreciated, sorry if I haven't put enough information.

I believe this is what you are trying to achieve:
public class RearrangeName{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println ("Enter your name");
String inputStr= keyboard.nextLine();
System.out.println(lastFirst(inputStr));
}
public static String lastFirst (String str){
String middleAndLast = str.substring(str.indexOf(" ")+ 1);
String last = middleAndLast.substring(middleAndLast.indexOf(" ") + 1);
String first = str.substring(0, str.indexOf(" "));
String middle = middleAndLast.substring(0, middleAndLast.indexOf(" "));
char middleInitial = middle.charAt(0);
return("\"" + last + ", " + first + ", " + middleInitial + "\"");
}
}
See the Demo here

Do you want output to be "Leonard, Charlotte, L" or "Leonard, Emma, C".
Current output of your program is the second option. And if you desired first output then you should declare middleInitial as String middleInitial =last.charAt(0);.

Try following example it is return the "Emma Charlotte Leonard" as " Leonard, Charlotte, L"
public class Example{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Example exp = new Example();
System.out.print("Enter your number : ");
System.out.println(exp.getName(input.nextLine()));
}
private String getName(String name){
String arr[] = name.split(" ");
return arr[2]+ ", "+arr[1]+", "+arr[2].substring(0, 1);
}
}

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) + ".");
}

Remove whitespace from start and end of String without trim()

How to remove whitespace from the start and end of a String without using the trim() method?
here is my code
public class StringTest {
public static void main(String[] args) {
String line = " Philippines| WNP|Naga |Camarines Sur|Naga Airport ";
//System.out.println(line);
int endIndex = line.indexOf("|");
String Country = line.substring(0, endIndex);
line = line.substring(endIndex + 1);
int endIndexCountry = line.indexOf("|");
String Code = line.substring(0, endIndexCountry);
line = line.substring(endIndexCountry + 1);
int endIndexCode = line.indexOf("|");
String City = line.substring(0, endIndexCode);
line = line.substring(endIndexCode + 1);
int endIndexCity = line.indexOf("|");
String State = line.substring(0, endIndexCity);
line = line.substring(endIndexCity + 1);
System.out.print("Code:" + Code + "____");
System.out.print("Country:" + Country + "____");
System.out.print("State:" + State + "____");
System.out.print("City:" + City + "____");
System.out.println("Airport:" + line+ "____");
}
}
and my output looks like this
Code: WNP____Country: Philippines____State:Camarines Sur____City:Naga ____Airport:Naga Airport ____
I need to look like this(without whitespaces)
Code:WNP____Country:Philippines____State:Camarines Sur____City:Naga____Airport:Naga Airport____
How to remove whitespace from the start and end of a String without
using the trim() method?
You can do it using a combination of regex patterns and String::replaceAll.
public class Main {
public static void main(String[] args) {
String str = " Hello ";
System.out.println("Before: " + str + "World!");
str = str.replaceAll("^[ \\t]+", "").replaceAll("[ \\t]+$", "");
System.out.println("After: " + str + "World!");
}
}
Output:
Before: Hello World!
After: HelloWorld!

Problems with Output in Java

I have no idea why my output is not coming out correct. For example, if the input is "Running is fun" then the output should read "Is running fun". However, the output I am getting is "Iunning".
import java.util.Scanner;
public class Problem1 {
public static void main( String [] args ) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter text: ");
String sentence = sc.nextLine();
int space = sentence.indexOf(" ");
String firstWord = sentence.substring(0, space + 1);
String removedWord = sentence.replaceFirst(firstWord, "");
String newSentence = removedWord.substring(0,1).toUpperCase() +
firstWord.substring(1).toLowerCase();
System.out.println("");
System.out.println( newSentence );
}
}
removedWord.substring(0,1).toUpperCase() this line adds the capitalized first letter of the second word in the sentence. (I)
firstWord.substring(1).toLowerCase(); adds every letter of the first word to the end of the sentence. (unning)
Thus this creates the output of Iunning. You need to add the rest of removedWord to the String, as well as a space, and the first letter of firstWord, as a lower case letter at the space in removedWord. You can do this more by using indexOf to find the space, and then using substring() to add on firstWord.toLowerCase() right after the index of the space:
removedWord = removedWord.substring(0, removedWord.indexOf(" ")) + " " +
firstWord.toLowerCase() +
removedWord.substring(removedWord.indexOf(" ") + 1,
removedWord.length());
String newSentence = removedWord.substring(0,1).toUpperCase() +
removedWord.substring(1, removedWord.length());
Output:
Is running fun
Your problem is that
firstWord.substring(1).toLowerCase()
Is not working as you expect it to work.
Given firstWord is “Running“ as in your example, then
”Running“.substring(1)
Returns ”unning“
”unning“.toLowerCase()
Obviously returns ”unning“
The problem is at String newSentence. You not make the right combination of firstWord and removedWord.
This is how should be for your case:
String newSentence = removedWord.substring(0, 1).toUpperCase() // I
+ removedWord.substring(1,2) + " " // s
+ firstWord.toLowerCase().trim() + " " // running
+ removedWord.substring(2).trim(); // fun
EDIT(add new solution. credits #andy):
String[] words = sentence.split(" ");
words[1] = words[1].substring(0, 1).toUpperCase() + words[1].substring(1);
String newSentence = words[1] + " "
+ words[0].toLowerCase() + " "
+ words[2].toLowerCase();
This works properly:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter text: ");
String sentence = sc.nextLine();
int space1 = sentence.indexOf(' ');
int space2 = sentence.indexOf(' ', space1 + 1);
if (space1 != -1 && space2 != -1) {
String firstWord = sentence.substring(0, space1 + 1);
String secondWord = sentence.substring(space1 + 1, space2 + 1);
StringBuilder newSentence = new StringBuilder(sentence);
newSentence.replace(0, secondWord.length(), secondWord);
newSentence.replace(secondWord.length(), secondWord.length()+ firstWord.length(), firstWord);
newSentence.setCharAt(0, Character.toUpperCase(newSentence.charAt(0)));
newSentence.setCharAt(secondWord.length(), Character.toLowerCase(newSentence.charAt(secondWord.length())));
System.out.println(newSentence);
}
}

String Method-converting string to char then display the characters with a specified index

I'm trying to make a code regarding string methods that accepts a string and returns the value of getChars. Indexes or indices should be an input from the user. A string should be converted to an array of character which will be used as destination. However, I'm having some confusing errors.
Any help?
Here's the code/.
import java.util.*;
public class Exercise5 {
public static void main(String[] args) {
//Stay Calm and Be Cool!
Scanner a = new Scanner(System.in);
String string = new String();
System.out.print("Enter any String: ");
string = a.nextLine();
System.out.print("Enter source begin index: ");
int begin = a.nextInt();
System.out.print("Enter source end index: ");
int end = a.nextInt();
System.out.print("Enter destination index: ");
int dest = a.nextInt();
char[] sample = string.toCharArray();
System.out.println("The value extracted from " + string + " with indexes "+ begin + " to "+ end + " is: " +
string.getChars(begin, end, sample, dest));
}
}
ERROR: void is not allowed. ---how to get rid of that?
String#getChars do not return any value, it writes the result into dest parameter:
final int length = end - begin;
char[] sample = new char[length];
string.getChars(begin, end, sample, dest);
System.out.println("The value extracted from " + string + " with indexes "+ begin + " to "+ end + " is: " + sample);

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