identifying a new line in a scanner [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java: Scanner stopping at new line
I'm new to programming and I was wondering if there is a way to identify when there is a new line in a Scanner. My method is supposed to take a Scanner of a text file and break the line if it is over 60 characters long without breaking it in the middle of a word.
The problem I'm having is since I'm going by each token my code doesn't account for lines that are less than 60 characters and appends them onto the previous line up to 60 characters.
This is the method I have created:
public static void wordWrap3(Scanner s) {
String k = "";
int length = 0;
while(s.hasNext()) {
k = s.next();
length = length + k.length() + 1;
if (length>60) {
System.out.print("\n");
length = 0;
}
System.out.print(" " + k);
}
}
This is the text I am using:
We're no strangers to love, You know the rules and so do I,
A full commitment's what Im thinking of, You wouldn't get this from any other guy.
I just wanna tell you how I'm feeling, Gotta make you understand.
Never gonna give you up, Never gonna let you down, Never gonna run around and desert you.
Never gonna make you cry, Never gonna say goodbye, Never gonna tell a lie and hurt you.

You seem to be saying that you want to word wrap each line separately. If so, the simple solution is to split the input into lines, and then create a scanner for each line and pass that to your existing wordWrap3 method.

you can try:
String fileLine = "";
while(s.hasNextLine()) {
fileLine = s.nextLine();
if(fileLine.length() > 60 )
{
while (fileLine.length() > 60)
{
String tempStr = fileLine.substring(0, 60);
int rightIdx = tempStr.lastIndexOf(' ');
String firstStr = tempStr.substring(0, rightIdx);
String secStr = fileLine.substring(rightIdx + 1, fileLine.length());
System.out.println(firstStr);
//if still it is big
if(secStr.length() > 60)
fileLine = secStr;
else
{
System.out.println(secStr);
break;
}
}
}
else
{
System.out.println(fileLine);
}
}
ofcourse it can be improved further.

Related

(JAVA) having trouble counting the exact number of lines and other specific characters on files

ok so i have two .txt files, one called "input.txt" and another called "output.txt". to create output i have to copy the text from input but replace all spaces between words with #'s and add a new line with the string "#NEW_LINE#" after each line of the original text
for example, if input.txt is this:
the unstoppable marching of time
that is slowly guiding us all towards
an inevitable death
then output.txt should be something like this:
the#unstoppable#marching#of#time
#NEW_LINE#
that#is#slowly#guiding#us#all#towards
#NEW_LINE#
an#inevitable#death
#NEW_LINE#
anyway you get the idea.
now i dont have a problem with this particular task, but then i am also asked to print on the screen a message that shows the total number of lines of text from both files, and another that prints the total number of #'s from output.txt. and while i dont have trouble with counting the lines, their numbers show up correctly but i do have trouble figuring out the #'s... ill explain.
here's part of the code i tried at first: [btw this whole thing takes place on one class, with no other methods apart from main, of course. i thought it would be simpler that way idk 💁‍♂️💅]
File fsrc=new File("input.txt");
File fdes=new File("output.txt");
int atCount = 0; //number of #'s
int lineCountIN=0; //number of input's lines
int lineCountOUT=0; //number of output's lines
FileReader fr = new FileReader(fsrc);
BufferedReader br =new BufferedReader(fr);
FileWriter fw = new FileWriter(fdes);
String s = null;
while((s=br.readLine())!=null)
{
if ((s.equals(" "))) {
fw.write(s.replace(" ","#"));
atCount++; }
else fw.write(s);
fw.write("\n");
lineCountOUT++;
lineCountIN++;
fw.write("#NEW_LINE#");
fw.write("\n");
lineCountOUT++;
fw.flush();
}
fw.close();
[...]
System.out.println("Total instances of # characters at output.txt: " + atCount);
the message that pops up on the screen will always be: "Total instances of # characters at output.txt: 0".
later i changed the if-else block to a do-while block:
do {
fw.write(s.replace(" ","#"));
atCount++; }
while ((s.equals(" ")));
but then the message does not return the exact number of #'s, in fact the number it shows just happens to be equal to lineCountIN for some reason (for example, for an input.txt file with 3 lines in total, the final message is: "Total instances of # characters at output.txt: 3")
so yeah thats pretty much it lmao i guess im using the atCount thingy wrong?? any help could be appreciated <3
Your approach finding the whitespace was not correct here is the solution, instead of searching in the whole string and count each line, you have to check each character and count it
public static void main(String[] args) {
String s = "the unstoppable marching of time\n" +
"that is slowly guiding us all towards\n" +
"an inevitable death";
int countSpace = 0;
if (s.contains(" ")) {
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' ') {
countSpace++;
}
}
s = s.replace(' ', '#');
}
System.out.println(s);
System.out.println(countSpace);
}

Java: Parse lines from files

I am in need of some ideas. I have a file with some information like this:
AAA222BBB%
CC333DDDD%
EEEE444FF%
The '%' sign is like an indicator of "end of line"
I would like to read every line, and then parse it to fit a certain format (4 letters, 3 digits and 4 letters again) - So if it looks like the above, it should insert a special sign or whitespace to fill, like this:
AAA-222BBB-%
CC--333DDDD%
EEEE444FF--%
My first and immediate idea was to read every line as a string. And then some huge if-statement saying something like
For each line:
{
if (first symbol !abc...xyz) {
insert -
}
if (second symbol !abc...xyz) {
insert -
}
}
However, I am sure there must be a more elegant and effective way, do to a real parsing of the text, but I'm not sure how. So if anyone has a good idea please enlighten me :-)
Best
My first advice is to read this other post (nice explanation of scanner and regex):
How do I use a delimiter in Java Scanner?
Then my solution (sure it is the the cleverest, but it should work)
For each line:
{
Scanner scan = new Scanner(line);
scan.useDelimiter(Pattern.compile("[0-9]"));
String first = scan.next();
scan.useDelimiter(Pattern.compile("[A-Z]"));
String second = scan.next();
scan.useDelimiter(Pattern.compile("[0-9]"));
String third = scan.next();
scan.close();
System.out.println(addMissingNumber(first, 4) + addMissingNumber(second, 3) + addMissingNumber(third, 4));
}
//For each missing char add "-"
private static String addMissingNumber(String word, int size) {
while (word.length() < size) {
word = word.concat("-");
}
return word;
}
The output: "AAA-222BBB-"

Java Scanner doesn't work in Processing

For an assignment I have due, my group and I were asked to code an educational/interactive game, and we decided on a basic maths one.
To get the users answers, we decided to use Java Scanner and put this line of code at the top of all the code we have;
java.util.Scanner
One of the loops that use this is the page with the questions on it, the loop looking something like this;
scoreCount = 0;
for (questions = 0; questions < 5;) {
//get the user's answer
userAnswer[questions] = input.nextInt();
//text box for users answer
if (userAnswer[questions] == compAnswer) {
//put tick next to answer
//add one to score
scoreCount = scoreCount + 1;
} else if (userAnswer[questions] != compAnswer) {
//put cross next to answer
}
//go to next question
questions++ ;
}
I'm working through all the errors that were thrown up and every time i don't have java.util.Scanner commented out Processing throws us the errors unexpected token: and then either class or void, which i don't get, but when java.util.Scanner is commented out, the classes and voids all work and the .input.nextInt() isn't recognised.
I am new to Java programming and Processing, any help at all would be greatly appreciated
EDIT
i think this is the link which lets you see my code, it's called Test;
https://github.com/MeganSime/Week8DataVis
you have to check if scanner has next int (token)
Scanner input = new Scanner(System.in);
.
.
if(input.hasNextInt()) { // or hasNext()
userAnswer[questions] = input.nextInt();
}
You're probably inserting a non int value where the scanner expects that. You should do something like that:
if(input.hasNextInt()) {
userAnswer[questions] = input.nextInt();
} else {
scan.next(); //consume any non-int value like ":"
}

Reading and compiling lines from JTextArea using conditional statements [duplicate]

This question already has answers here:
How to evaluate a math expression given in string form?
(26 answers)
Closed 9 years ago.
Good morning everyone, I'm a beginner student in java programming. So, direct to the point, I'm creating a program that can read and compile a .txt file with a click of a button.
I'm already done with the reading of the file. My problem is that my program doesn't compile the text from the first JTextArea and show the results to the second JTextArea.
I've been having this problem for four days now, I've been trying to change the code in any possible ways I can think of. Can someone enlighten me and tell me what's wrong with my code? It will surely help me a lot.
Many thanks to all.
#SuppressWarnings("IncompatibleEquals")
private void executeCodeActionPerformed(java.awt.event.ActionEvent evt) {
String loadi = "Load";
String add = "Add";
String subt = "Subt";
String mult = "Mult";
String div = "Div";
String input = "Input";
String print = "Print";
int number = 0;
String txt = textAreaCode.getText();
String split = " ";
String [] text = txt.split(split);
String word = text[0];
int num = Integer.getInteger(text[1]);
int result = num;
int result1 = 0;
Scanner scan = new Scanner(txt);
scan.nextLine();
for (int count=0;count<txt.length();count++ ) {
if (loadi.equalsIgnoreCase(word)){
result1 = num + number;
}
else if (add.equalsIgnoreCase(word)){
result1 = num + result;
}
else if (subt.equalsIgnoreCase(word)){
result1 = num - result;
}
else if (mult.equalsIgnoreCase(word)){
result1 = num * result;
}
else if (div.equalsIgnoreCase(word)){
result1 = num / result;
}
else if (print.equalsIgnoreCase(word)){
textAreaOutput.setText(String.valueOf(result1));
}
else if (input.equalsIgnoreCase(word)){
String nmbr = inputField.getText();
int nmr = Integer.parseInt(nmbr);
result1 = nmr + number;
}
}
I see a few errors in your code that might add up to not working at all. Here they are:
The variable word is never updated to the following tokens (it is set to text[0] at first then never changed). Same goes for num.
All operations act on variables num and result, then put the result into result1. So intermediate results are not carried from an operation to the next.
The "input" operation load current value from inputField, without waiting for the user to actually type something.
The main loop iterate until count reach the number of characters in the program; it should loop for the number of tokens instead.
Also, here are a few suggestions to make your code more ligible:
If you are beginning in Java, then get rid of the Scanner object, and keep only the "split on spaces" approach. I would not recommend this for real problems, but Scanner is somewhat complex to use correctly.
Wrap the splited words array into a List collection, then obtain an iterator from it. Here it is:
Iterator<String> words = Arrays.asList(txt.split("[ ]+")).iterator();
Then, write your loop as:
while (words.hasNext()) {
String command = words.next();
...
}
Move your operation mnemonics outside of the function, and mark them as final.
Read your operation arguments from inside each operation block; this is required because some operation do not receive arguments.
Well, I won't give you the code, as this is something you really have to do by yourself. Hope that helps. Good luck.

For or While loop skipping an input [duplicate]

This question already exists:
Closed 10 years ago.
Possible Duplicate:
Scanner issue when using nextLine after nextInt
I am creating a client program that needs to read both a String and an integer from my server. Depending on what integer it receives it adds some labels to the GUI. So far, my program reads the integer but skips the String. The following output is the output of my program when I try to write the integers to the program:
Server writes: 1
Server writes: 1
System prints: 1
System prints: j1
System prints: Name
The problem is that I am unable to write a String because it skips the String. How can I avoid this problem (note that I have also tried a for loop)
My code is as following:
int times = client.reciveCommando();
int o = 0;
System.out.println(times);
while (o != times) {
int j = client.reciveCommando();
System.out.println("j"+ j);
String name = client.reciveString();
System.out.println("Name " +name);
createUser(j, name);
o++;
}
The createUser method:
private void createUser(int j, String reciveChat) {
if (j == 1) {
chatPerson1.setVisible(true);
lbl_Chatperson1_userName.setVisible(true);
lbl_Chatperson1_userName.setText(reciveChat);
} else if (j == 2) {
lbl_chatPerson2.setVisible(true);
lbl_userName2.setVisible(true);
lbl_userName2.setText(reciveChat);
} else {
chatPerson3.setVisible(true);
lbl_userName3.setVisible(true);
lbl_userName3.setText(reciveChat);
}
}
The client.reciveCommando method:
public int reciveCommando() throws IOException{
Integer i = input.nextInt();
return i;
}
The client.reciveString method:
public String reciveString(){
String x = input.nextLine();
return x;
}
Hope someone is able to help me with this :)
Thank you in advance.
I don't see anywhere in the loop code where you are incrementing o or changing the value of times. So either the loop is being skipped altogether (ie: times = 0) or some other place in the code is modifying either the loop variable (o) or the loop condition (times) - very bad coding in either case.
Your loop variable/increment rules should be very clear in reading the loop and easily discernible what the start/stop conditions are without needing to read other methods/etc which may modify the values during loop iteration.
My immediate guess is that times = 0, or you would be in an endless loop.
i found the solution to my question it turned out to be quite simple!
first of all let me explain what i ment.
When i my program ran the while loop it basicly skipped the line where it should have recived an input from the server. i found that the reason it did that was that the input.nextLine(); was empty which makes sence when you read the api for input.nextLine();
Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.
Returns:
the line that was skipped
since the line that i tried to get was an empty line it would skip and set name to " ".
here is the full complete code for my program and it currently works:
The while loop:
while (o != times) {
int j = client.reciveCommando();
System.out.println("j"+ j);
String name = client.reciveString();
System.out.println("Name " +name);
createUser(j, name);
o++;
}
The client.reciveString();
public String reciveString(){
String x = input.next();
return x;
}
The createUser();
private void createUser(int j, String reciveChat) {
if (j == 1) {
chatPerson1.setVisible(true);
lbl_Chatperson1_userName.setVisible(true);
lbl_Chatperson1_userName.setText(reciveChat);
}else if (j == 2) {
lbl_chatPerson2.setVisible(true);
lbl_userName2.setVisible(true);
lbl_userName2.setText(reciveChat);
}else if (j == 3){
chatPerson3.setVisible(true);
lbl_userName3.setVisible(true);
lbl_userName3.setText(reciveChat);}
Thank you for all of your responses and i will be sure to vote you up :)

Categories