Selecting Last line of Text Area - java

I am trying to create a java text area, with it being created with the text
"Chat Here!" being placed inside the textarea. I then want them to type in a word, and press enter. When they press enter, i want to be able to select the text from just that line - (i.e. chatArea.getText() gets all the text, including the "Chat Here!", which is not what I want. As well, I can't say that the text they enter will always be on a specific line (i.e. always the 2nd line); I haven't found a way to access the line the user has put in exclusively yet. Any help would really be appreciated. I'm still new to java, so if examples of code could be given as well, that'd be really helpful. Thanks a lot.

I then want them to type in a word, and press enter. When they press enter, i want to be able to select the text from just that line
You can use the Utilities class to help you out:
int end = textArea.getDocument().getLength();
int start = Utilities.getRowStart(textArea, end);
while (start == end)
{
end--;
start = Utilities.getRowStart(textArea, end);
}
String text = textArea.getText(start, end - start);
System.out.println("(" + text + ")");
The above will return the last line that contains text. The while loop handles empty lines at the end of the text area.

Related

Checking user input with scanner

I am trying to implement a simulator that has certain commands the user can input.
One of these commands is "s" which when entered should step through one instruction of the assembly file. However there is another instruction with the format "s num" where the user can define just how many instructions they want to step through.
I check for this
if(input.equals("s"))
{
//check for num next
if(user.hasNextInt())
{
input = user.next();
step(Integer.parseInt(input), assembler);
}
else
{
step(1, assembler);
}
}
However the problem is if the user only enters "s" the scanner will wait for the next input rather than just calling step. My idea is if there is an int after the s was input then proceed with the num step, other wise just call step.
Any help is greatly appreciated!
I would split the input into two parts and then treat it. For example,
String input = user.nextLine();
String array[] = input.split(" ");
if(array.length<2){
//check for `s`
}else{
//check for `s num`
}
you could try this:
if(input.equals("s"))
{
step(1, assembler);
}
else if(input.startsWith("s") && input.length() > 2)
{
step(Integer.parseInt(input.substring(input.indexOf(" ")+1)), assembler);
}
If control were to go inside the else if block, the current solution assumes that there is always a number after the String s with a white space delimiter in between them, but you can go on further and do more validations if necessary.

Making input.getText take my next input rather than my last one

I've got a window (like a command prompt) and when I type "calculate", it's supposed to begin the calculator process. When I type "calculator", it says "calculator activated" and "please input your first value".
The problem is, when I type this value, I don't know how to make it use it. Instead, it's taking the text from when I said "calculate" before.
Any ideas of how I can get it to take the number, rather than the word "calculate"?
public void calculate(){
try{
print("calculator activated" + "\n" + "please input your first value" + "\n", false, new Color(210, 190, 13));
String words = input.getText();
//trying to get it to take the number I input
print (words +"\n", false, new Color(210, 190, 13));
//this print is to test what text it's saving as the 'words' variable
//all it prints is the word 'calculate'
}
catch (Exception ex){}
}
You're printing the invitation to type a number and reading the content of the input immediately after. So yes, the input at that time still contains "calculate". Printing an invitation, or calling getText() on a text field, don't block until the user erases the text and replaces by something else. It just returns the current text in the field.
GUI applications don't work like console applications. They are event based. Your calculate method should not do anything other that printing the invitation. You should have an ActionListener on the text field or on a button, so that, when the user types enter in the text field or presses the button, the listener is called, and gets the text from the text field.
Read the tutorial about events.

Open a text file and find a word and point to that word

I need to open a log file (.txt) and to go to that specific word.
Ex:- If im searching "MyTextWord" in the text file, it should open the default editor and go to the word "MyTextWord".
If it's in the 100th line it should go there, so that it shows 100th line and onwards.
Can it be done for linux and windows?
Depending on which editor is the default, yes it is doable. For example if you use Sublime Text you can open files with sublime somefile.txt:X:Y where X is the line number and Y is the column or character position. I'm sure most decent editors have similar capabilities, I'm not sure if there is any standards for this though.
So basically you would have to pre-process the log in question to find the line number and character position, start the editor with some additional parameters. As far as default editor goes, that would be more difficult since they probably don't share the same parameters for specifying line/column. And some, such as windows notepad probably don't support this kind of thing at all.
Here is a way to open NotePad for windows. I'm not sure if you are able to search and select text within the process itself...I'll check into that.
You can also check out the Desktop javadocs.
I think, past a few days I was developing a simple project which involved the same thing.
You can use Scanner to scan the file for the data. And then loop through it to get the data.
I would paste the code here and I would share the post link with you, so that if you need any further info, you can get it from there.
You can pass the string as the parameter to the method.
String character = sc.next(); // read character...
// Find the character
System.out.println("Searching now...");
getCharacterLocation(character); // here is the parameter as character
File reading function is below:
File file = new File("res/File.txt");
Scanner sc = new Scanner(file);
int lineNumber = 0;
int totalLines = 0;
boolean found = false;
// First get the total number of lines
while(sc.hasNextLine()) {
totalLines++;
sc.nextLine();
System.out.println("Line looping! For Total Lines variable.");
}
int[] lineNumbers = new int[totalLines];
int lineIndex = 0;
System.out.println("Searching in each line...");
sc.close();
sc = new Scanner(file);
while(sc.hasNextLine()) {
// Until the end
/* Get each of the character, I mean string from
* each of the line... */
String characterInLine = sc.nextLine().toLowerCase();
if(characterInLine.indexOf(character.toLowerCase()) != -1) {
found = true;
}
lineNumber++;
if(sc.hasNextLine())
sc.nextLine();
}
System.out.println("Searching complete, showing results...");
// All done! Now post that.
if(found) {
// Something found! :D
System.out.print("'" + character + "' was found in the file!");
} else {
// Nope didn't found anything!
System.out.println("Sorry, '" +
character + "' didn't match any character in file .");
}
sc.close();
Yes, I know its a bit messed up code, because I like writing comments and I like to get information of what ever process is being executing and has done executing.
To get the whole code for this, go to the link below.
http://basicsofwebdevelopment.wordpress.com/2014/05/27/scanning-file-for-particular-string-or-character-searching/

Adding input to arrayList using java.util.Scanner [duplicate]

This question already has answers here:
System.in.read() does not block to read more input characters? [duplicate]
(3 answers)
Closed 8 years ago.
I have a project the is suppose add an input to an array list. I used scanner.util for my input, I'm suppose to input a Title = (String) and ID = (int), after input the project then provides me an option to input another or exit, for this i used while loop that when the input value is not equal to "Exit", loop. The problem is my project skips the input option to Exit or continue, does anyone have any idea how to fix it???
here is the code
String option = "";
while(!option.equals("Exit"))
{
System.out.println("Add your New Movie below\n");
movie.setName(input.nextLine());
movie.setid(input.nextInt());
System.out.println("Type in 'Quit'to end, type anything to add another Movie");
movieList.add(movie.getid() + " " + movie.getName());
option = input.nextLine();
}
Well, the problem is pretty obvious, the methods nextXXX in java.util.Scanner will only read the value of type XXX.
This means your return character "\n" is still available for read, so the input Exit is not even tested the option is always tested against a "\n".
I suggested using a better InputStream reader, or BufferedReader or anything else. If you still want go with this code then add another option.nextInt(); at the end of this loop.
String option = "";
while(!option.equals("Exit"))
{
System.out.println("Add your New Movie below\n");
movie.setName(input.nextLine());
movie.setid(input.nextInt());
System.out.println("Type in 'Quit'to end, type anything to add another Movie");
movieList.add(movie.getid() + " " + movie.getName());
option = input.nextLine();
option = input.nextLine();
}
nextInt() only reads the next int from the input stream, and leaves any other characters on the stream.
When you press "enter" after entering an ID, your computer sticks either a newline character ('\n') on *nix systems or a newline and a carriage return ("\r\n") on Windows systems at the end of the line. So this is what happens on a *nix system when you enter the ID:
User input:
> 5\n
Process next int: return 5
// So now "\n" is left on the input stream
// Code goes to option = input.nextLine()
// "\n" is still on the input stream, so nextLine() immediately returns an empty string
You should read the entire line when getting the next integer and use Integer.parseInt() to extract its value.

Why cant my while-loop with system.in.read() get the last line in console?

Im stuck with a problem regarding System.in.read(). I want to print everything that is pasted into the console.
My code looks like this:
import java.io.IOException;
public class printer {
public static void main(String[ ] args) {
int i;
try {
while ((i = System.in.read()) != -1) {
char c = (char)i;
System.out.print(c);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
The problem is that if you paste ,for example, three lines into the console the program will then print the two first lines, but not the third. Why is that? It prints the third if i press enter but with a huge space between the second and the third line.
I've also tried to store every char in a string and then print the whole string after the loop, but the loop never ends. Is their a way to stop this specific loop (I will not know how many rows the user will paste)
Your app echoes any line you type (or paste) in the console. Problem is, consoles are a thing of the past, and they were supposed to do stuff line by line. This means your app only prints after having read the new line character, because System.in.read blocks.
The text you are pasting already includes two line breaks, but the last line lacks this delimiter. This is what you are posting, where <nl> means a line break:
line1<nl>line2<nl>line3
If you go to your fav text editor, paste there, add an additional line break at the end and copy all again with the "select all" menu, you'll see the last line.

Categories