If statement with two conditions not working properly - java

I am new to programming and I am trying to create a program which parses a file and outputs the tokens. At the minute I am trying to create an if statement which will output the name of each operator with two characters, e.g. "&&" or "<=". My if statement does not work for "<=" as it picks up the '<" and '=' separately due to the earlier code:
else if (getOp(ch) != null) {
System.out.println(line + ", " + sglchar + ", "+ ch);
counter++;
continue;
}
My getOp(ch) method contains the operators with one character, however I cannot figure out how to do this with two character operators and my if statements don't seem to be doing the trick.
This is the if statement I am trying:
else if (prog.charAt(counter) == '<' && prog.charAt(counter+1) == '=') {
String str = "";
str += ch;
str += prog.charAt(counter++);
System.out.println(line + ", " + getOp(str) + ", " + str);
counter++;
continue;
}

As outlined in my comments, use of Java's Scanner class. It makes parsing text files very easy.
Consider the following:
Scanner sc = new Scanner(new File("file.txt"));
while (sc.hasNext()) {
String token = sc.next();
if (Pattern.matches("<=", token)) {
System.out.println(token);
}
}
sc.close();
}
outputs:
<=

Related

String formatter function in java

I m writing a function to format a string input. The function is to make the text output left indented, with a limit to the number of characters in a line.
if there are excess whitespaces,' ', between words; i skip the excess whitespace and only put one whitespace' '. if the word is too long and will go over the character per line limit, i insert whitespaces until the limit and start a new line with that word in the newline.
i am unable to create the padding section of the code. which is the part which checks whether the word will go over the limit and to start a newline with the word in the newline.
as part of the assignment requirements, i am only allowed to use charAt() and length methods on a String
void runApp(){
String text = " Knowing You Jesus " +
" Graham Kendrick " +
"All I once held dear, built my life upon " +
"All this world reveres, and wars to own " +
"All I once thought gain I have counted loss " +
"Spent and worthless now, compared to this " +
"Knowing you, Jesus " +
"Knowing you, there is no greater thing " +
"You're my all, you're the best " +
"You're my joy, my righteousness " +
"And I love you, Lord " +
"Now my heart's desire is to know you more " +
"To be found in you and known as yours " +
"To possess by faith what I could not earn " +
"All-surpassing gift of righteousness " +
"Oh, to know the power of your risen life " +
"And to know You in Your sufferings " +
"To become like you in your death, my Lord " +
"So with you to live and never die " +
"Source: Musixmatch " +
"Songwriters: Tim Hughes / Ben Cantelon ";
//limit = 60
System.out.println(" `123456789012345678901234567890123456789012345678901234567890");`
System.out.println(leftTextFormat(text, 60));
System.out.println();
}
// This prints out everything left indented, but does not pad.
String leftTextFormat(String text, int limit){
String formattedText = "";
int charCount = 0;
formattedText = formattedText+"[";
for (int i=0; i<text.length(); i++){
if (charCount%limit ==0){
if (text.charAt(i) == ' '){
continue;
}else if (text.charAt(i) != ' ' ){
formattedText = formattedText+text.charAt(i);
charCount++;
}
}else if (charCount%limit != 0){
if (text.charAt(i) == ' '){
if (text.charAt(i-1) != ' '){
formattedText = formattedText+text.charAt(i);
charCount++;
}else{
continue;
}
}else if (text.charAt(i) != ' '){
formattedText = formattedText+text.charAt(i);
charCount++;
}
}
if (charCount%limit ==0 && charCount!=0){
formattedText = formattedText+"]\n[";
}
}
return formattedText;
}
The expected output is this:
https://drive.google.com/file/d/1uYXtSBo37sFnpwJeBGtjF0MFYNngtZXv/view?usp=sharing
what i managed to do is this:
https://drive.google.com/file/d/102zNMe4JhaO2IUoOPCS5GSZ02Pq9aXwX/view?usp=sharing
123456789012345678901234567890123456789012345678901234567890
[Knowing You Jesus Graham Kendrick All I once held dear, buil]
[t my life upon All this world reveres, and wars to own All I]
[once thought gain I have counted loss Spent and worthless no]
[w, compared to this Knowing you, Jesus Knowing you, there is]
[no greater thing You're my all, you're the best You're my jo]
[y, my righteousness And I love you, Lord Now my heart's desi]
[re is to know you more To be found in you and known as yours]
[To possess by faith what I could not earn All-surpassing gif]
[t of righteousness Oh, to know the power of your risen life ]
[And to know You in Your sufferings To become like you in you]
[r death, my Lord So with you to live and never die Source: M]
[usixmatch Songwriters: Tim Hughes / Ben Cantelon
Ok attempt, but your problem is that you only adding characters and never actually establishing if those characters make up words and if those words, which you are adding, are going to go over your "limit". Hence you have no idea when a word will actually cause you to go over your imposed limit and subsequently you are make no attempt to pad your line when you are potentially going to go over that limit.
Essentially you need to work word for word and line by line. Each time you've established a word, check that the length of that word plus the length of your current line is not greater than your limit. If it's greater don't concatenate it to your current line, rather pad the line to your limit and start a new line.
public String formattedLine(String singleLine, int limit) {
int padding = limit - singleLine.length();
String pad ="";
for(int j = 0; j < padding; j ++) {
pad += " ";
}
return "[" + singleLine + pad + "]\n";
}
public String leftTextFormat(String text, int limit) {
String word = "";
String singleLine = "";
String formattedText = "";
for(int i=0; i<text.length(); i++) {
if (text.charAt(i) != ' ') {
word = word + text.charAt(i);
} else {
if(word.length() > 0) {
if(singleLine.length() + word.length() >= limit) {
formattedText = formattedText + formattedLine(singleLine, limit);
singleLine = "";
}
if(singleLine.length() == 0) {
singleLine = word;
} else {
singleLine = singleLine + " " + word;
}
word = "";
}
}
}
formattedText = formattedText + formattedLine(singleLine, limit);
return formattedText;
}

Scanner won't read the next line from a file. JAVA

Like the title says, I can get it to write the first thing to the file I want it to, but after that it doesn't write any more. I run it through the debugger, and see that it's not even reading the next line (I know this because it's not filling the array.) I tried manually advancing the pointer (I don't know if that's actually a thing you can do) at the end of the loop with "line = in.readline;", but It just throws a "nosuchelement" exception. Here's my try block"
try
{
in = new BufferedReader(new FileReader("lab7input.txt"));
outNormal = new PrintWriter(new File("normal.txt"));
outVegetarian = new PrintWriter(new File("vegetarian.txt"));
outPescetarian = new PrintWriter(new File("pescetarian.txt"));
outInvalid = new PrintWriter(new File("invalid.txt"));
String line = in.readLine();
StringTokenizer st = new StringTokenizer(line);
while (line != null)
{
Scanner sc = new Scanner(line);
while(sc.hasNext())
{
if(st.countTokens() == 3)
{
attendee3[0] = sc.next();
attendee3[1] = sc.next();
attendee3[2] = sc.next();
if(Integer.parseInt(attendee3[2]) == 0)
{
outNormal.println(attendee3[0] + " " + attendee3[1]);
outNormal.close();
}
else if(Integer.parseInt(attendee3[2]) == 1)
{
outVegetarian.println(attendee3[0] + " " + attendee3[1]);
outVegetarian.close();
}
else if(Integer.parseInt(attendee3[2]) == 2)
{
outPescetarian.println(attendee3[0] + " " + attendee3[1]);
outPescetarian.close();
}
else
{
outInvalid.println(attendee3[0] + " " + attendee3[1]);
outInvalid.close();
}
}
if(st.countTokens() == 4)
{
attendee4[0] = sc.next();
attendee4[1] = sc.next();
attendee4[2] = sc.next();
if(Integer.parseInt(attendee4[3]) == 0)
{
outNormal.println(attendee4[0] + " " + attendee4[1] + " " + attendee4[2]);
outNormal.close();
}
else if(Integer.parseInt(attendee4[3]) == 1)
{
outVegetarian.println(attendee4[0] + " " + attendee4[1] + " " + attendee4[2]);
outVegetarian.close();
}
else if(Integer.parseInt(attendee4[3]) == 2)
{
outPescetarian.println(attendee4[0] + " " + attendee4[1] + " " + attendee4[2]);
outPescetarian.close();
}
else
{
outInvalid.println(attendee4[0] + " " + attendee4[1] + " " + attendee4[2]);
outInvalid.close();
}
}
//line = in.readLine();
}
}
}
a simpler and cleaner way would be
String line = in.readLine();
while (line != null)
{
String arr [] = line.split ();
if(arr.length == 3)
{
attendee3[0] = arr[0];
attendee3[1] = arr[1];
attendee3[2] = arr[2];
}
// other count code
line = in.readLine();
}
You have to put line = in.readLine() one block below and not in a while block of a scanner.
Not only that, i've had the experience that Scanner can only read in UTF-8 codeded .txt files. so always make sure that they are UTF-8 coded.
If they are not just simply open the file and save it with that coding.

Fill in "secret word" letters

I am doing a hangman project.
I have got most of the code working.
The one part I can't get working is where the "secret word" has more than one letter which is the same. For example "hello" has 2 "l"'s.
This is the code for the part of the code where it replaces the "----" (hello) with the letter that was guessed if the guess was right:
int pos = $Input.indexOf($Guessed);
if (pos == -1)
{
System.out.print("Search string '" + $Guessed + "' not found");
}
else
{
System.out.println("\nSearch string found at " + (pos + 1));
pos = $Input.indexOf($Guessed);
String before = $Display.substring(0, pos);
String after = $Display.substring(pos + $Guessed.length());
System.out.println(before + $Guessed + after);
$Display = before + $Guessed + after;
System.out.println($Display);
$GuessAmt++;
}
I have looked at various answers on here but I cannot get one to work so far.
Obviously if someone guessed "l" then "-----" would change to "--ll-" for (hello).
I am not looking for someone to code this for me as I enjoy a challenge but a bit of a hint would be lovely!!
Obviously from looking at my code you may be able to guess we are not allowed to use arrays yet unfortunately. This is only an intro to Java class really.
Any help would be appreciated.
EDIT: Just to be clear, at the moment it ONLY does the first "l" not both the "l"'s of (hello).
EDIT: Changed to this. However, now it is repeating the "inside if" print statement over and over. Cant see how to fix this!
int pos = $Input.indexOf($Guessed);
if (pos == -1)
{
System.out.print("Search string '" + $Guessed + "' not found");
}
else
{
//System.out.println("\nSearch string found at " + (pos + 1));
for(int i=0;i<$StrLength;i++)
{
System.out.println(i);
if($Input.charAt(i) == $Guessed.charAt(0))
{
i = $Input.indexOf($Guessed);
String before = $Display.substring(0, i);
String after = $Display.substring(i + 1);
System.out.println("inside if" + before + $Guessed + after);
$Display = before + $Guessed + after;
}
}
System.out.println($Display);
$GuessAmt++;
}
If you still wanna use the indexOf you can use its overloaded version as well to insure that you have gone through all letter occurrences:
int index = str.indexOf('l');
while(index >= 0) {
// FILL THE BLANKS WITH THE LETTER
index = str.indexOf('l', index +1);
}
You can iterate over the String and check every character individually using word.charAt(i).
for (int i = 0; i < word.length; i++) {
if (word.charAt(i) == guessedChar) {
// do stuff
}
}

Automating search functionality using Selenium - Java

I need to automate search functionality as below:
Search string = (X* OR "Y") AND Z
On entering this search system should assert the result. My problems are:
1) How to make precedence among operators because if there is () then that should be executed and with its result other parts of search string to be checked.
2) termi* can be terminate, terminator. How do we check this and assert
3) "Stack Overflow" means the result should have exactly matched. How can we find and assert
4) Likewise NOT operator, how can we assert
Pls share with me if any kind of help you can provide.
Thanks in advance.
Some how managed to write code in java using StringBuffer :)
Instead of storing the result of first block and process next I have created a string command based on the searchString as below and finally fire the newly created command and verified the answer.
Like whenevenever AND comes in searchString we insert && operator and for OR || operator.
String[] arrSearch=searchString.split("\\s");
StringBuffer sb = new StringBuffer();
boolean skipFlag = false;
for(int i=0;i<arrSearch.length;i++){
System.out.println(arrSearch[i]);
if(!skipFlag && arrSearch[i].startsWith("\"")){
skipFlag = true;
continue;
}else if(skipFlag){
if(arrSearch[i].endsWith("\"")){
skipFlag = false;
continue;
}else{
continue;
}
}else if(arrSearch[i].startsWith("(")){
String temp = arrSearch[i].substring(1);
sb.append("(selenium.isTextPresent(" + temp + ")" + " ");
}else if(arrSearch[i].startsWith(")")){
String temp = arrSearch[i].substring(0,arrSearch[i].length()-1);
sb.append("selenium.isTextPresent(" + temp + "))" + " ");
}else if(arrSearch[i].equalsIgnoreCase("AND")){
sb.append("&&" + " ");
}else if(arrSearch[i].equalsIgnoreCase("OR")){
sb.append("||" + " ");
}else if(arrSearch[i].equalsIgnoreCase("NOT")){
sb.append("!");
}else if(arrSearch[i].endsWith("*")){
String temp = arrSearch[i].substring(0,arrSearch[i].length()-1);
sb.append("selenium.isTextPresent(\"//*[contains('" + temp + "')]\")" + " ");
}else{
sb.append("selenium.isTextPresent(" + arrSearch[i] + ")" + " ");
}

removing comma from string array

I want to execute a query like
select ID from "xyz_DB"."test" where user in ('a','b')
so the corresponding code is like
String s="(";
for(String user:selUsers){
s+= " ' " + user + " ', ";
}
s+=")";
Select ID from test where userId in s;
The following code is forming the value of s as ('a','b',)
i want to remove the comma after the end of array how to do this ?
Here is one way to do this:
String s = "(";
boolean first = true;
for(String user : selUsers){
if (first) {
first = false;
} else {
s += ", ";
}
s += " ' " + user + " '";
}
s += ")";
But it is more efficient to use a StringBuilder to assemble a String if there is looping involved.
StringBuilder sb = new StringBuilder("(");
boolean first = true;
for(String user : selUsers){
if (first) {
first = false;
} else {
sb.append(", ");
}
sb.append(" ' ").append(user).append(" '");
}
sb.append(")");
String s = sb.toString();
This does the trick.
String s = "";
for(String user : selUsers)
s += ", '" + user + "'";
if (selUsers.size() > 0)
s = s.substring(2);
s = "(" + s + ")";
But, a few pointers:
When concatenating strings like this, you are advised to work with StringBuilder and append.
If this is part of an SQL-query, you probably want to sanitize the user-names. See xkcd: Exploits of a Mom for an explanation.
For fun, a variation of Stephen C's answer:
StringBuilder sb = new StringBuilder("(");
boolean first = true;
for(String user : selUsers){
if (!first || (first = false))
sb.append(", ");
sb.append('\'').append(user).append('\'');
}
sb.append(')');
you could even do the loop it like this :-)
for(String user : selUsers)
sb.append(!first || (first=false) ? ", \'" : "\'").append(user).append('\'');
Use the 'old style' of loop where you have the index, then you add the comma on every username except the last:
String[] selUsers = {"a", "b", "c"};
String s="(";
for(int i = 0; i < selUsers.length; i++){
s+= " ' " + selUsers[i] + " ' ";
if(i < selUsers.length -1){
s +=" , ";
}
}
s+=")";
But as others already mentioned, use StringBuffer when concatenating strings:
String[] selUsers = {"a", "b", "c"};
StringBuffer s = new StringBuffer("(");
for(int i = 0; i < selUsers.length; i++){
s.append(" ' " + selUsers[i] + " ' ");
if(i < selUsers.length -1){
s.append(" , ");
}
}
s.append(")");
Use StringUtils.join from apache commons.
Prior to adding the trailing ')' I'd strip off the last character of the string if it's a comma, or perhaps just replace the trailing comma with a right parenthesis - in pseudo-code, something like
if s.last == ',' then
s = s.left(s.length() - 1);
end if;
s = s + ')';
or
if s.last == ',' then
s.last = ')';
else
s = s + ')';
end if;
Share and enjoy.
i would do s+= " ,'" + user + "'"; (place the comma before the value) and add a counter to the loop where i just do s = "'" + user + "'"; if the counter is 1 (or 0, depending on where you start to count).
(N.B. - I'm not a Java guy, so the syntax may be wrong here - apologies if it is).
If selUsers is an array, why not do:
selUsers.join(',');
This should do what you want.
EDIT:
Looks like I was wrong - I figured Java had this functionality built-in. Looks like the Apache project has something that does what I meant, though. Check out this SO answer: Java: function for arrays like PHP's join()?
I fully support Stephen C's answer - that's the one I wanted to suggest aswell: simply avoid adding the additional comma.
But in your special case, the following should work too:
s = s.replace(", \\)", ")");
It simply replaces the substring ", )" with a single bracket ")".
Java 1.4+
s = s.replaceFirst("\\, \\)$", ")");
Edited: I forgot last space before parethesis
StringBuilder has a perfectly good append(int) overload.
String [] array = {"1","2","3" ...};
StringBuilder builder = new StringBuilder();
builder.append(s + "( ")
for(String i : array)
{
if(builder.length() != 0)
builder.append(",");
builder.append(i);
}
builder.append(" )")
Answer shamelessly copied from here

Categories

Resources