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 :)
Related
I'm trying to progress displaying a file line by line with an Enter key, but the if statement that I try doesn't seem to work. If I disregard the if statement, it works, but it feels incomplete because then I'm asking for input and doing nothing with it.
This is what I have:
import java.util.Scanner;
import java.io.*;
public class LineByLine {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
System.out.println("What is the filename?");
String input = in.nextLine();
BufferedReader buff = new BufferedReader(new FileReader(input));
String sen = buff.readLine();
System.out.println(sen);
Scanner enter = new Scanner(System.in);
while (sen != null){
String output = enter.next();
if (output.equals("")){
System.out.println(sen = buff.readLine());
}
}
}
}
I just don't know why my if statement doesn't work.
The core issue is that you misunderstand Scanner and its default configuration: Out of the box, scanner splits on any amount of whitespace. .next() asks for the next token; a token is the thing that appears in between the whitespace.
Thus, pressing enter 500 times produces zero tokens. After all, tokens are what's in between the separator, and the default separator is 'any amount of whitespace'. Pressing enter a bunch of time is still just you entering the same separator.
The underlying problem is that most people appear to assume that Scanner reads one line at a time. It doesn't do that. At all. But you want it to. So, tell it to! Easy peasy - make scanner do what you already thought it did:
Scanner in = new Scanner(System.in);
in.useDelimiter("\\R"); // a single enter press is now the separator.
You should also stop using nextLine on scanners. nextLine and any other next call do not mix. The easiest way to solve this problem is to only ever use nextLine and nothing else, or, never use nextLine. With the above setup, .next() gets you a token which is an entire line - thus, no need for nextLine, which is good news, as nextLine is broken (it does what the spec says it should, but what it does is counterintuitive. We can debate semantics on whether 'broken' is a fair description of it. Point is, it doesn't do what you think it does).
Also, while you're at it, don't make multiple scanners. And, to improve this code, resources must be properly closed. You're not doing that. Let's use try-with, that's what it is for.
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
in.useDelimiter("\\R");
System.out.println("What is the filename?");
String input = in.next();
try (BufferedReader buff = new BufferedReader(new FileReader(input))) {
String sen = buff.readLine();
System.out.println(sen);
while (sen != null){
enter.next(); // why does it matter _what_ they entered?
// as long as they pressed it, we're good, right? Just ignore what it returns.
System.out.println(sen = buff.readLine());
}
}
}
I am trying to learn Java and was specifically learning about User Input using Scanner class.
I was wondering if you can add something like a ':' or ';' after a prompt.
My understanding is somewhat like this
Scanner var1 = new Scanner(System.in); //Creates a new object of scanner class
String var2 = var1.next(); //Stores input in a string variable
So what should be the way to put a ":" after the prompt, in the same line?
You can create a prompt on the same line as the user input by using System.out.print(prompt)
Note that this is not the same as System.out.println(prompt), which puts a newline after the string to be printed.
Example:
System.out.print("Enter your value: ");
String value = myScanner.next();
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.
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.
I encounter some problem when using useDelimiter from the Scanner class.
Scanner sc = new Scanner(System.in).useDelimiter("-");
while(sc.hasNext())
{
System.out.println(sc.next());
}
if I have this input
A-B-C
the output will be
A B
and wait until I type in another "-" for it to print out the last character
However if I instead of having user input data, and insert a String to the Scanner instead the code will work. What's the reason for it, and how do I fix it? I don't want to use StringTokenzier
If the Scanner didn't wait for you to enter another - then it would erroneously assume that you were done typing input.
What I mean is, the Scanner must wait for you to enter a - because it has no way to know the length of the next input.
So, if a user wanted to type A-B-CDE and you stopped to take a sip of coffee at C, it woud not get the correct input. (You expect [ A, B, CDE ] but it would get [ A, B, C ])
When you pass it in a full String, Scanner knows where the end of the input is, and doesn't need to wait for another delimiter.
How I would do it follows:
Scanner stdin = new Scanner(System.in);
String input = stdin.nextLine();
String[] splitInput = input.split("-", -1);
You will now have an array of Strings that contain the data between all of the -s.
Here is a link to the String.split() documentation for your reading pleasure.
You could use an alternative delimiter string useDelimiter( "-|\n" );
It works with a String argument as well as by reading from System.in.
In case of System.in this requires you to press enter at the end of the line.
How I would do it follows:
Scanner stdin = new Scanner(System.in);
String s = stdin.nextLine();
String[] splitInput = s.split("-", -1);
You will now have an array of Strings that contain the data between all of the -s.