I am trying to make program that have a different behavior when the user inputs certain arguments to a String that is received by the program through a Scanner. My problem is the fact that i want to make it as if the user doesn't write the 2nd argument for example, the program should still work.
static String ReadString() {
Scanner scan = new Scanner(System.in);
return scan.nextLine();
}
String command = ReadString();
String words[]=new String[4];
words[0]="empty";
words[1]="empty";
words[2]="empty";
words[3]="empty";
words = command.split(" ");
The problem is that if I am calling for example words[1] after the user has written only one argument to that string, I still get the error ArrayOutOfBounds, although there should be an string with the value "empty".
Example:
User writes : ababbbbb command1 >>> when I call words[1] it should give me command1
User writes : ababbbbb >>> when I call words[1] it should give me empty
Because, when you wrote below code that means words which is Array of String type is pointing to reference, which is allocated memory to hold 4 string.
String words[]=new String[4];
Now, below line of code where you are creating Array by spliting them by " " has only size 1. Now, words variable reference has changed and it can only hold 1 String.
words = command.split(" ");
You need to make following correction :
String command = ReadString();
String words[]=new String[4];
String[] n = command.split(" ");
for(int i=0; i< 4; i++)
{
if((n.length-1)==i)
{
words[i]=n[i];
}
else
{
words[i]="empty";
}
}
>>>Demo<<<
Related
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().
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.
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.
In Java, How can I store a string in an array? For example:
//pseudocode:
name = ayo
string index [1] = a
string index [2] = y
string index [3] = o
Then how can I get the length of the string?
// this code doesn't work
String[] timestamp = new String[40]; String name;
System.out.println("Pls enter a name and surname");
Scanner sc = new Scanner(System.in);
name = sc.nextLine();
name=timestamp.substring(0, 20);
If you want a char array to hold each character of the string at every (or almost every index), then you could do this:
char[] tmp = new char[length];
for (int i = 0; i < length; i++) {
tmp[i] = name.charAt(i);
}
Where length is from 0 to name.length.
This code doesn't compile because the substring method can only be called on a String, not a String array if I'm not mistaken. In the code above, timestamp is declared as a String array with 40 indexes.
Also in this code, you're asking for input from a user and assigning it to name in this line:
name = sc.nextLine();
and then you are trying to replace what the user just typed with what is stored in timestamp on the next line which is nothing, and would erase whatever was stored in name:
name = timestamp.substring(0,20);
And again that wouldn't work anyway because timestamp is an array of 40 strings instead of one specific string. In order to call substring it has to be just one specific string.
I know that probably doesn't help much with what you're trying to do, but hopefully it helps you understand why this isn't working.
If you can reply with what you're trying to do with a specific example I can help direct you further. For example, let's say you wanted a user to type their name, "John Smith" and then you wanted to seperate that into a first and last name in two different String variables or a String array. The more specific you can be with what you want to do the better. Good luck :)
BEGIN EDIT
Ok here are a few things you might want to try if I understand what you're doing correctly.
//Since each index will only be holding one character,
//it makes sense to use char array instead of a string array.
//This next line creates a char array with 40 empty indexes.
char[] timestamp = new char[40];
//The variable name to store user input as a string.
String name;
//message to user to input name
System.out.println("Pls enter a name and surname");
//Create a scanner to get input from keyboard, and store user input in the name variable
Scanner sc = new Scanner(System.in);
name = sc.nextLine();
//if you wanted the length of the char array to be the same
//as the characters in name, it would make more sense to declare it here like this
//instead of declaring it above.
char[] timestamp = new char[name.length()];
//For loop, loops through each character in the string and stores in
//indexes of timestamp char array.
for(int i=0; i<name.length;i++)
{
timestamp[i] = name.charAt(i);
}
The other thing you could do if you wanted to just seperate the first and last name would be to split it like this.
String[] seperateName = name.split(" ");
That line will split the string when it finds a space and put it in the index in the seperateName array. So if name was "John Smith", sperateName[0] = John and seperateName[1] = Smith.
Are you looking for a char[]? You can convert a character array to a String using String.copyValueOf(char[]).
Java, substring an array:
Use Arrays.copyOfRange:
public static <T> T[] copyOfRange(T[] original,
int from,
int to)
For example:
import java.util.*;
public class Main{
public static void main(String args[]){
String[] words = new String[3];
words[0] = "rico";
words[1] = "skipper";
words[2] = "kowalski";
for(String word : words){
System.out.println(word);
}
System.out.println("---");
words = Arrays.copyOfRange(words, 1, words.length);
for(String word : words){
System.out.println(word);
}
}
}
Prints:
rico
skipper
kowalski
---
skipper
kowalski
Another stackoverflow post going into more details:
https://stackoverflow.com/a/6597591/445131
I have just started the java programming and at the moment I am doing the basic things. I came across a problem that I can't solve and didn't found any answers around so I thought you might give me a hand. I want to write a program to prompt the user to enter their full name (first name, second name and surname) and output their initials.
Assuming that the user always types three names and does not include any unnecessary spaces. So the input data will always look like this : Name Middlename Surname
Some of my code that I have done and stuck in there as I get number of the letter that is in the code instead of letter itself.
import java.util.*;
public class Initials
{
public static void main (String[] args)
{
//create Scanner to read in data
Scanner myKeyboard = new Scanner(System.in);
//prompt user for input – use print to leave cursor on line
System.out.print("Please enter Your full Name , Middle name And Surname: ");
String name = myKeyboard.nextLine();
String initials1 = name.substring(0, 1);
int initials2 = name.
//output Initials
System.out.println ("Initials Are " + initials1 + initials2 + initials3);
}
}
Users will enter a string like
"first middle last"
so therefore you need to get each word from the string.
Loot at split.
After you get each word of the user-entered data, you need to use a loop to get the first letter of each part of the name.
First, the nextLine Function will return the full name. First, you need to .split() the string name on a space, perhaps. This requires a correctly formatted string from the user, but I wouldn't worry about that yet.
Once you split the string, it returns an array of strings. If the user put them in correectly, you can do a for loop on the array.
StringBuilder builder = new StringBuilder(3);
for(int i = 0; i < splitStringArray.length; i++)
{
builder.append(splitStringArray[i].substring(0,1));
}
System.out.println("Initials Are " + builder.toString());
Use the String split() method. This allows you to split a String using a certain regex (for example, spliting a String by the space character). The returned value is an array holding each of the split values. See the documentation for the method.
Scanner myKeyboard = new Scanner(System.in);
System.out.print("Please enter Your full Name , Middle name And Surname: ");
String name = myKeyboard.nextLine();
String[] nameParts = name.split(" ");
char firstInitial = nameParts[0].charAt(0);
char middleInitial = nameParts[1].charAt(0);
char lastInitial = nameParts[2].charAt(0);
System.out.println ("Initials Are " + firstInitial + middleInitial + lastInitial);
Note that the above assumes the user has entered the right number of names. You'll need to do some catching or checking if you need to safeguard against the users doing "weird" things.