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
Related
I have started to learn Java, wrote couple of very easy things, but there is a thing that I don't understand:
public static void main(String[] args) throws java.io.IOException
{
char ch;
do
{
System.out.println("Quess the letter");
ch = (char) System.in.read();
}
while (ch != 'q');
}
Why does the System.out.println prints "Quess the letter" three times after giving a wrong answer. Before giving any answer string is printed only once.
Thanks in advance
Because when you print char and press Enter you produce 3 symbols (on Windows): character, carriage return and line feed:
q\r\n
You can find more details here: http://en.wikipedia.org/wiki/Newline
For your task you may want to use higher level API, e.g. Scanner:
Scanner scanner = new Scanner(System.in);
do {
System.out.println("Guess the letter");
ch = scanner.nextLine().charAt(0);
} while (ch != 'q');
Using System.in directly is probably the wrong thing to do. You'll see that if your character is changed from q to something in Russian, Arabic or Chinese. Reading just one byte is never going to match it. You are just lucky that the bytes read from console in UTF-8 match the character codes for the plain English characters.
The way you are doing it, you are looking at the input as a stream of bytes. And then, as #Sergey Grinev said, you get three characters - the actual character you entered, and the carriage return and line feed that were produce by pressing Enter.
If you want to treat your input as characters, rather than bytes, you should create a BufferedReader or a Scanner backed by System.in. Then you can read a whole line, and it will dispose of the carriage return and linefeed characters for you.
To use a BufferedReader you do something like:
BufferedReader reader = new BufferedReader( InputStreamReader( System.in ) );
And then you can use:
String userInput = reader.readLine();
To use a Scanner, you do something like:
Scanner scanner = new Scanner( System.in );
And then you can use:
String userInput = scanner.nextLine();
In both cases, the result is a String, not a char, so you should be careful - don't compare it using == but using equals(). Or make sure its length is greater than 1 and take its first character using charAt(0).
As has been mentioned, the initial read command takes in 3 characters and holds them in the buffer.
The next time a read command comes around, it first checks the buffer before waiting for a keyboard input. Try entering more than one letter before hitting enter- your method should get called however many characters you entered + 2.
For an even simpler fix:
//add char 'ignore' variable to the char declaration
char ch ignore;
//add this do while loop after the "ch = (char) System.in.read();" line
do{
ignore = (char) System.in.read();
} while (ignore != '\n');
this way 'ignore' will cycle through the buffer until it hits the newline character in the buffer (the last one entered via pressing enter in Windows) leaving you with an fresh buffer when the method is called again.
I am trying to write a method that prints out whatever character the user is entering character by character appended with the previous ones as he enters and throws an exception when he presses enter. I have written the following code but when i enter, it appends what ever character I have written and does not throw an exception. I would appreciate your help and suggestion.
public static void inputM(StringBuffer a) throws EntExc, IOException{
char c;
String m;
while(true){
Scanner s = new Scanner(System.in);
m=s.next();
c=m.charAt(0);
if(c=='\r'){
throw new EntExc();
}
System.out.println(a.append(m));
}
}
There are a few issues here. First s.next() grabs a whitespace-delimited token and returns the entire token as a single string. Second, because Scanner uses whitespace as a delimiter, it will never return \r, it will just skip it and read the next token.
Why not use s.readLine() and simply echo the whole line? While it won't process characters as they are entered (Scanner can't really do this, it always buffers lines), it will be closer to your described requirement.
I'm convinced this is a product of how the string.replaceAll() method works, but for some odd reason its making my loop run twice when you type anything with a space in it?
public class TestCode{
public static void main(String[] args) throws IOException{
Scanner scan = new Scanner(System.in);
String input = "";
while(!input.equals("X")){
System.out.println("Prompt user for input");
input = scan.next().toUpperCase();
calculatePolynomial(input);
}
}
public static void calculatePolynomial(String input){
//Clean up entry removing spaces and extracting polynomial names
String calculation = input.replaceAll("\\s", "");
System.out.println(calculation);
}
}
The idea was to have the code run... printing out the message, prompting input. Then process the input and do some stuff. Repeat the process over and over until the sentinel value 'x' is entered.
But when you type input that contains a space it, for some reason, runs the loop as if each word was now separate input. So if you enter three words, it just runs the loop three times instead of once.
I just want the user's input to be without spaces and without a nightmare of logical errors.
When using a Scanner, by default, next() tokenizes the input by whitespace. So if the user enters two words separated by whitespace, your loop will run twice.
To get the entire input in the user's input line, try using the nextLine() method instead.
Im working right now on a program that can divide, add, ect, but, im also making it for others, so, the problems usually have letters as well. What code could I implement so that my program ignores characters, and just focuses on numbers?
import static java.lang.System.out;
import java.util.Scanner;
public class Trinomial {
public static void main(final String args[]) {
final Scanner first = new Scanner(System.in);
out.print("Enter the first number: ");
final int First = first.nextInt();
final Scanner second = new Scanner(System.in);
out.print("Enter the second number: ");
final int Second = second.nextInt();
final Scanner third = new Scanner(System.in);
out.print("Enter the third number: ");
final int Third = third.nextInt();
numFactors(First);
}
}
You can have your program check whether each character it looks at is a digit using Character.isDigit()
http://www.tutorialspoint.com/java/character_isdigit.htm
You probably also want to allow your math operators through, e.g.
if (Character.isDigit(input) || input == '+' ||
input == '-' || input == '/' || input == '*')
{
// Do something with input
}
If that's not what you're looking for, please improve your question to be more specific.
Firstly, you will have to use next() method from the scanner, as nextInt() will return an exception if the next token contains non-digit characters. This will read the token as a String. Then you can get rid of non-digit characters by, for example, creating an empty String (for performance reasons StringBuilder can be better, but that makes it more complex), looping through the original string and using the already mentioned isDigit() method to determine whether the character is a digit. If it is, add it to your new string. Once you have a string containing only digits, use Integer.parseInt(string) method to get the integer value.
I am not quite sure, why you initialise a new Scanner every time, I think you should be able to use the first one throughout your program.
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.