I need to parse an input-line character by character, and this will be done through several methods. To do it char by char, I am using useDelimiter(""). My question is: do i need to set this delimiter in every method? Or is it enough once, at the beginning?
e.g.
void start() {
Scanner in = new Scanner(System.in);
in.useDelimiter("");
char first = in.next();
readSecond(in);
...
}
void readSecond(Scanner in) {
//in.useDelimiter(""); <-- is this needed?
char second = in.next();
...
}
Example input: A5c*vd
Thanks !
You wouldn't have to set it every time if you declare and initialize the Scanner object in the class body that the methods are in. If you initialize the Scanner in each method, then I think you would have to set the delimiter in each method body.
Once set, the delimiter stays the same.
Therefore, you do not need to set it again to the same value.
Related
New to programming, so my apologies if this is dumb question.
When utilizing the Scanner class, I fail to see if there is an option for obtaining a single character as input. For example,
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String a = input.nextLine();
}
}
The above code allows me to pull the next line into a string, which can then be validated by using a while or if statement using a.length() != 1 and then stored into a character if needed.
But is there a way to pull a single character instead of utilizing a string and then validating? If not, can someone explain why this is not allowed? I think it may be due to classes or objects vs primitive types, but am unsure.
You can use System.in.read() instead of Scanner
char input = (char) System.in.read();
You can also use Scanner, doing something like:
Scanner scanner = new Scanner(System.in);
char input = scanner.next().charAt(0);
For using Stringinstead of char, you can also to convert to String:
Scanner scanner = new Scanner(System.in);
String input = String.valueOf(input.next().charAt(0));
This is less fancy than other ways, but for a newbie, it'll be easier to understand. On the other hand, I think the problem proposed doesn't need amazing performance.
Set the delimiter so every character is a token:
Scanner input = new Scanner(System.in).useDelimiter("(?<=.)");
String c = input.next(); // one char
The regex (?<=.) is a look behind, which has zero width, that matches after every character.
I have a question based on character arrays. At the moment I have an input variable that takes the first letter of the word.
char input = scanner.nextLine().charAt(0);
What I want to do is for every enter, I want to put it in an array so that I can keep a log of all the letters that have been retrievied. I am assuming this is using char[] but I am having trouble implementing added each input into the array.
char input = scanner.nextLine().charAt(0);
First thing that's unclear is what Object type is scanner?
But for now I'll assume scanner is the Scanner object from Java.util.Scanner
If that's the case scanner.nextLine() actually returns a String.
String has a charAt() method that will allow you to pick out a character anywhere in the string.
However scanner.nextLine() is getting the entire line, not just one word. So really scanner.nextLine().charAt(0) is getting the first character in the line.
scanner.next() will give you the next word in the line.
If the line contained "Hello World"
scanner.next().charAt(0) would return the character 'H'.
the next call of scanner.next().charAt(0) would then return the character 'W'
public static void main(String[] args) {
boolean finished = false;
ArrayList<Character> firstLetters = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
while (!finished) {
firstLetters.add(scanner.next().charAt(0));
}
}
The above code sample might give you the behavior you're looking for.
Please note that the while loop will run forever until finished becomes true.
Your program will have to decide when to set finished to true.
AND here's a couple of links about Java's Scanner class
tutorials point
Java Docs
Print the prompt "Character: " then use the Scanner object to read a string from the keyboard into a temporary variable that you must declare. Next extract the first character of the temporary string into myCharacter.
(Scanner is already initialized)
This is what I have so far but I don't understand what the question is asking.
char myCharacter;
char myCharacter1;
Scanner kbd = new Scanner(System.in);
System.out.println("Character: ");
myCharacter1 = kbd.next().charAt(0);
Your code looks like it's doing what you were asked. The question is asking you to read in a string from user input and get the first character out of the string, which is this part of your code:
myCharacter1 = kbd.next().charAt(0);
As far as I can tell, it only cares about having the temporary string variable only so you can grab the first character out of it and store it in to your myCharacter1 variable. It might just be that it's trying to illustrate the idea that strings are an array of characters? I hope that helps!
-Frank
EDIT:
You had a comment that you weren't reading the string into a temporary string variable. That's an important step from your question. As far as I know, your code should work fine, but if this is a homework problem for a class your professor will likely deduct points for not reading into a String variable first.
// Scanner declaration and initialization.
Scanner scanner = new Scanner(System.in);
// 1. Prompting 'Character: '
System.out.print("Character: ");
// 2. Temporary variable declaration and initialization.
String tempVar = scanner.next();
// 3. Extraction of the first character of the temporary variable into char variable
char myCharacter = tempVar.charAt(0);
In Java's Scanner class, why does the syntax nextChar() not exist, and is there a command would do something similar with out using the String variable?
Two solutions:
use toCharArray(): this will return a char[] over which you can use a foreach loop;
use the string length in combination with .charAt().
Java's Scanner class operates on tokens, complete units of output. This is usually complete words, lines of text, numbers (integers, doubles, floats, etc). If you want to read individual characters, you should use BufferedReader in a construct like this
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Replacing System.in with whatever input you're using for Scanner. Then use char c = (char)in.read() to read the next character from the input.
If you want char level access you can go a level below and simply use the InputStream interface :
public class Test
{
public static void main(String[] args) throws Exception
{
while (true)
{
char c = (char)System.in.read();
System.out.println("[" + c + "]");
}
}
}
Scanner s = new Scanner(System.in);
s.next(“.{1,}”);
So, you can use Scanner#next() method and pass regular expression which consumes only one char as a parameter.
You can use an example above.
The problem is I cant read the variable input with next() cause when I try to split (.split" ") every whitespace then the array just get the first two words I type so I had to use keyboard.nextLine() and the splitting process works the way it should work and I get all the words in the array but the problem is that If I use nextLine() then I have to create another keyboard object to read the first variable (answer) and that is the only way I can make it work here is the code
Scanner keyboard=new Scanner(System.in);
Scanner keyboard2=new Scanner(System.in);//just to make answer word
int answer=keyboard.nextInt();//if I don't use the keyboard2 here then the program will not work as it should work, but if I use next() instead of nextLine down there this will not be a problem but then the splitting part is a problem(this variable counts number of lines the program will have).
int current=1;
int left=0,right=0,forward=0,back=0;
for(int count=0;count<answer;count++,current++)
{
String input=keyboard.nextLine();
String array[]=input.split(" ");
for (int counter=0;counter<array.length;counter++)
{
if (array[counter].equalsIgnoreCase("left"))
{
left++;
}
else if (array[counter].equalsIgnoreCase("right"))
{
right++;
}
else if (array[counter].equalsIgnoreCase("forward"))
{
forward++;
}
else if (array[counter].equalsIgnoreCase("back"))
{
back++;
}
}
}
}
Thanks :)
Put keyboard.nextLine() after this line:
int answer=keyboard.nextInt();
This is a common problem that usually happens when you use nextLine() method after nextInt() method of Scanner class.
What actually happens is that when the user enters an integer at int answer = keyboard.nextInt();, the scanner will take the digits only and leave the new-line character \n. So you need to do a trick by calling keyboard.nextLine(); just to discard that new-line character and then you can call String input = keyboard.nextLine(); without any problem.