Need Help Beginner Java Program "STRINGS" [duplicate] - java

This question already has answers here:
How to capitalize the first character of each word in a string
(51 answers)
How to upper case every first letter of word in a string? [duplicate]
(16 answers)
Closed 8 years ago.
Hey guys so im new to java and im trying to write a program that declares two strings
First && Last name ( both under case )
And i need to use the .uppercase to convert the first letter in both the first name and last name from lower case to uppercase.
Example convert jon to Jon
This is what i have so far
I really dont understand how i make the first letter uppercase.
/////
public class firstProgram {
public static void main(String args[])
{
//NAME GOES HERE. DECLARED 2 STRINGS
String first = "firstname";
String last = "lastname";
//PRINT OUT STRINGS
System.out.println(first);
System.out.println(last);
}
}

You can do something like -
String first = "firstname";
String last = "lastname";
first = String.valueOf(first.charAt(0)).toUpperCase() + first.substring(1);
last = String.valueOf(last.charAt(0)).toUpperCase() + last.substring(1);
//PRINT OUT STRINGS
System.out.println(first);
System.out.println(last);
You can check documentation for toUpperCase().

If you only want to capitalize the first letter of a string named first and leave the rest alone:
first = first.substring(0, 1).toUpperCase() + first.substring(1);
Now first will have what you want.
Do like this for last

You can do this by employing the String class subString methods.
String input = "first name";
String out = input.substring(0, 1).toUpperCase() + input.substring(1);

firstName = Character.toUpperCase(firstName.charAt(0)) + firstName.substring(1);
lastName = Character.toUpperCase(lastName.charAt(0)) + lastName.substring(1);
or in class
class FirstProgram {
public static void main(String[] args) {
String firstName = "arun";
String lastName = "kumar";
firstName = Character.toUpperCase(firstName.charAt(0)) + firstName.substring(1);
lastName = Character.toUpperCase(lastName.charAt(0)) + lastName.substring(1);
System.out.println(firstName+ " "+lastName);
}
}

Related

Debugging a simple console game for Java

import java.util.Scanner;
public class Project3 {
public static void main(String[] args) {
Scanner keys = new Scanner(System.in);
System.out.println("Welcome to mini mad libs!"); // word1-word3 are inputs that point out which words from the story need to be replaced.
System.out.printf("Please enter the story: ");
String story = keys.nextLine();
System.out.printf("Please enter the first word type that should be replaced:");
String word1 = keys.nextLine();
System.out.printf("Please enter the second word type that should be replaced:");
String word2 = keys.nextLine();
System.out.printf("Please enter the third word type that should be replaced:");
String word3 = keys.nextLine();
System.out.println();
System.out.println("Ok, the game is ready to play!"); //the replace strings are the new words that are replacing the original words in the story.
System.out.println("Please enter a word type to replace "+word1);
String replace1 = keys.nextLine();
System.out.println("Please enter a word type to replace "+word2);
String replace2 = keys.nextLine();
System.out.println("Please enter a word to replace "+word3);
String replace3 = keys.nextLine();
String storyV2 = story.toLowerCase();
String word1V2 = word1.toLowerCase();
String word2V2 = word2.toLowerCase();
String word3V2 = word3.toLowerCase();
storyV2=storyV2.replaceAll("[.,!]", " ");
int positionOf1= storyV2.indexOf(" "+word1V2+" ");
int positionOf2= storyV2.indexOf(" "+word2V2+" ");
int positionOf3= storyV2.indexOf(" "+word3V2+" ");
int length1 = word1.length();
int length2 = word2.length();
int length3 = word3.length();
String WordMod1 = story.substring(positionOf1,positionOf1+length1);
String WordMod2 = story.substring(positionOf2,positionOf2+length2);
String WordMod3 = story.substring(positionOf3,positionOf3+length3);
String lib = story.replaceFirst(WordMod1, replace1); //lib serves as a string that has a version of the original story replaced by the three words one by one in the next lines below.
lib = lib.replaceFirst(WordMod2, replace2);
lib = lib.replaceFirst(WordMod3, replace3);
System.out.println();
System.out.println("Here is your little mad lib: \n"+ lib);
}
}
Mad libz is a game that replaces selected words from a sentence with other words of your choice. I cannot use if/else statements, loops or anything that is not string methods. My problem seems to be in this part of the code. I'm not too experienced with Java so it might look terrible.
String WordMod1 = story.substring(positionOf1,positionOf1+length1);
String WordMod2 = story.substring(positionOf2,positionOf2+length2);
String WordMod3 = story.substring(positionOf3,positionOf3+length3);
This part is making a substrings that obtain the word in a sentence, for example if I want the word "noun", it looks the standalone word anywhere in the sentence instead of possible getting the word from other words like "pronoun" or "pronounced". PositionOf1 looks for the position between blank spaces and lenghtOf1 is the length of the original word we want to replace.
That is why this is also supposed to be case insensitive so that is why I made string storyV2, its a copy of the original set to lower case.
If you just want to replace one string with another, then why not using the replaceAll() method?
String story = "...";
String fromWord = "foo";
String toWord = "bar";
String newStory = story.replaceAll(" " + foo + " ", " " + bar + " ");
You could use more elaborate regex patterns for finding foo not only enclosed by spaces but all kinds of non-word characters, so you wouldn't need to remove characters like .,; etc. first as you currently do.

How can I pick a string apart and outprint it? [duplicate]

This question already has answers here:
How to split a String by space
(17 answers)
Closed 5 years ago.
public void display()
{
super.display();
String str = super.getChoices();
System.out.println(str);
while(!str.equals(""))
{
int a = str.indexOf(" ");
System.out.println(str.substring(0, a));
String sentence = str.replaceFirst(str, str.substring(a));
System.out.println(sentence);
}
}
I have a String str containing "Apple Banana Orange". I want to system out print these fruits separately because they are each a choice to a question stored in a single variable. How can I do this? The code above is my failed attempt because the substring doesn't update the str variable rather creates a new string. I can't use a loop and I can't make it dynamic and thus not use it.
You need to change str as well:-
while(!str.equals("") ) {
int a = str.indexOf(" ");
System.out.println(str.substring(0, a));
String sentence = str.replaceFirst(str, str.substring(a));
System.out.println(sentence);
str = str.substring(a); // Remove the bit of str that we've processed.
}
(Untested, but you get the idea). You obviously also need to check if str actually contains a space and drop out.
If i understand you correctly, you should try to use StringTokenizer
StringTokenizer st=new StringTokenizer("Apple Banana Orange");
while (st.hasMoreTokens()){
System.out.println(st.nextToken());
}

Scanner method and string pool

The script below will compare two string to see if they are equal. In this case one string is declared and the other string is input from the scanner. I understand why these two string are not equal when compared (say aName = test and anotherName= test) because they will contain different references addresses.
This next paragraph will lead into my question. The nextLine() method returns a string. I know normally if two strings contain the same text they would have the same address in the string pool. So my question is, why isn't the string returned from the nextLine() method to the anotherName variable assigned to the string pool and given the same address as aName, since they have the same text? *
import java.util.Scanner;
public class TryToCompareString
{
public static void main(String[] args)
{
String aName = "test";
String anotherName;
Scanner input = new Scanner(System.in);
System.out.println("Enter your name");
anotherName = input.nextLine();
if (aName == anotherName)
{
System.out.println(aName + " equals " + anotherName);
}
else
{
System.out.println(aName + " does not equal " + anotherName);
}
}
}

How to get started with writing a program that consists of three classes [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Write a program that consists of three classes. The first class will be the actual program.
The second class will simply convert a string to lower case.
The third class will have three methods: I have been working on this assignment but i need some help. All my previous assignments have been only in one string. So i'm not sure how to get started with this. I will list what i have tried so far.
import java.io.*;
public class A3BE2300780
{
BufferedReader in = getReader ("input.txt");
private static class LowerCase {
public static String convertToLowerCase(String input) {
if (input==null) return "";
return input.toLowerCase();
}
}
public static class ThirdStringManip{
//This method will trim the white space from the
//beginning and end of the string
public static String trimmed(String s){
if (s == null){
return "";
}
return s.trim();
}
//This method will return a trimmed string of size len
public static String trimmed(String s, int len){
String retVal = ThirdStringManip.trimmed(s);
if (len > retVal.length()){
len = retVal.length();
}
return retVal.substring(0,len);
}
//This method will convert all double spaces to a single space
public static String squeeze(String s){
return s.replace(" ", " ");
}
}
//This method will read strings from the input file
//and perform manipulations on each string. The results of the
//manipulations are displayed in the text area
private void displayManipulatedStrings() throws Exception{
while(loop)
{
//Get the next line in the file
String curString = s.nextLine();
//Trim and Squeeze
System.out.print ( "Trim & Squeeze: " + ThirdStringManip.squeeze(ThirdStringManip.trimmed(curString)) + "\n");
//Trim, Squeeze, and Shorten to 10 characters
System.out.print ( "Trim, Squeeze, Shorten to 10: " + ThirdStringManip.trimmed(ThirdStringManip.squeeze(ThirdStringManip.trimmed(curString)),10) + "\n");
//Trim, Squeeze, lower-case and shorten to 20 characters
System.out.print ( "Trim, Squeeze, Shorten to 20, lower-case: " + toLower(ThirdStringManip.trimmed(ThirdStringManip.squeeze(ThirdStringManip.trimmed(curString)),20)) + "\n");
System.out.print ( "\n");
}
}
}
Ok so ... Some JAVA book & online tutorials will help a lot...
To start
Main class is where your main method is. So create a new empty class and add your main method to it.
public static void main (String[] args) {
//inside you can put some logic
}
Create another class and i.e StringConversion and insert a simple method iniside for example
class StringConversion {
private String lowerCaseString = "";
public String stringConversion(String somestring) {
lowerCaseString = somestring.toLowerCase();
return this.lowerCaseString;
}
}
Then create a third class with whatever methods you require
In your main method you can do
StringConversion lowerCaseString = new StringConversion();
String lowerCase = lowerCaseString.stringConversion("SOME STRING");
Then you can just print out the lowerCase string ;)
ALSO NOTE: MEGA ULTRA UBER IMPORTANT
When asking question on StackOverflow do not ASK US to do something for you, You have to show effort and show us what you tried by either explaining nicely or showing to us what have you done and why it didn't work. You can not just dump a homework question and pray that someone will do it for you. it just doesn;t work that way, and often you will find your questions to be locked and closed

What did I do wrong in my program?

I am writing a program where if someone types in the following two lines:
HELLO, I’D LIKE TO ORDER A FZGH
KID’S MEAL
The program will output it like this:
HELLO, I’D LIKE TO ORDER A KID’S MEAL
In other words, the "FZGH" the user inputs into the sentence will be replaced with the second line's words, as you can see: the "FZGH" is replaced by "KID'S MEAL." Kinda get what I mean? If not, I can elaborate more but this is the best I can explain it as.
I'm really close to solving this! My current output is: HELLO, I’D LIKE TO ORDER A FZGH KID’S MEAL
My program didn't replace the "FZGH" with "KID'S MEAL," and I don't know why that is. I thought that by using the .replaceAll() thingy, it would replace "FZGH" with the "KID'S MEAL," but that didn't really happen. Here is my program so far:
public static void main(String[] args) {
sentences();
}
public static void sentences() {
Scanner console = new Scanner(System.in);
String sentence1 = console.nextLine();
String sentence2 = console.nextLine();
//System.out.println(sentence1 + "\n" + sentence2);
String word = sentence1.replaceAll("[FZGH]", "");
word = sentence2;
System.out.print(sentence1 + word);
}
Where did I mess up, resulting in the FZGH still appearing in output?
Use
sentence1 = sentence1.replaceAll("FZGH", "");
String word = sentence2;
Your first (and primary) problem is that you're creating a new String named word, that you're setting to the value of sentence1.replaceAll("[FZGH]", ""). You're then changing the value of word to be sentence2 immediately afterward, so the replacement is lost.
Instead, setting sentence1 to sentence1.replaceAll("FZGH", ""); will change sentence1 to no longer contain the string "FZGH", which is what you're going for. You don't actually need a word value at all, so if you'd like to remove it, it wouldn't hurt.
In addition, using [FZGH] will replace all F's, Z's, G's, and H's from the string- you should use FZGH instead, as this will only remove instances of all four letters in a row.
I think you have a couple of mistakes. Maybe the following is close...
public static void main(String[] args) {
sentences();
}
public static void sentences() {
Scanner console = new Scanner(System.in);
String sentence1 = console.nextLine();
String sentence2 = console.nextLine();
String sentence3 = sentence1+sentence2;
String final = sentence3.replaceAll("FZGH", "");
System.out.print(final);
}
You are reassigning the string "word"
in place of lines :
String word = sentence1.replaceAll("[FZGH]", "");
word = sentence2;
System.out.print(sentence1 + word);
use the following lines
sentence1 = sentence1.replaceAll("[FZGH]", "");
System.out.print(sentence1 + sentence2);
Actually replace method return a string that should be assign again to sentence1. you can run this code its works fine.
public static void main(String[] args) {
sentences();
}
public static void sentences() {
Scanner console = new Scanner(System.in);
String sentence1 = "HELLO, I’D LIKE TO ORDER A FZGH";
String sentence2 = "KID’S MEAL";
//System.out.println(sentence1 + "\n" + sentence2);
sentence1 = sentence1.replace("FZGH", "");
String word = sentence2;
System.out.print(sentence1 + word);
}

Categories