Using eclipse btw.
Why does this:
public class charCounter {
public static void main(String[] args)
throws java.io.IOException {
char entry;
int count;
for (count = 0;;){
System.out.println("Press \" . \" to exit.");
entry = (char) System.in.read();
if (entry != '.')
count++;
else break;
}
System.out.println("Number of entries: " + count);
}
}
result in 3x the amount of "count" as it should be? That is when I enter a, b, and c, for example, and then press '.', it says "Number of entries: 12"
I'm reading through "Java, A Beginner's Guide" and I don't understand what I did wrong? I'm new but not stupid so I don't see the logic behind this. Is it simply a bug or too fast of a mechanic behind the for loop to be used for such short code?
It's a bug in your code. When you push <enter> you are actually inserting special (invisible) characters \r\n (also known as carriage return and newline). This is why every time you push enter you get extra characters.
You effectively have the input (spaces added for clarity only):
a \r \n b \r \n c \r \n . \r \n
even though your console looks like:
a
b
c
.
System.in.read reads one character at a time, so your loop will actually execute thrice for the sequence a\r\n, once for a and once for \r and once for \n.
I made a program using JavaFX where I have to paste into an excel like table.
I followed some tutorials online but noticed strange behavior in the way the paste code functions. After a while, I isolated the problem to the following code.
public void handlePaste() {
Clipboard clipboard = Clipboard.getSystemClipboard();
if (clipboard.hasString()) {
//start from the point that has focus
// abort if there's not cell selected to start with
if (getSelectionModel().getSelectedCells().size() == 0) {
return;
}
// get the cell position to start with
TablePosition pasteCellPosition = getFocusModel().getFocusedCell();
String pasteString = Clipboard.getSystemClipboard().getString();
int rowClipboard = -1;
Iterable<String> rowStrings = Splitter.on("\n").omitEmptyStrings().split(pasteString);
System.out.println("Print Rows");
for (String rowString : rowStrings) {
System.out.println(rowString);
System.out.println(rowString + " printing again");
}
for (String rowString : rowStrings) {
rowClipboard++;
Iterable<String> columnStrings = Splitter.on("\t").split(rowString);
int colClipboard = -1;
System.out.println("Printing Columns");
for (String columnString : columnStrings) {
System.out.println(columnString);
System.out.println(columnString + " printing again");
}
}
}
}
I use the output statement to demonstrate the problem.
Basically, I'm splitting the contents of the string based off and '\n' and '\t' characters.
The problem is whenever I try to do anything with the split strings, the string just...DISAPPEARS...
The output statements I put in demonstrate this.
Suppose the string on the clipboard is
l a
l b
l c
Then the expected output should be
Print rows
l a
l a printing again
l b
l b printing again
r c
r c printing again
Printing Columns
l
l again
a
a again
l
l again
b
b again
r
r again
c
c again
But the output ends up being
Print rows
l a
printing again
l b
printing again
r c
printing again
Printing Columns
l
again
a
again
l
again
b
again
r
again
c
again
Notice how when I try to append " printing again" to the split string, I'm simply getting blank strings.
I tried fixing the issue by using substring, and by using the standard java string splitting methods and I got the same behavior.
Finally, to fix it, I just used the java.awt Clipboard instead of the JavaFX clipboard and suddenly...it worked!
java.awt.Toolkit toolkit = java.awt.Toolkit.getDefaultToolkit();
java.awt.datatransfer.Clipboard awtClipboard = toolkit.getSystemClipboard();
try {
pasteString = (String) awtClipboard.getData(java.awt.datatransfer.DataFlavor.stringFlavor);
} catch (UnsupportedFlavorException ex) {
} catch (IOException ex) {
}
Using the above line of code to get the pasteString instead of the JavaFX clipboard fixed the problem, and now I get the expected behavior and output.
For now, I will stick with the above fix, but it seems strange that the JavaFX clipboard is producing this behavior when the awt clipboard does not. Can anybody explain why this is happening? Is this a bug with the JavaFX clipboard?
LuxxMiner's comment above appears to offer a solution.
Using System.lineSeparator() also seems to work fine.
Unfortunately I found the above solutions didn't quite work out for me. The problem is that while the system seperator does get me the seperator for my systems, when I copy and paste from another program, it isn't guaranteed that the program I'm copying from is using the systems' seperator. For instance, when I copied from an excel spreadsheet, I kept getting the same strange behavior I got before, and I believe it was because excel didn't use the systems seperator.
So this is the solution I eventually came upon...
Basically it looks for ANY of the basic line seperators and splits on them.
import com.google.common.base.CharMatcher;
import com.google.common.base.Splitter;
Iterable<String> rowStrings = Splitter.on(CharMatcher.anyOf("\n\r")).omitEmptyStrings().split(pasteString);
I'm trying to make a piece of code that will yell out anything I input.
So the command is 'yell'
I want to be able to type 'yell (whatever i want here)' and it will yell it out. I've managed to get this working with a help of a friend. But for some reason it will only yell the first word that's been output. So I can't type a sentence because it will only say the first word of a sentence.
Here's the piece of code, I hope you can help.
case "npcyell":
for (NPC n : World.getNPCs()) {
if (n != null && Utils.getDistance(player, n) < 9) {
String sentence = "";
for (int i = 1; i < cmd.length; i++) {
sentence = sentence + " " + cmd[i];
}
n.setNextForceTalk(new ForceTalk("[Alert] "
+ Utils.getFormatedMessage(sentence)));
}
}
return true;
Well I did something similar a while ago. You said that you wanted to be able to say "yell(text)" and have it output whatever the text was. I have a different way of implementing it than you do, but the general result is the same, but it can be adapted to however you are using it in this context. This is also assuming that you are running this program as a console project only. if not change the scanner with whatever you are using to input text into and replace the text assignment to text = textInputArea.getText().toString(); and change the output statement to System.out.println(text.getText().toString().substring(6,text.getText().toString().length() - 1));
Scanner s = new Scanner(System.in);
String text = s.nextLine();
if (text.startsWith("yell(") && text.endsWith(")")){
System.out.println(text.substring(6,text.length() - 1));
}
I hope this works for you. And I honestly hope that this is adaptable towards the program you are making.
In the below example , I am trying accept single character input from user, but when running the program, I get do..while loop executed multiple times. Please see the result of the program below.
If some one could help me with the answer, how to fix this problem?
import java.io.*;
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
char c;
// BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
DataInputStream in =new DataInputStream(System.in);
// Asking the user what to do with the application
do{
System.out.println("Would you like to access your account, if yes,type 'Y' or if you want to create a new account press 'N'to exit press 'E' ");
byte b = in.readByte();
c = (char) b;
c = Character.toUpperCase(c);
if (c=='Y'){
System.out.println(c);
}
else if (c=='N') {
System.out.println(c);
}
else if (c=='E'){
System.out.println(c);
}
else{
System.out.println("Incorrect Entry, try again: "+c);
}
}while (c!='E');
}
}
Output
init:
deps-jar:
compile:
run:
Would you like to access your account, if yes,type 'Y' or if you want to create a new account press 'N'to exit press 'E'
asdfgaf
Incorrect Entry, try again: A
Would you like to access your account, if yes,type 'Y' or if you want to create a new account press 'N'to exit press 'E'
Incorrect Entry, try again: S
Would you like to access your account, if yes,type 'Y' or if you want to create a new account press 'N'to exit press 'E'
Incorrect Entry, try again: D
Would you like to access your account, if yes,type 'Y' or if you want to create a new account press 'N'to exit press 'E'
Incorrect Entry, try again: F
Would you like to access your account, if yes,type 'Y' or if you want to create a new account press 'N'to exit press 'E'
Incorrect Entry, try again: G
Would you like to access your account, if yes,type 'Y' or if you want to create a new account press 'N'to exit press 'E'
Incorrect Entry, try again: A
Would you like to access your account, if yes,type 'Y' or if you want to create a new account press 'N'to exit press 'E'
Incorrect Entry, try again: F
Would you like to access your account, if yes,type 'Y' or if you want to create a new account press 'N'to exit press 'E'
Incorrect Entry, try again:
Would you like to access your account, if yes,type 'Y' or if you want to create a new account press 'N'to exit press 'E'
Using DataInputStream isn't probably the best way to handle your situation.
DataInputStream buffers the inputs that you typed, which is why you get unwanted lengthy messages with loops.
Try using Scanner instead.
Here's an example of Scanner:
Scanner objScanner = new Scanner(System.in);
char c = objScanner.next().charAt(0);
System.out.println(c);
Use System.in.read() instead of DataInputStream.
DataInputStream (InputStream) is fundamentally a binary construct. If you want to read text data (e.g. from the console) you should use a Reader. In the source code There was a commented out BufferedReader. Its better to use the same instead of DataInputStream. You can do as below,
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String input = in.readLine();
Or you can use DataInputStream.readLine(), but its deprecated for a reason. And its suggested there also to use BufferedReader.readLine().
You can go for other options like Scanner.
User Scanner class for getting input. Its good way to resolve your issue.
Scanner scan = new Scanner(System.in);
System.out.println(scan.next().charAt(0));
Since this thread has no ACCEPTED ANSWER yet, I'm still going to answer even though its really old; for the people who still want a explanation.
Using a Scanner are the best idea for the situation.
Scanners are easy to use, and stop the thread until completion. You can use this to your advantage, or you can create a new thread to keep the current thread running.
The basic usage of a scanner:
Scanner s = new Scanner(System.in) //Makes a new scanner with System.in
String letter = s.next(); //Use next to find the character typed
//Insert code using letter variable
"letter" will return EVERYTHING before a space in the scanner. To only find the first letter, split the string by "" then take the 1st (0th) of the array.
Lastly, a good quote taken from this thread about scanners
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.
Later, when looking for multiple words, use nextLine() instead of next() to get the full String
Probably in above execution example you gave input as "asdfgaf" and then pressed enter.
hence it is taking A, S, D, F .... as input one character at a time.
you should give input as 'y' or 'n' or 'e' (single character at a time) and then press Enter.
e.g
Would you like to access your account, if yes,type 'Y' or if you want to create a new account press 'N'to exit press 'E' :
y
I have a problem with typing in Robot Class. I want the robot to type something the
user has entered. The robot for some reason can't type some of the characters. Here is my type code:
public void type(String s,Robot robot) {
byte[] stringBytes = s.getBytes();
for (byte b : stringBytes) {
int code = b;
if (code > 96 && code < 123)
code = code - 32;
robot.keyPress(code);
robot.keyRelease(code);
}
}
how can i fix this problem?
If you want to "type back what the user entered", then surely you should be capturing a set of KeyEvent objects, and not a String. There is not a key for every String character, far from it! (for instance you need to press 'shift' to input a colon, so that's two key presses and not one)
Robot expects key codes defined in KeyEvent.