Problems with Output in Java - 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);
}
}

Related

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!

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);

What's Wrong? Number Of Words In a Sentence Java

int numOfWords = str.length() - str.replace(" ", "").length();
Why does that not work? If str is equal to "Hello bye", numOfWords should equal 2, but when ran numOfWords equals 0. Any help would be greatly appreciated!
You are only replacing one blank, so the output will be 1 (at least this is what is produce in my JVM)
If you want to know the number of words then either add 1 to this number or use
str.split(" ").length;
Why dont you use :
int numOfWords = str.split(" ").length;
I hope out put is much clear
public static void main(String[] args) {
String str = "Hello bye";
System.out.println("Length of Input String = " + str.length() + " for String = " + str);
System.out.println("Length of Input String with space removed = " + str.replace(" ", "").length() + " for String = "
+ str.replace(" ", ""));
int numOfWords = str.length() - str.replace(" ", "").length();
System.out.println(numOfWords);
}
Output
Length of Input String = 9 for String = Hello bye
Length of Input String with space removed = 8 for String = Hellobye
1

Program Runs but No Output?

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);
}
}

Java split line not working

this is my code
//Numbers (Need errors on sort and numbers)
if(line.contains("n"))
{
//split the line with space
String[] LineSplit = line.split(" ");
if(LineSplit[0].contains("n"))
{
//split the already split line with "n thename "
String[] LineSplit2 = line.split("n " + LineSplit[0] + " ");
String text = "var " + LineSplit[1] + "=" + LineSplit2[0] + ";";
text = text.replace("\n", "").replace("\r", "");
JAVASCRIPTTextToWrite += text;
}
}
the line of text is
n number 1
the output should be
var number = 1;
but the output is
var number=n number = 1;
can some one please tell me how to fix this? the code looks right but doesn't work :(
String line = "n number 1";
String JAVASCRIPTTextToWrite="";
if(line.contains("n"))
{
//split the line with space
String[] LineSplit = line.split(" ");
if(LineSplit[0].contains("n"))
{
//split the already split line with "n thename "
String[] LineSplit2 = line.split("n " + LineSplit[1] + " ");
System.out.println( LineSplit[1]);
System.out.println( LineSplit2[0]);
String text = "var " + LineSplit[1] + "=" + LineSplit2[1] + ";";
text = text.replace("\n", "").replace("\r", "");
JAVASCRIPTTextToWrite += text;
System.out.println(JAVASCRIPTTextToWrite);
}
}
String number = "n number 1";
Sting[] temp = number.split(" ");
StringBuilder sb = new StringBuilder("var ");
sb.append(temp[1]);
sb.append(temp[2]);
perform this operation if your condition satisfied
String line = "n number 1";
if(line.contains("n"))
{
//split the line with space
String[] LineSplit = line.split(" ");
if(LineSplit[0].contains("n")) {
//split the already split line with "n thename "
String LineSplit2 = line.substring(line.lastIndexOf(" ") + 1 , line.length());
String text = "var " + LineSplit[1] + "=" + LineSplit2 + ";";
//text = text.replace("\n", "").replace("\r", "");
System.out.println(text);
}
}
Output:
var number=1;
I do not know what is your purpose for split the string twice. Just for the out put you want, I think the solution below is enough. Please look at the code below whether is you want:
String line = "n number 1";
String JAVASCRIPTTextToWrite = "";
//Numbers (Need errors on sort and numbers)
if(line.contains("n")) {
//split the line with space
String[] LineSplit = line.split(" ");
if(LineSplit.length == 3) {
StringBuilder text = new StringBuilder();
text.append("var ");
text.append(LineSplit[1]);
text.append("=");
text.append(LineSplit[2]);
text.append(";");
JAVASCRIPTTextToWrite += text.toString().replace("\n", "").replace("\r", "");
System.out.println(JAVASCRIPTTextToWrite);
}
}

Categories