Creating a Java String array - java

I'm not sure how to get the program to understand there are three different strings in the text file, and how would I add this to my code? I've never created an array before although I'm fairly experienced with creating fun Java programs (like calculators and such) and want to move onto the next step
I've made a program which does the following:
Program Functions:
Asks user to enter a string.
Asks user to enter a second string which will replace the last two characters of each word of the first string.
Asks user to enter a third string who's first character will replace every letter "I" of each word of the first string.
*If the words in the first string are less than two characters and do not include an I- the string will be left alone.
And here is the working code (I'm running with Ready to Program - not sure why the first bit is not included in the code):
import java.io.*;
import java.util.*;
public class StringModifications
{
private String input1, input2, input3; // Values only used within this method
public String information;
// Constructor
public StringModifications ()
{
// Initialize class data to 0
this.input1 = "";
this.input2 = "";
this.input3 = "";
}
public void setInputStrings (String s1, String s2, String s3)
{
// Method to set class data
this.input1 = s1; // Equal to string 1
this.input2 = s2;
this.input3 = s3;
}
public String processStrings ()
{
StringTokenizer stok = new StringTokenizer (this.input1); // Splits first input string (word by word)
StringBuffer strBuff = new StringBuffer ("");
String outstring = ""; // Initialize variable to 0
while (stok.hasMoreTokens () == true) // As long as there are more words in the string:
{
String word = stok.nextToken ();
if (word.length () > 2)
{
word = word.substring (0, word.length () - 2); // Removes the last two letters of each word in the first string
word = word.concat (this.input2); // Adds the second input to the end of the first string
char letter = input3.charAt (0); // Finds the first letter of the third input
word = word.replace ('I', letter); // Replaces letter I in first string with first letter of third input
}
outstring = outstring + word + " "; // Adds a space between each word when output
}
return outstring;
}
public static void main (String[] args) throws IOException
{
String string1, string2, string3;
BufferedReader keyboard = new BufferedReader ( // // Define the input stream reader
new InputStreamReader (System.in));
System.out.println ("Enter first string"); // User inputs the first string
string1 = keyboard.readLine ();
System.out.println ("Enter second string"); // User inputs the econd string
string2 = keyboard.readLine ();
System.out.println ("Enter third string"); // User inputs the third string
string3 = keyboard.readLine ();
StringModifications strProc = new StringModifications ();
strProc.setInputStrings (string1, string2, string3); // Sends values to method (e.g. this.input1 = stirng 1)
PersonalInfo pi = new PersonalInfo();
String out = strProc.processStrings (); // String (e.g. this.input1) sent through processStrings method before output
System.out.println ("Original Input: " + string1); // Displays the original input
System.out.println ("Modified Input: " + out); // Displays the modified input
}
}
and what I am trying to do is create an array which takes three inputs (Strings, which would be string1, 2 and 3 in the code), as following in the text:
1
hello how are you (string 1)
i am good (string 2)
great (stirng 3)
I'm not sure how to get the program to understand there are three different strings in the text file, and how would I add this to my code? I've never created an array before although I'm fairly experienced with creating fun Java programs (like calculators and such) and want to move onto the next step

You use String[] str = new String[n] to declare and initialize a new String array. This is a static array with a fixed length of n, where n has to be known during the initialization. Individual elements are accessed through str[i], where i is the index of an element from interval [ 0,n ).
Example of usage:
String[] phrases = new String[3];
phrases[0] = "Hello, how are you?";
phrases[1] = "I am good";
phrases[2] = "Great";
System.out.println("What phrase would you wish to see?");
Scanner in = new Scanner(System.in);
System.out.println(phrases[in.nextInt()]);
in.close();
If you need a dynamic array with variable number of elements, I would suggest looking into ArrayList class.

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 to limit the number of words when reading a line from standard input?

I am new to Stackoverflow and this is my first time asking a question. I have searched my problem thoroughly, however, could not find an appropriate answer. I am sorry if this has been asked. Thank you in advance.
The question is from Hyperskill.com as follows:
Write a program that reads five words from the standard input and outputs each word in a new line.
First, you need to print all the words from the first line, then from the second (from the left to right).
Sample Input 1:
This Java course
is adaptive
Sample Output 1:
This
Java
course
is
adaptive
My trial to solve it
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
/* I have not initialized the "userInput" String.
* I know that String is immutable in Java and
* if I initialize it to an empty String ""
* and read a String from user.
* It will not overwrite to the "userInput" String.
* But create another String object to give it the value of the user input,
* and references the new String object to "userInput".
* I didn't want to waste memory like that.
*/
String userInput;
String[] userInputSplitFirstLine = new String[3];
String[] userInputSplitSecondLine = new String[2];
Scanner scan = new Scanner(System.in);
userInput = scan.nextLine();
userInputSplitFirstLine = userInput.split("\\s+");
userInput = scan.nextLine();
userInputSplitSecondLine = userInput.split("\\s+");
for(String firstLineSplitted: userInputSplitFirstLine) {
System.out.println(firstLineSplitted);
}
for(String secondLineSplitted: userInputSplitSecondLine) {
System.out.println(secondLineSplitted);
}
scan.close();
}
}
If you try the sample input above, the output will match the sample output above. However, if you write more than 3 words to the first line and/or more than 2 words to the second line, the userInputSplitFirstLine array of size 3 will store more than 3 words. Same goes with the userInputSplitSecondLine array also. My first question is how can an array of size 3 (userInputSplitFirstLine) and an array of size 2 (userInputSplitSecondLine) can hold more than 3 and 2 elements, respectively? My second question is that how can I restrict/limit the number of words that the user can insert in a line; for example, the first line only accepts 3 words and the second line only accepts 2 words?
Also the answer to this question suggested by Hyperskill.com is as follows:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String wordOne = scanner.next();
String wordTwo = scanner.next();
String wordThree = scanner.next();
String wordFour = scanner.next();
String wordFive = scanner.next();
System.out.println(wordOne);
System.out.println(wordTwo);
System.out.println(wordThree);
System.out.println(wordFour);
System.out.println(wordFive);
}
}
You can use next method of scanner object to read string and then it can be printed easily on new line.
while(true){
if(scanner.hasNext()){
System.out.println(scanner.next());
}
else{
break;
}
}
I think this should do the work. Don't hesitate to ask, if you have some questions.
import java.util.Scanner;
class App {
public static void main(String[] args) {
final StringBuffer line = new StringBuffer();
final StringBuffer words = new StringBuffer();
try (final Scanner sc = new Scanner(System.in)) {
while (sc.hasNextLine()) {
final String currentLine = sc.nextLine();
line.append(currentLine).append(System.lineSeparator());
for (final String word : currentLine.split("\\s+")) {
words.append(word).append(System.lineSeparator());
}
}
} finally {
System.out.println(line.toString());
System.out.println();
System.out.println(words.toString());
}
}
}
My first question is how can an array of size 3 (userInputSplitFirstLine) and an array of size 2 (userInputSplitSecondLine) can hold more than 3 and 2 elements, respectively?
The array here:
String[] userInputSplitFirstLine = new String[3];
is not the same one as the one you got from split:
userInputSplitFirstLine = userInput.split("\\s+");
When you do the above assignment, the old array that was in there is basically "overwritten", and now userInputSplitFirstLine refers to this new array that has a length independent of what the old array had. split always return a new array.
My second question is that how can I restrict/limit the number of words that the user can insert in a line; for example, the first line only accepts 3 words and the second line only accepts 2 words?
It really depends on what you mean by "restrict". If you just want to check if there are exactly three words, and if not, exit the program, you can do this:
userInputSplitFirstLine = userInput.split("\\s+");
if (userInputSplitFirstLine.length != 3) {
System.out.println("Please enter exactly 3 words!");
return;
}
You can do something similar with the second line.
If you want the user to be unable to type more than 3 words, then that's impossible, because this is a command line app.
By the way, the code in the suggested solution works because next() returns the next "word" (or what we generally think of as a word, anyway) by default.
hope this will help you!
public class pratice1 {
public static void main (String[]args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String input1 = sc.nextLine();
char[]a =input.toCharArray();
char[]a1 = input1.toCharArray();
System.out.println(input +""+ input1);
int a2=0;
if(input!=null) {
for(int i=0;i<input.length();i++) {
if(a[i]==' ') {
a2=i;
for(int j=0;j<a2;j++) {
System.out.println(a[i]);
a2=0;
}
}
else System.out.print(a[i]);
}System.out.println("");
for(int i=0;i<input1.length();i++) {
if(a1[i]==' ') {
a2=i;
for(int j=0;j<a2;j++) {
System.out.println(a1[i]);
a2=0;
}
}
else System.out.print(a1[i]);
}
}
}
}
To solve the problem:
Write a program that reads five words from the standard input and
outputs each word in a new line.
This was my solution:
while(scanner.hasNext()){
System.out.println(scanner.next());
}

Hanging Letter Program

I was practicing problems in JAVA for the last few days and I got a problem like this:
I/p: I Am A Good Boy
O/p:
I A A G B
m o o
o y
d
This is my code.
System.out.print("Enter sentence: ");
String s = sc.nextLine();
s+=" ";
String s1="";
for(int i=0;i<s.length();i++)
{
char c = s.charAt(i);
if(c!=32)
{s1+=c;}
else
{
for(int j=0;j<s1.length();j++)
{System.out.println(s1.charAt(j));}
s1="";
}
}
The problem is I am not able to make this design.My output is coming as each character in each line.
First, you need to divide your string with space as a delimiter and store them in an array of strings, you can do this by writing your own code to divide a string into multiple strings, Or you can use an inbuilt function called split()
After you've 'split' your string into array of strings, just iterate through the array of strings as many times as your longest string appears, because that is the last line you want to print ( as understood from the output shared) i.e., d from the string Good, so iterate through the array of strings till you print the last most character in the largest/ longest string, and exit from there.
You need to handle any edge cases while iterating through the array of strings, like the strings that does not have any extra characters left to print, but needs to print spaces for the next string having characters to be in the order of the output.
Following is the piece of code that you may refer, but remember to try the above explained logic before reading further,
import java.io.*;
import java.util.*;
public class MyClass {
public static void main(String args[]) throws IOException{
//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Scanner sc = new Scanner(System.in);
String[] s = sc.nextLine().split(" ");
// Split is a String function that uses regular function to split a string,
// apparently you can strings like a space given above, the regular expression
// for space is \\s or \\s+ for multiple spaces
int max = 0;
for(int i=0;i<s.length;i++) max = Math.max(max,s[i].length()); // Finds the string having maximum length
int count = 0;
while(count<max){ // iterate till the longest string exhausts
for(int i=0;i<s.length;i++){
if(count<s[i].length()) System.out.print(s[i].charAt(count)+" "); // exists print the character
else System.out.print(" "); // Two spaces otherwise
}
System.out.println();count++;
}
}
}
Edit: I am sharing the output below for the string This is a test Input
T i a t I
h s e n
i s p
s t u
t

problems with java toLowerCase function when using arrays and multiple 'words' in the string

I am exceptionally new to java, as in, I can barely write 20 lines of basic code and have them work, level of new, I have 2 issues which may or may not be related as they are from very similar pieces of code that I have personally written.
import java.util.Scanner;
public class StringCW {
public static void main (String [] args) {
String word = "";
while(!(word.equals("stop"))){
Scanner capconversion = new Scanner(System.in);
System.out.println("Enter word:" );
word = capconversion.next();
String lower = word.toLowerCase();
word = lower;
System.out.println("conversion = " + word);
}
System.out.println("ending program");
}
}
}
This is my first chunk of code, it is designed to take any string and convert it into lowercase, however if I am to print anything seperated by a space, eg: "WEWEFRDWSRGdfgdfg DFGDFGDFG" only the first 'word' will be printed and converted, I am also getting a memory leak from cap conversion, though I don't understand what that means or how to fix it
My second problem is likely along the same lines
import java.util.Scanner;
public class splitstring {
private static Scanner capconversion;
public static void main (String [] args) {
String word = "";
while(!(word.equals("stop"))){
capconversion = new Scanner(System.in);
System.out.println("Enter word:" );
word = capconversion.next();
String lower = word.toLowerCase();
String[] parts = lower.split(" ");
parts [0] = "";
parts [1] = "";
parts [2] = "";
parts [3] = "";
parts [4] = "";
System.out.println("conversion = " + lower
parts [0] + parts [1] + parts [2] + parts [3] + parts [4]);
}
System.out.println("ending program");
}
}
this is the 2nd chunk of code and is designed to do the same job as the previous one except print out each 'word' on a new line, then return to the input part until the stop command is entered
the error I get is
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at splitstring.main(splitstring.java:21)
however I don't understand where the error is coming in
This is because you're using Scanner.next(), which returns a single token - and which uses whitespace as a token separator by default.
Perhaps you should use nextLine() instead, if you want to capture a whole line at a time?
As for your ArrayIndexOutOfBoundsException - that has basically the same cause. You're calling split on a single word, so the array returned has only one element (element 0). When you try to set element 1, that's outside the bounds of the array, hence the exception.
Note that nothing in here really has anything to do with toLowerCase().

Beginner with 'nextLine'

I am working on a java problem at the moment where I am creating a program that simulates the old TV quiz show, You Bet Your Life. The game show host, Groucho Marx, chooses a secret word, then chats with the contestants for a while. If either contestant uses the secret word in a sentence, he or she wins $100.00.
My program is meant to check for this secret word.
Here is my code so far:
import java.util.Scanner;
public class Groucho {
String secret;
Groucho(String secret) {
this.secret = secret;
}
public String saysSecret(String line) {
if(secret.equals(line)){
return ("true");
} else {
return ("false");
}
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
}
}
In the main method I need to now create a new Groucho object with a secret word from the first line of standard input (in.nextLine()).
I am not sure how I go about doing this? Can someone explain please!
Thanks!
Miles
Have a look at the Scanner API, and perhaps the Java Tutorial on Objects. And that on Strings.
Learning the basics is usually more useful than just getting a line of code from somewhere.
No offence :).
You can read the line with the following statement:
String line = in.nextLine();
Then, if you'd like to have the first word (for example), you can split the line and create a new Groucho object.
String split = line.split(" ");
Groucho g = new Groucho(split[0]);
Here you can find more information about :
Scanner
String.split()
You would create a new Groucho object and pass in in.nextLine() as a parameter. This would be done by Groucho g = new Groucho( in.nextLine() );
You will need something that looks like this:
Scanner in = new Scanner(System.in); //take in word
String secretWord = in.nextLine(); //put it in a string
Groucho host = new Groucho (secretWord); //create a Groucho object and pass it the word
in.nextLine() will take a single line of the whole input, so you can simply pass it into the constructor.
For example:
String inputWord = in.nextLine();
Groucho g = new Groucho(inputWord);
In the Scanner class the nextLine() method takes the next line of input as a String. You can save that line of input to a String variable:
String line = in.nextLine();
Now that you have a full line of input, you can get the first word from it.
In a sentence each word is separated from other words by a space. In the String class the split() method can split a String into an array of smaller strings, such as words in a sentence, with a given separator, such as a space (" "), that you specify as a parameter:
String[] words = line.split(" ");
Next you can choose a secret word from the array by selecting the appropriate index.
For the first word:
String chosenWord = words[1];
For the last word:
String chosenWord = words[words.length - 1];
For a random word:
String chosenWord = words[Math.floor(Math.random() * words.length)];
Now you can simply pass on the secret word as a parameter to a new Groucho constructor:
Groucho secretWord = new Groucho(chosenWord);
This step by step explanation created a new variable at each step. You can accomplish the same task by combining multiple lines of code into a single statement and avoid creating unnecessary variables.

Categories