package com.selenium;
import java.io.FileInputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.io.IOException;
public class Exxcel {
public static void main(String[] args) throws Exception,NullPointerException{
//WebDriver driver= new FirefoxDriver();
//WebElement wb;
String Value;
try{
FileInputStream file= new FileInputStream("C:\\Documents and Settings\\OMEGA\\Desktop\\Test Planning And Documents\\Automation Data.xlsx");
Workbook data=WorkbookFactory.create(file);
Sheet sheet=data.getSheet("Sheet1");
for(int i=1;i<=sheet.getLastRowNum();i++){
Row row = sheet.getRow(i);
if(row != null){
// Putting condition to check row is null or not
for (int j = 1; j < row.getLastCellNum();) {
if (row.getCell(j) != null) {
// Putting condition to check row cell is null or not
String value=row.getCell(j).getStringCellValue();
Value=value;
//String value1=row.getCell(j+1).getStringCellValue();
String[] array= new String[2];
array[0]=Value;
//array[1]=value1;
if( array[0] != null ) {
// Putting condition to check array[] is null or not
System.out.println(array[0]);
//System.out.println(array[1]);
}
}
}
}
}
}catch(NullPointerException n){
n.printStackTrace();
//System.out.println("Null");
}// catch
}//main
}//class
This is the code which i am trying to run but as soon as i click on run buton the entier eclipse stops responding. Don't know why its happening?
It is possible that your loop never ends:
for (int j = 1; j < row.getLastCellNum();) {
I don't see j being incremented anywhere in your code.
An infinite loop on the main GUI thread would have the side-effect to freeze the IDE.
As the OP Shantanu commented, adding an increment j++ was enough to resolve the situation:
for(int j=0; j<=row.getLastRowNumber(); j++) {
...
}
You must put an increment or decrement operater on the second for loop. You have not put any condition in the second loop which is why your program is going in an infinite loop and eclipse becomes slow in performance.
Change your code with:
for(int j=0; j<=row.getLastRowNumber(); j++)
{
//Your Code
}
Related
I have tried to find the time complexity for the below code but I am not sure whether it is right or not. can anyone help me on finding the time complexity for the below code. the code language is JAVA.
code:
// importing the necessary header files for the program
// header files are imported using the keyword import
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
//creating a class called "Partone". class can be created using the keyword class
public class Partone
{
public static void main(String[] args) throws IOException
{
// opening a file named "hikernet1"
File inputFile = new File("hikernet1.txt");
int maxTransmission = 0; //declaring maxTransmission as Integer data type and setting as 0
//reading the content of the file
Scanner reader = new Scanner(inputFile);
// inputCoordinatedAndTransmissionRange
String[] iCATR = reader.useDelimiter("\\A").next().replaceAll("\n", ",").replace("\r", "").split(",");
for (int i = 0; i < Integer.parseInt(iCATR[0]); i++)
{
int transmissions = 0; //declaring transmissions as integer data type and setting is as 0
String[] thisHiker = iCATR[i+1].split(" ");
int transMissionRange = Integer.parseInt(thisHiker[2]);
for (int j = 0; j < Integer.parseInt(iCATR[0]); j++)
{
int distance = (int) Math.sqrt(
Math.pow(Integer.parseInt(thisHiker[0])-Integer.parseInt(iCATR[j+1].split(" ")[0]), 2) + //x2-x1
Math.pow(Integer.parseInt(thisHiker[1])-Integer.parseInt(iCATR[j+1].split(" ")[1]), 2)); //y2-y1
if (distance<=transMissionRange)
{
transmissions++;
}
}
if (transmissions>maxTransmission) //checking the condition
{
maxTransmission = transmissions;
}
}
System.out.println(" The Maximum Transmission: "+maxTransmission);
//the outpit will be displayed in the hikernet1out file
FileWriter fw = new FileWriter("hikernet1out.txt"); //hikernet1out is the name of the output file
fw.write(""+maxTransmission);
fw.close(); //closing the file
reader.close(); //closing all the files
}
} //end of the program
any help would be appreciated much . thanks in advance.
Integer.parseInt(iCATR[0]); retruning any value let consider n.
The inner loop is running n times for every iteration of the outer loop.
The total number of nested loop itration = total number of iteration of outer loop . total number of iteration of inner loop = n * n = n^2
For each iteration nested loop doing O(1) operation.
Total time complexity = O(n^2)*O(1) = O(n^2).
Is there any way to solve sorting web element ? I am getting difficulties while sorting using drag and drop function. My drag and drop is not working, i think my logic is good, but while running code nothing happening...
public void sortable() { // loop for drag and drop is not working...
try {
driver.get("http://jqueryui.com/");
myLibrary.clickButton(By.partialLinkText("Sortable"));
WebElement iframe = driver.findElement(By.xpath("//*[#id='content']/iframe"));
driver.switchTo().frame(iframe);
String temp = "";
Thread.sleep(10 * 1000); //manual work to disorder sortable list prior to start for loop.
Actions action = new Actions(driver);
int i = 1, j = 1;
for (i = 1; i < 8; i = i + 1) {
WebElement sourceText = driver.findElement(By.cssSelector("#sortable > li:nth-child(" + i + ")"));
WebElement dragElement = driver
.findElement(By.cssSelector("#sortable > li:nth-child(" + i + ") > span"));
while (true) {
temp = "Item" + " " + j;
if (temp == sourceText.getText()) {
WebElement targetElement = driver
.findElement(By.cssSelector("#sortable > li:nth-child(" + j + ")"));
action.moveToElement(dragElement).dragAndDrop(dragElement, targetElement).build().perform();
Thread.sleep(1 * 1000);
break;
} else {
if (j == 8) {
break;
} else {
j++;
}
}
}
}
Thread.sleep(5 * 1000);
} catch (Exception e) {
e.printStackTrace();
}
}
Building upon what #JeffC posted as an answer, here's another variant of the same that uses some of the built in capabilities of Java.
We basically use the List.sort() and a Comparator to get this done.
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class SorterSample {
private RemoteWebDriver driver;
#BeforeClass
public void setup() {
driver = new ChromeDriver();
}
#AfterClass
public void cleanup() {
if (driver != null) {
driver.quit();
}
}
#Test
public void testMethod() {
String url = "http://jqueryui.com/sortable/";
driver.get(url);
driver.switchTo().frame(driver.findElement(By.cssSelector("iframe.demo-frame")));
List<WebElement> items = driver.findElements(By.cssSelector("#sortable > li"));
items.sort(
(o1, o2) -> {
int compareValue = o1.getText().compareTo(o2.getText());
if (compareValue < 0) {
new Actions(driver).dragAndDrop(o1, o2).perform();
}
return compareValue;
});
}
}
This was a fun little exercise...
Rather than trying to invent your own sorting code, you should use an established sorting algorithm. I chose bubble sort but you can pick any one you want. If you are just sorting a few items, this should work just fine. It runs in just a few seconds.
The main code
String url = "http://jqueryui.com/sortable/";
driver.get(url);
driver.switchTo().frame(driver.findElement(By.cssSelector("iframe.demo-frame")));
List<WebElement> items = driver.findElements(By.cssSelector("#sortable > li"));
bubbleSort(items);
The bubble sort method
static void bubbleSort(List<WebElement> items)
{
int n = items.size();
boolean swapped;
for (int i = 0; i < n - 1; i++)
{
swapped = false;
for (int j = 0; j < n - i - 1; j++)
{
int compare = items.get(j).getText().compareTo(items.get(j + 1).getText());
if (compare < 0)
{
swap(items.get(j + 1), items.get(j));
swapped = true;
}
}
// break if no elements were swapped
if (swapped == false)
{
break;
}
}
}
and finally the support method to swap items
public static void swap(WebElement source, WebElement target)
{
new Actions(driver).dragAndDrop(source, target).perform();
}
I just ran this code a few times and it's working just fine. It sorts the items in reverse order (so you don't have to mix them up manually). This is not the most efficient way to do this but I wanted to be able to watch the bubble sort work so you see each swap. If you want this to go faster, you can pull the text from the items, sort that list and then line up the elements with their sorted text so you only have to do n swaps.
I´m currently dealing with some Problems concerning dual mouse input. I've looked up several libraries and decided that JInput would do best. Although i was able to get a list of all devices plugged into my laptop, i couldn't retrieve any PollData. The following code only produces 0's:
public static void main(String[] args) {
Controller mouse1 = null;
Controller[] cs = ControllerEnvironment.getDefaultEnvironment().getControllers();
for(int i = 0; i < cs.length; i++) {
if(cs[i].getType() == Type.MOUSE) {
mouse1 = cs[i];
}
}
mouse1.poll();
Component[] comps = mouse1.getComponents();
while(true) {
mouse1.poll();
for(int i = 0; i < comps.length; i++) {
System.out.print(comps[i].getName() + ": ");
System.out.println(comps[i].getPollData());
}
}
}
I also tried out to get KeyBoard-Input with this, same problem. I could get the number of keys, but i was unable to access any information about the key's state.
I hope that someone knows how to solve this problem or has an idea what might be causing it.
Thank you in advance, aquatyp.
I know this is almost a year old, but for the benefit of anyone who finds this through Google like I did...
Make sure you have an OpenGL display initialized (note the if statement is there just to eliminate the flood of messages):
import net.java.games.input.Controller;
import net.java.games.input.ControllerEnvironment;
import net.java.games.input.Mouse;
import net.java.games.input.RawInputEnvironmentPlugin;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
public class Main
{
public static void main(String[] args)
{
try
{
Display.setDisplayMode(new DisplayMode(800,600));
Display.create();
}
catch (LWJGLException e)
{
e.printStackTrace();
System.exit(0);
}
RawInputEnvironmentPlugin rep = new RawInputEnvironmentPlugin();
Mouse mouse;
StringBuilder sb = new StringBuilder();
while (!Display.isCloseRequested())
{
int i = 0;
for (Controller controller : ControllerEnvironment.getDefaultEnvironment().getControllers())
{
if (controller.getType() == Controller.Type.MOUSE)
{
//System.out.println(controller.getName() + " | " + controller.getType());
mouse = (Mouse)controller;
mouse.poll();
i += 1;
if (mouse.getX().getPollData() > 0.0f || mouse.getY().getPollData() > 0.0f)
{
sb.append("[");
sb.append(i);
sb.append("] X=");
sb.append(mouse.getX().getPollData());
sb.append(" Y=");
sb.append(mouse.getY().getPollData());
System.out.println(sb.toString());
sb.setLength(0);
}
}
}
Display.update();
}
}
}
I am trying to read data from a excel sheet but getting NullPointerException every time when reading data at the cell index =6. Put while(value != null) to avoid null values but still got the exception without any output.
I am putting the screen shot of excel sheet from where i am trying to get data.
Code-
package com.selenium;
import java.io.FileInputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.io.IOException;
public class Exxcel {
public static void main(String[] args) throws Exception,NullPointerException{
//WebDriver driver= new FirefoxDriver();
//WebElement wb;
try{
FileInputStream file= new FileInputStream("C:\\Documents and Settings\\OMEGA\\Desktop\\Test Planning And Documents\\Automation Data.xlsx");
Workbook data=WorkbookFactory.create(file);
Sheet sheet=data.getSheet("Sheet1");
for(int i=1;i<=sheet.getLastRowNum();i++){
Row row= sheet.getRow(i);
int j=0;
String value=row.getCell(j).getStringCellValue();
while(value != null){
System.out.println(value);
}//while
while(value == null){
j++;
}
}//for
/*while(j1==9){
String value=row.getCell(j1).getStringCellValue();
System.out.println(value);
}//while2
*/
}catch(NullPointerException n){n.printStackTrace();
System.out.println("Null");
}// catch
}//main
}//class
StackTrace-
Null
java.lang.NullPointerException
at com.selenium.Exxcel.main(Exxcel.java:22)
It's not enough to check that row.getCell(j).getStringCellValue() != null. You should check that row.getCell(j) != null.
In addition, your while loops makes no sense :
The first one will either do nothing or print value forever (since you are not changing value inside the loop).
while(value != null) {
System.out.println(value);
}//while
The second one will either do nothing or increment j forever (since you are not changing value inside the loop).
while(value == null) {
j++;
}
I suggest you replace them with the following code :
Row row = sheet.getRow(i);
if (row != null) {
for (int j = 0; j < row.getLastCellNum(); j++) {
if (row.getCell(j) != null) {
if (row.getCell(j).getCellType() == CELL_TYPE_STRING) {
String value=row.getCell(j).getStringCellValue();
if(value != null) {
System.out.println(value);
}
}
}
}
}
So I'm working on an assignment for my game design class to build a pacman clone, it'll be throughout the semester.
Currently I've got a text file that is the pacman maze
see below :
WWWWWWWWWWWWWWWWWWWWWWWWWWWW
W............WW............W
W.WWWW.WWWWW.WW.WWWWW.WWWW.W
W*WWWW.WWWWW.WW.WWWWW.WWWW*W
W.WWWW.WWWWW.WW.WWWWW.WWWW.W
W..........................W
W.WWWW.WW.WWWWWWWW.WW.WWWW.W
W.WWWW.WW.WWWWWWWW.WW.WWWW.W
W......WW....WW....WW......W
WWWWWW.WWWWW.WW.WWWWW.WWWWWW
WWWWWW.WWWWW.WW.WWWWW.WWWWWW
WWWWWW.WW..........WW.WWWWWW
WWWWWW.WW.WWWWWWWW.WW.WWWWWW
WWWWWW.WW.WWWWWWWW.WW.WWWWWW
..........WWWWWWWW..........
WWWWWW.WW.WWWWWWWW.WW.WWWWWW
WWWWWW.WW.WWWWWWWW.WW.WWWWWW
WWWWWW.WW..........WW.WWWWWW
WWWWWW.WW.WWWWWWWW.WW.WWWWWW
WWWWWW.WW.WWWWWWWW.WW.WWWWWW
W............WW............W
W.WWWW.WWWWW.WW.WWWWW.WWWW.W
W*WWWW.WWWWW.WW.WWWWW.WWWW*W
W...WW................WW...W
WWW.WW.WW.WWWWWWWW.WW.WW.WWW
WWW.WW.WW.WWWWWWWW.WW.WW.WWW
W......WW....WW....WW......W
W.WWWWWWWWWW.WW.WWWWWWWWWW.W
W.WWWWWWWWWW.WW.WWWWWWWWWW.W
W..........................W
WWWWWWWWWWWWWWWWWWWWWWWWWWWW
the idea is that this is read in, line by line by a reader from the java io package and then used to populate a 2d array, I think then I can use a loop to specify where to print images using the paint class with the data in the array.
My problem currently is the paint method, it doesnt seem to be working at all but I cant find what's wrong with it at the moment. Can anyone point me in the right direction?
(My codes formatting has been messed up a tad by indentation required here, I'm also new to the java IO package, first time I've seen exception handling!)
Thanks in advance for any help!
//imports
import java.awt.*;
import java.io.*;
import javax.swing.*;
public class Maze extends JFrame
{
//V.Decleration
private static final Dimension WindowSize = new Dimension (600,600);
static char[][] Amaze = new char[28][31];
//default constructor
public Maze()
{
this.setTitle("Pacman");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension screensize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
int x = screensize.width/2 - WindowSize.width/2;
int y = screensize.height/2 - WindowSize.height/2;
setBounds(x, y, WindowSize.width, WindowSize.height);
setVisible(true);
}
public void paint (Graphics g)
{
String line = null;
try
{
BufferedReader reader = new BufferedReader(new FileReader("G:\\Game Design\\Pacman\\src\\Maze.txt"));
for (int i=0; i<=31; i++)
{
do
{
try
{
line=reader.readLine();
for (int y=0; y<=28; y++)
{
Amaze[y][i]=line.charAt(y);
}
}catch (IOException e) { }
}
while (line!= null);
try
{
reader.close();
} catch (IOException e) { }
}
} catch (FileNotFoundException e) {}
}
//main
public static void main (String [] args)
{
Maze maze = new Maze();
for (int i=0;i<=28;i++)
System.out.print(Amaze[i][31]);
}
}
You are creating an array that is too small for the loop. Namely: new char[28][31]; will only allow for a maximum index of 27 and 30. Your for loops are:
for (int i=0; i<=31; i++)
for (int y=0; y<=28; y++)
Use i<31 and y<28, or increase your array to be [29][32]. Either one of these should solve your current problem.
Three suggestions:
It may be less misleading to separate your functions to do just one job at a time. So there should be a function to read the file and then another to paint the results.
Put more System.out.println() statements in your code when you're trying to debug. That's a good way to check whether each part did what you intended. For example, printing the line variable after reading it in would at least let you know whether you were reading the file correctly.
Always print out your exceptions. They will tell you what went wrong and where.
That said, this code will load and print your maze:
import java.io.*;
public class Read2DArray {
private final int WIDTH = 28;
private final int HEIGHT = 31;
private char[][] maze = new char[WIDTH][HEIGHT];
public static void main(String[] args) {
Read2DArray array = new Read2DArray();
array.loadFile("maze.txt");
array.printArray();
}
public void loadFile(String fname) {
try {
BufferedReader reader = new BufferedReader(new FileReader(fname));
String line;
int col = 0, row = 0;
while((line = reader.readLine()) != null && row < HEIGHT) {
for(col = 0; col < line.length() && col < WIDTH; col++) {
maze[col][row] = line.charAt(col);
}
row++;
}
reader.close();
} catch(IOException e) {
e.printStackTrace();
}
}
public void printArray() {
for(int row = 0; row < HEIGHT; row++) {
for(int col = 0; col < WIDTH; col++) {
System.out.print(maze[col][row]);
}
System.out.println();
}
}
}