I created a code in while loop in Orange HRM.
I am taking data for UID & Pwd from a text file.
But while Executing that it executes 1st line also, which is not necessary.
I want to skip the first line (UID, PWD) and proceed further.
I want the Solution with While as well as with For Loop.
I think It's simple but i am unable to do it immediately.
Please find my code written with while loop.
BufferedReader br = new BufferedReader(new FileReader("E:/WorkSpace/Test/InputData/uid.txt"));
String sCurrentLine;
while ((sCurrentLine = br.readLine())!= null)
{
String str[] = sCurrentLine.split(" ");
driver.findElement(By.id("txtUsername")).sendKeys(str[0]);
driver.findElement(By.id("txtPassword")).sendKeys(str[1]);
driver.findElement(By.id("btnLogin")).click();
Thread.sleep(3000);
if (driver.findElement(By.tagName("a")).getAttribute("id").contains("welcome"))
{
System.out.println("Login is Successful");
temp = true;
break;
}
else
{
System.out.println("Login Failed");
temp = false;
driver.navigate().to("http://opensource.demo.orangehrm.com/");
}
if (temp) {
break;
}
}
If you want to skip the first line, read it before the loop:
br.readLine()
while ((sCurrentLine = br.readLine())!= null)
{
...
Couldn't you just move the code you want executed only once, outside of the loop? Put it right before the loop, and it'll be executed, then go immediately into the loop.
Or you could have something like:
for(int i=0; i<length; i++) {
if (i == 0) {
//code you want executed
}
}
Related
i have the below code to read emails and check if the subject is matching with the expected message
Message[] messages = folder.getMessages();
String message="Thanks for contacting";
if(folder.getUnreadMessageCount()!=0)
{
for (Message mail : messages)
{
if(!mail.isSet(Flags.Flag.SEEN) && mail.getSubject().contains("Thanks"))//if mail is unread and the message matches
{
mail.setFlag(Flags.Flag.SEEN, true);
softAssert.assertTrue(true,"Email received ->");
Reporter.log("Email received ->" + mail.getSubject(), true);
break;
}
if(!mail.isSet(Flags.Flag.SEEN) && !mail.getSubject().contains("Thanks"))//if mail is unread and the message does not match
{
System.out.println(mail.getSubject() + "-> is not the email we are looking for");
}
}
}
else
{
softAssert.assertTrue(false,"Email not received");
Reporter.log("Email not received ->" + message, true);
}
The problem is I want to fail this test if both the conditions inside the for loop fail. if i put the else inside the for loop it prints not received for reach element in the loop. how do i go about this?
You can use boolean expression. See the below simple example,
boolean test = true;
boolean test2 = true;
for (int i = 0; i < 3; i++) {
if (!test) {
System.out.println("Test value is false.");
} else {
test = false;
}
if (!test2) {
System.out.println("Test2 value is false.");
} else {
test2 = false;
}
if(!test && !test2) {
System.out.println("Breaking loop.");
break;
}
}
Create two boolean variables and set their values as true incase if your if condition fails inside the loop then by using else block change the boolean value to false and do the same for your second if condition as well. In the last if condition if both statements fails then break the loop.
My website went down for a few days, therefore I am trying to produce some error handling while the MVC app doesnt have access to certain resources so if something doesnt become unavailable again the WHOLE THING doesnt have to go down.
At the moment a controller is trying to access viewbag.moreNewProducts that isnt available.
public ActionResult Index(string search)
{
string[] newProductLines = this.getMoreNewProducts();
string[] newNews = this.getMoreNews();
string[] newPromotions = this.getMorePromotions();
string[] fewerProductLines = this.getLessNewProducts(newProductLines);
ViewBag.moreNewProducts = newProductLines;
ViewBag.moreNews = newNews;
ViewBag.morePromotions = newPromotions;
ViewBag.lessNewProducts = fewerProductLines;
bool disableShowMore = false;
This is where I run into an error: " foreach (string line in newProductLines)"
public string[] getLessNewProducts(string[] newProductLines)
{
int charCount = 0;
int arrayCount = 0;
string[] displayProductLines = new string[6];
bool continueWriting;
if (newProductLines == null)
{
foreach (string line in newProductLines)
{
continueWriting = false;
for (int i = 0; charCount < 250 && i < line.Length && arrayCount < 5; i++)
{
string index = newProductLines[arrayCount].Substring(i, 1);
displayProductLines[arrayCount] += index;
charCount++;
continueWriting = true;
}
if (continueWriting == true)
{
arrayCount++;
}
}
string[] LessNewProducts = new string[arrayCount];
for (int d = 0; d < arrayCount; d++)
{
LessNewProducts[d] = displayProductLines[d];
}
return LessNewProducts;
}
else
{
return null;
}
}
how do I get around an if else statement so the whole thing doesnt have to crash?
Two things.
Your if (newProductLines == null) statement has the wrong condition on it. I don't believe that you want to enter that if newProductLines is null. You can inverse this condition to get the desired result(if (newProductLines != null)).
If you run into another situation later where you need to catch an error, you can always use the try-catch block to catch exceptions that you are expecting.
try
{
//code that could cause the error here
}
catch(NullReferenceException nullRefExcep)
{
//what you want it to do if the null reference exception occurs
}
if (newProductLines == null)
should be replaced with if (newProductLines != null) so you don't have to handle the code with newProductLines as null. Basically, with this condition you will always have the NullReferenceException unless you manage your exception with a try catch block.
The real question to ask yourself is:
Why would newProductLines be null?
Presumably getMoreNewProducts() found a situation where it thought it would be appropriate to return a null value.
If this is happening because the system has an error that would make your page meaningless, then you may just want to change getMoreNewProducts() so that it throws an exception when that error state occurs. Typically it's safest and easiest to debug programs that fail as soon as they run into an unexpected situation.
If this is happening because there are no new products, then you should just return an empty collection, rather than null. All your code should work just fine after that, without the need for an if/else statement: it will return an empty array for LessNewProducts, which is probably correct.
However, let's assume that there's a situation that you're anticipating will occur from time to time, which will make it impossible for you to retrieve newProductLines at that time, but which you would like the system to handle gracefully otherwise. You could just use null to indicate that the value isn't there, but it's really hard to know which variables might be null and which never should be. It may be wiser to use an optional type to represent that getMoreNewProducts() might not return anything at all, so you can force any consuming code to recognize this possibility and figure out how to deal with it before the project will even compile:
public ActionResult Index(string search)
{
Maybe<string[]> newProductLines = this.getMoreNewProducts();
string[] newNews = this.getMoreNews();
string[] newPromotions = this.getMorePromotions();
Maybe<string[]> fewerProductLines = newProductLines.Select(this.getLessNewProducts);
Disclaimer: I am the author of the Maybe<> class referenced above.
Here are some additional improvements I'd suggest:
Don't use ViewBag. Instead, create a strongly-typed ViewModel so that you can catch errors in your code at compile-time more often:
var viewModel = new ReportModel {
newProductLines = this.getMoreNewProducts(),
newNews = this.getMoreNews(),
...
};
...
return View(viewModel);
Learn to use LINQ. It will simplify a lot of your very complicated code. For example, instead of:
string[] LessNewProducts = new string[arrayCount];
for (int d = 0; d < arrayCount; d++)
{
LessNewProducts[d] = displayProductLines[d];
}
return LessNewProducts;
... you can say:
string[] LessNewProducts = displayProductLines.Take(arrayCount).ToArray();
In fact, I think your entire getLessNewProducts() method can be replaced with this:
return newProductLines
.Where(line => line.Length > 0)
.Select(line => line.Substring(0, Math.Min(line.Length, 250)))
.Take(5);
I'm Developing windows phone 8 application.
In my application i'm using listbox.I bind listbox value form Webservice. Webservice return json format data's.
The webservice return 40 to 50 records.I bind all the values into listbox.
Everthing work fine.Only on first time run.
For example:-
My project page structure.
1.welcomepage
2.Menu Page (it contain six buttons. click on any one particular button it's redirect to sub-menupage)
3.Sub-menupage(Six different page present)
In menu page Hotels button is present . if hotels button is clicked it's navigate to Hotels Page.
Now my problem is:-
First Time - welcomepage -> Menu Page -> HotelSubmenu [List of hotels is bind in listbox from webservice]
Now I goback to Menupage by click on hardwareback button.Now it's in Menu page
If i click again the same Hotels button
It show me the error
e.ExceptionObject {system.OutofMemoryException:Insufficient memory to continue the execution of the program.
[System.outofmemoryException]
Data {system.Collections.ListDictionaryInternal}
HelpLink null
Hresult -2147024882
Message "insufficient memory to continue the execution of the program"
My C# code for bind values in listbox
public void commonbind()
{
try
{
this.loadimg.Visibility = System.Windows.Visibility.Visible;
loadcheck();
string common_url = "http://xxxxxx.com/Service/bussinesscitynamesub.php?bcatid=" + businessid + "&cityname=" + cityname + "&bsubid=" + filterid;
WebClient common_wc = new WebClient();
common_wc.DownloadStringAsync(new Uri(common_url), UriKind.Relative);
common_wc.DownloadStringCompleted += common_wc_DownloadStringCompleted;
}
catch (Exception ex)
{
}
}
void common_wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
try
{
lbbusiness.Items.Clear();
var common_val = e.Result;
if (common_val != "null\n\n\n\n")
{
lbopen = 2;
var jsonconvertvalue = JsonConvert.DeserializeObject<List<common_bindclass>>(common_val);
List<common_bindclass> ls = new List<common_bindclass>();
ls = jsonconvertvalue;
for (int i = 0; i < ls.Count; i++)
{
lbbusiness.Items.Add(ls[i]);
}
this.loadimg.Visibility = System.Windows.Visibility.Collapsed;
loadcheck();
}
else
{
if (lbopen == 0)
{
MessageBoxResult resultmsg = MessageBox.Show("No Result present based on your current Location! " + System.Environment.NewLine + "Now showing result without Location based", "Sorry!", MessageBoxButton.OK);
if (resultmsg == MessageBoxResult.OK)
{
lbbusiness.Items.Clear();
cityname = "";
**commonbind();**
}
else
{
NavigationService.GoBack();
}
}
else if (lbopen == 1)
{
MessageBox.Show("No Result Present In this Categories");
LPfilter.Open();
}
else if (lbopen == 2)
{
MessageBox.Show("No Result Present In this City");
Lpcity.Open();
}
}
}
catch (Exception ex)
{
}
}
I try with following method for solve the memory exception
Try1:-
Clear the List box value before bind every time.
Try2:-
Create the new list every time
common_bindclass bind = new common_bindclass();
foreach (common_bindclass bind in jsonconvertvalue)
{
lbbusiness.Items.Add(bind);
}
I change the above code to
List<common_bindclass> ls = new List<common_bindclass>();
ls = jsonconvertvalue;
for (int i = 0; i < ls.Count; i++)
{
lbbusiness.Items.Add(ls[i]);
}
MY Output For single List
But my try's not help for me .
any one tell me how to solve it. or alternate way .
How to find in which line the error occur .[I try with break point but it's not help me]
I was writing simple refactoring and noticed a strange thing. The comment line before the node I am rewriting disappears after refactoring. Also comments after the node in question are transferred inside the node and break the indentation in the new place. This is very strange and I want to ask if it is a bug in jdt or I did something wrong and oblivious.
For example my code suppose to refactor if-else statements in a way that the shortest branch would appear first.
when I try to refactor this:
// pre
if(a==6) {
a = 5;
return false;
} else {
a++;
}
//post
I get this:
if (!(a==6)) {
a++;
}
//post
else {
a = 5;
return false;
}
The relevant snippet where the refactoring is done:
protected ASTRewrite createRewrite(CompilationUnit cu, SubProgressMonitor pm) {
pm.beginTask("Creating rewrite operation...", 1);
final AST ast = cu.getAST();
final ASTRewrite rewrite = ASTRewrite.create(ast);
cu.accept(new ASTVisitor() {
public boolean visit(IfStatement node) {
if (node.getStartPosition() > selection.getOffset() + selection.getLength() || node.getStartPosition() < selection.getOffset())
return true;
if (node.getElseStatement() == null)
return true;
int thenCount = countNodes(node.getThenStatement());
int elseCount = countNodes(node.getElseStatement());
if(thenCount <= elseCount)
return true;
IfStatement newnode = ast.newIfStatement();
PrefixExpression neg = negateExpression(ast, rewrite, node.getExpression());
newnode.setExpression(neg);
newnode.setThenStatement((org.eclipse.jdt.core.dom.Statement) rewrite.createMoveTarget(node.getElseStatement()));
newnode.setElseStatement((org.eclipse.jdt.core.dom.Statement) rewrite.createMoveTarget(node.getThenStatement()));
rewrite.replace(node, newnode, null);
return true;
}
});
pm.done();
return rewrite;
}
The // pre comment goes away because the parser considers it to be part of the next statement (represented by node), which you replace with newNode. When node goes away, so does the attached comment.
still thinking about why the // post ends up where it does... Try replacing the newNode before setting its then and else statements
I'm trying to find the shortest path of finding friends. If person X wants to connect to person Y, I want to print out the shortest path of friends in order for X to get to Y. Everytime I run the code, I get null as a result.
public void shortest(String first, String target){
HashMap<String, String> prev = new HashMap<String, String>();
Queue<PersonNode> q = new LinkedList<PersonNode>();
PersonNode firstPerson = hash.get(first);
firstPerson.visited = true;
prev.put(first, first + " ");
q.add(firstPerson);
while(!q.isEmpty()){
PersonNode curr = q.remove();
if(!curr.visited){
curr.visited = true;
if(curr.equals(target)){
break;
}
else{
for(int i =0; i < curr.list.size(); i++){
if(curr.list.get(i).visited = false){
q.add(curr.list.get(i));
curr.list.get(i).visited = true;
prev.put(curr.list.get(i).name, prev.get(curr.list.get(i).name) + curr.list.get(i));
}
}
}
if(!curr.equals(target)){
System.out.println("They have no connections");
}
}
}
System.out.println(prev.get(target));
}
Try debugging your code. I see you set firstperson.visited to true outside of the loop. You then pop it from you queue and ignore it because it's true. It's the same inside your loop: you set all visited attributes to true which will cause them to be ignored when they get popped from the queue at runtime
I'm also thinking that the "they have no connections"-part should not be inside the while loop