Java String - How to get chars until and after space - java

I'm load to variable string using:
Scanner scanner = new Scanner(System.in);
x = scanner.nextLine();
String always looks like: "Random Example". I want to grab first word (before space) for one variable and second word (after space) to next one variable. Can someone show me example?

You can get split a String using .split(String s) and put it in a String[]
String editMe;
Scanner user_input = new Scanner( System.in );
editMe = user_input.nextLine();
String[] edit1 = editMe.split(" ");
If you would like to see the values in the System you can use
int i =0;
for(String s:edit1)
{
System.out.println(s);
i++;
}
See more information on the String variable and how to use it here.

Input obtained from scanning the input stream can be split based on the space character.
Scanner scanner = new Scanner(System.in);
String x = scanner.nextLine();
String array[] =x.split(" ");
In this way, the words are stored in array.

Related

How to skip whitespaces and take input in Single line using Scanner

I need to take input in a single line of String which is a combination of String and integers.
I have tried to take the input like this
Scanner in = new Scanner(System.in);
String stringWithoutSpaces=in.nextLine();
But, scanner reads only the first character.
Input String:A 10,B 10,C 10,D 10
Required String:A10,B10,C10,D10
I need this input in a one single line using scanner class.
From what I understand, you are trying to receive the string from the user without storing all the white spaces. If your goal is to remove all the white spaces from the user input string, you can use replaceAll.
Code:
Scanner in = new Scanner(System.in);
System.out.print("Enter input: ");
String input = in.nextLine();
String noWhiteSpaces = input.replaceAll(" ", "");
System.out.println(noWhiteSpaces);
Console:
Enter input: A 10,B 10,C 10,D 10
A10,B10,C10,D10
import java.util.*;
public class Solution {
public static void main(String args[]) {
System.out.println("Hello world");
Scanner scanner=new Scanner(System.in);
String aItems = scanner.nextLine();
System.out.println(aItems);
}
}
This is working fine. I have Provided same input as mentioned by you and it is taking it as one string.Share your complete code or match from this one.

countTokens() always returns 1 with user input

Before we begin, I don't believe this is a repeat question. I've read the question entitled StringTokenzer countTokens() returns 1 with any string, but that does not address the fact that a properly delimited string is counted correctly, but a properly delimited input is not.
When using the StringTokenizer class I've found that the countTokens method returns different outcomes depending on the whether the argument in countTokens was a defined String or a user defined String. For example, the following code prints the value 4.
String phrase = "Alpha bRaVo Charlie delta";
StringTokenizer token = new StringTokenizer(phrase);
//There's no need to specify the delimiter in the parameters, but I've tried
//both code examples with " " as the delimiter with identical results
int count = token.countTokens();
System.out.println(count);
But this code will print the value 1 when the user enters:Alpha bRaVo Charlie delta
Scanner in = new Scanner(System.in);
String phrase;
System.out.print("Enter a phrase: ");
phrase = in.next();
StringTokenizer token = new StringTokenizer(phrase);
int count = token.countTokens();
System.out.println(count);
Use in.nextLine() instead of in.next();
Scanner in = new Scanner(System.in);
String phrase;
System.out.print("Enter a phrase: ");
phrase = in.nextLine();
System.out.print(phrase);
StringTokenizer token = new StringTokenizer(phrase);
int count = token.countTokens();
System.out.println(count);
Print phrase and check that in.next() is returning "Alpha".
As suggested above, Use in.nextLine().
You could try using an InputStreamReader, instead of the Scanner:
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String phrase = "";
System.out.print("Enter a phrase: ");
try {
phrase = in.readLine();
} catch (IOException e) {
e.printStackTrace();
}
StringTokenizer token = new StringTokenizer(phrase);
int count = token.countTokens();
System.out.println(count);
nextLine() of Scanner also got the job done for me, though.
If you want the delimiter to be a space-character specifically, you might want to pass it to the constructor of StringTokenizer. It will use " \t\n\r\f" otherwise (which includes the space-character, but might not work as expected if e.g. the \n-character is also present inside the phrase).
If you check the value of phrase, after invoking in.next(), you will see that's equal to "Alpha". By definition, Scanner's next() reads the next token.
Use in.nextLine() instead.

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.

How to input a specific number of words in java?

I'm supposed to input an array of strings in java according to the following specification:
Input:A text containing K English words (where K <= 5000), with spaces and punctuation marks
My approach is to use an array of strings, each string containing a word and taking input using java.util.Scanner.next() inside a loop.
My problem is how to stop taking inputs when the user hits enter. Any idea?
Use a Scanner. Read the lines that the user enters. If the user enters an empty line then exit the loop:
public static void main(String[] args) throws Exception {
final Scanner scanner = new Scanner(System.in);
while (true) {
final String read = scanner.nextLine();
if ("".equals(read)) {
break;
}
System.out.println(read);
}
}
You could use two Scanner objects to handle this like so:
Scanner inScan = new Scanner(System.in);
String line = sinScan.nextLine();
while (line.length() > 0) {
Scanner lineScan = new Scanner(line);
while(lineScan.hasNext()) {
String word = lineScan.next();
// process this word.
}
line = inScan.nextLine();
}
// loop should exit when the user enters a blank line.

Storeing a users input as a string in JAVA

Firstly I am very new to JAVA, so I apoligise if I am not quick to pickup on something.
In the example below how could I store the user's input to a string as well as return it?
Scanner inputme = new Scanner(System.in);
System.out.println(inputme.nextLine());
I was thinking something along the lines of:
inputme.WritetoString(thestringname);
Simply use an intermediate variable:
Scanner inputme = new Scanner(System.in);
String line = inputme.nextLine();
// Do whatever in between
System.out.println(line);
Then the line variable is a String containing... the line :)

Categories