Below is the code that I wrote:
import static java.lang.System.out;
import java.util.Scanner;
import java.util.ArrayList;
class Uni{
static public void main(String...args){
Scanner sc = new Scanner(System.in);
ArrayList<Integer>list = new ArrayList<Integer>();
for(int a=0,i=0;list.get(i)!=42;i++){
a=sc.nextInt();
list.add(i,a);
}
for(int i=0;i<list.size();i++){
out.println(list.get(i));
}
}
}
And this is the error im getting:
Execution failed.
java.lang.IndexOutOfBoundsException : Index: 0, Size: 0
Stack Trace:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at Uni.main(Uni.java:8)
Can you please help with what to do?
Maybe you wanted to use a while cycle? It's much easier to initialize the list.
Furthermore, your code is checking if list.get(i) is not equal to 42, but you cannot do that because your list at the index 0 is still null.
A solution could be:
import static java.lang.System.out;
import java.util.Scanner;
import java.util.ArrayList;
class Uni{
static public void main(String...args){
Scanner sc = new Scanner(System.in);
ArrayList<Integer>list = new ArrayList<Integer>();
int i = 0;
while(i!=42) {
list.add(i++,sc.nextInt());
}
for(int i=0;i<list.size();i++)
{
out.println(list.get(i));
}
}
}
EDIT: to stop after the Input is 42:
import static java.lang.System.out;
import java.util.Scanner;
import java.util.ArrayList;
class Uni{
static public void main(String...args){
Scanner sc = new Scanner(System.in);
ArrayList<Integer>list = new ArrayList<Integer>();
int i = 0
while (true) {
int in = sc.nextInt();
if (in==42) break;
list.add(i++,sc.nextInt())
}
for(int i=0;i<list.size();i++)
{
out.println(list.get(i));
}
}
}
Related
I am trying to fetch the data using data provider in selenium from an excel sheet. When the data is returned/passed on to the caller function, i get null values for the first time even though loop begins from the second row having the actual data. I am not sure why this is happening.
package pageobjectmodel;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import Utils.ReadingExcelfile;
import Utils.TestBase;
import pagebasedexecution.LinkedInloginPage;
public class LinkedInLoginTest extends TestBase
{
//public static ReadExcel excelfile;
public static ReadingExcelfile excelfile;
LinkedInloginPage loginPage;
public LinkedInLoginTest() throws IOException
{
super();
}
#BeforeMethod
public void Setup() throws IOException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
{
BrowserSetup();
loginPage = new LinkedInloginPage();
}
#Test(dataProvider="TestData")
public void LoginTest(String uname, String password) throws InterruptedException
{
// System.out.println("received data is --- " +uname + " , " + password);
loginPage.LoginIntoAccount(uname, password);
String title = loginPage.VerifyTitle();
Assert.assertEquals(title, "LinkedIn", "Unable to login: invalid credentials");
Thread.sleep(5000);
}
/*#Test(priority=2)
public void VerifyloginPageTitleTest() throws InterruptedException
{
String title = loginPage.VerifyTitle();
Assert.assertEquals(title, "LinkedIn", "Unable to login: invalid credentials");
}*/
#DataProvider
public Object[][] TestData() throws IOException
{
excelfile = new ReadingExcelfile(System.getProperty("user.dir")+"\\src\\main\\java\\testData\\LinkedIn.xlsx");
int rows = excelfile.RowCount(1);
int colm = excelfile.TotalColm("LoginPage", 0);
Object[][] credentials = new Object[rows][colm];
for(int i = 1; i < rows; i++)
{
for(int j = 0; j<colm; j++)
{
credentials[i][j] = excelfile.getdata("LoginPage", i, j);
System.out.println("Fetched data from excel sheet is -- "+credentials[i][j]);
}
}
return credentials;
}
#AfterMethod
public void closebrowser()
{
System.out.println("quitting browser");
driver.quit();
}
}
Even though i am fetching the data from second row, somehow it's fetching the data from first row(column names) and first set of data is returned as null, null. i have provided the screenshot of error console and highlighted the error portion. Any help is appreciated.
Thanks
This is because here
Object[][] credentials = new Object[rows][colm];
you are creating array of object with number of rows and colums present in your sheet but you are inserting value in this array from second row So In first row it is taking default null values.
Replace code :
for(int j = 0; j<colm; j++)
{
credentials[i][j] = excelfile.getdata("LoginPage", i, j);
System.out.println("Fetched data from excel sheet is -- "+credentials[i][j]);
}
With
for(int j = 0; j<colm; j++)
{
credentials[i-1][j] = excelfile.getdata("LoginPage", i, j);
System.out.println("Fetched data from excel sheet is -- "+credentials[i-1][j]);
}
I am new to selenium and I am trying to verify selected date in datepicker field but when I am executing this program it is printing else section, which it should not show. Kindly help to know where I am going wrong.
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class tripadviser {
static WebDriver driver;
public static void main(String[] args) {
String start_date = "29-March 2017";
String[] splitter = start_date.split("-");
String start_day = splitter[0];
String start_month = splitter[1];
System.setProperty("webdriver.chrome.driver", "D:\\rakesh\\software\\selenium browser\\New folder\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("https://www.tripadvisor.in/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.findElement(By.id("rdoFlights")).click();
WebElement datepicker_ele = driver.findElement(By.id("metaCheckInSpan"));
datepicker_ele.click();
select_date_fun(start_day, start_month);
WebElement check_in_ele = driver.findElement(By.id("checkIn"));
String datepicker_expected_str = "29/3/2017";
if (check_in_ele.getText().equals(datepicker_expected_str)) {
System.out.println("Date selection is done succesfully");
} else {
System.out.println("Something went wrong");
}
driver.close();
}
public static void select_date_fun(String day, String month_year) {
List < WebElement > month_ele = driver.findElements(By.xpath(".//div[#class='calendar']/div[#class='month']/table/thead/tr/th[#class='caption']"));
for (int i = 0; i < month_ele.size(); i++) {
//System.out.println(month_ele.get(i).getText());
if (month_ele.get(i).getText().equals(month_year)) {
List < WebElement > day_ele = driver.findElements(By.xpath(".//div[#class='calendar']/div[#class='month'][1]/table/tbody/tr/td/a"));
for (WebElement j: day_ele) {
//System.out.println(j.getText());
if (j.getText().equals(day)) {
j.click();
return;
}
}
}
}
}
}
My question is resolved by using .getAttribute("value") instead of .getText()
I am trying to print names of all result links on the first 5 pages on Google.com
Scenario is,
1) Go to www.google.com and search for something.
2) Print names of all result links on first 5 pages
I am able to print all the result links of first page and click next page link. But second page links are not printing. I think the reason may be with the xpath changing in second page. If so, how do I print all the links of 2nd 3rd 4th and 5th page.
Kindly help me in solving this solution.
package com;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
public class Exercise2 {
static WebDriver d;
public static void main(String[] args) throws InterruptedException {
ProfilesIni prop = new ProfilesIni();
FirefoxProfile seleniumProfile = prop.getProfile(("Selenium"));
d = new FirefoxDriver();
d.manage().window().maximize();
d.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
d.get("http://www.google.com");
Thread.sleep(5000);
d.findElement(By.name("q")).sendKeys("Selenium");
d.findElement(By.name("q")).sendKeys(Keys.ENTER);
Thread.sleep(5000);
//Print names of all result links on first page.
String part1 = "//div[#id='rso']/div[2]/div[";
String part2 = "]/div/h3/a";
for(int i=2;i<=5;i++){
String part3 = "//div[#id='navcnt']/table/tbody/tr/td[";
String part4 = "]";
int a = 1;
while(isElementPresent(part1+a+part2)){
String text = d.findElement(By.xpath(part1+a+part2)).getText();
System.out.println(text);
a++;
}
Thread.sleep(5000);
System.out.println("*************Next Page**********");
Thread.sleep(5000);
d.findElement(By.xpath(part3+i+part4)).click();
}
}
public static boolean isElementPresent(String xpathexp){
List<WebElement> allList = d.findElements(By.xpath(xpathexp));
//WebElement nextPages = d.findElement(By.xpath(nextPage1));
if(allList.size()==0)
{
return false;
}else{
return true;
}
}
}
List<WebElements> links = driver.findElements(By.tagName("a"));
for(int i = 0 ; i < 5 ; i ++)
{
string firstLink = links[i].getAttribute("href");
}
try following code.
package javaselenium;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
/**
*
* #author Muhammad USman
*/
public class JavaSelenium {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Hello Wrold");
GetUrls("Selenium");
}
public static ArrayList GetUrls(String keyWord)
{
FirefoxDriver driver;
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
driver.get("https://www.google.com/?gws_rd=ssl");
WebElement qElement;
qElement = driver.findElement(By.name("q"));
qElement.sendKeys(keyWord);
qElement.sendKeys(Keys.ENTER);
try {
Thread.sleep(3*1000);
} catch (InterruptedException ex) {
Logger.getLogger(JavaSelenium.class.getName()).log(Level.SEVERE, null, ex);
}
//give number how mange pages you want to crawl
int nPageToCrawl=5;
List links;
links=new ArrayList();
for (int i = 0; i < nPageToCrawl; i++) {
if(i>0)
{
System.out.println("***Click on Next Page***");
//Click on Next Page
driver.findElement(By.id("pnnext")).click();
try {
Thread.sleep(3*1000);
} catch (InterruptedException ex) {
Logger.getLogger(JavaSelenium.class.getName()).log(Level.SEVERE, null, ex);
}
}
//it will get all links of pageLinks
List<WebElement> pageLinks = driver.findElements(By.cssSelector(".r>a"));
for (WebElement pageLink : pageLinks) {
links.add(pageLink.getAttribute("href"));
System.out.println(pageLink.getText());
System.out.println(pageLink.getAttribute("href"));
}
}
//close browser
driver.quit();
return (ArrayList) links;
}
}
if any issue then let me know.
This question already has answers here:
Compile code fully in memory with javax.tools.JavaCompiler [duplicate]
(7 answers)
Closed 6 years ago.
I want to treat a String as a Java file then compile and run it. In other words, use Java as a script language.
To get better performance, we should avoid writing .class files to disk.
This answer is from one of my blogs, Compile and Run Java Source Code in Memory.
Here are the three source code files.
MemoryJavaCompiler.java
package me.soulmachine.compiler;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.tools.*;
/**
* Simple interface to Java compiler using JSR 199 Compiler API.
*/
public class MemoryJavaCompiler {
private javax.tools.JavaCompiler tool;
private StandardJavaFileManager stdManager;
public MemoryJavaCompiler() {
tool = ToolProvider.getSystemJavaCompiler();
if (tool == null) {
throw new RuntimeException("Could not get Java compiler. Please, ensure that JDK is used instead of JRE.");
}
stdManager = tool.getStandardFileManager(null, null, null);
}
/**
* Compile a single static method.
*/
public Method compileStaticMethod(final String methodName, final String className,
final String source)
throws ClassNotFoundException {
final Map<String, byte[]> classBytes = compile(className + ".java", source);
final MemoryClassLoader classLoader = new MemoryClassLoader(classBytes);
final Class clazz = classLoader.loadClass(className);
final Method[] methods = clazz.getDeclaredMethods();
for (final Method method : methods) {
if (method.getName().equals(methodName)) {
if (!method.isAccessible()) method.setAccessible(true);
return method;
}
}
throw new NoSuchMethodError(methodName);
}
public Map<String, byte[]> compile(String fileName, String source) {
return compile(fileName, source, new PrintWriter(System.err), null, null);
}
/**
* compile given String source and return bytecodes as a Map.
*
* #param fileName source fileName to be used for error messages etc.
* #param source Java source as String
* #param err error writer where diagnostic messages are written
* #param sourcePath location of additional .java source files
* #param classPath location of additional .class files
*/
private Map<String, byte[]> compile(String fileName, String source,
Writer err, String sourcePath, String classPath) {
// to collect errors, warnings etc.
DiagnosticCollector<JavaFileObject> diagnostics =
new DiagnosticCollector<JavaFileObject>();
// create a new memory JavaFileManager
MemoryJavaFileManager fileManager = new MemoryJavaFileManager(stdManager);
// prepare the compilation unit
List<JavaFileObject> compUnits = new ArrayList<JavaFileObject>(1);
compUnits.add(fileManager.makeStringSource(fileName, source));
return compile(compUnits, fileManager, err, sourcePath, classPath);
}
private Map<String, byte[]> compile(final List<JavaFileObject> compUnits,
final MemoryJavaFileManager fileManager,
Writer err, String sourcePath, String classPath) {
// to collect errors, warnings etc.
DiagnosticCollector<JavaFileObject> diagnostics =
new DiagnosticCollector<JavaFileObject>();
// javac options
List<String> options = new ArrayList<String>();
options.add("-Xlint:all");
// options.add("-g:none");
options.add("-deprecation");
if (sourcePath != null) {
options.add("-sourcepath");
options.add(sourcePath);
}
if (classPath != null) {
options.add("-classpath");
options.add(classPath);
}
// create a compilation task
javax.tools.JavaCompiler.CompilationTask task =
tool.getTask(err, fileManager, diagnostics,
options, null, compUnits);
if (task.call() == false) {
PrintWriter perr = new PrintWriter(err);
for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
perr.println(diagnostic);
}
perr.flush();
return null;
}
Map<String, byte[]> classBytes = fileManager.getClassBytes();
try {
fileManager.close();
} catch (IOException exp) {
}
return classBytes;
}
}
MemoryJavaFileManager.java
package me.soulmachine.compiler;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.nio.CharBuffer;
import java.util.HashMap;
import java.util.Map;
import javax.tools.FileObject;
import javax.tools.ForwardingJavaFileManager;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.JavaFileObject.Kind;
import javax.tools.SimpleJavaFileObject;
/**
* JavaFileManager that keeps compiled .class bytes in memory.
*/
#SuppressWarnings("unchecked")
final class MemoryJavaFileManager extends ForwardingJavaFileManager {
/** Java source file extension. */
private final static String EXT = ".java";
private Map<String, byte[]> classBytes;
public MemoryJavaFileManager(JavaFileManager fileManager) {
super(fileManager);
classBytes = new HashMap<>();
}
public Map<String, byte[]> getClassBytes() {
return classBytes;
}
public void close() throws IOException {
classBytes = null;
}
public void flush() throws IOException {
}
/**
* A file object used to represent Java source coming from a string.
*/
private static class StringInputBuffer extends SimpleJavaFileObject {
final String code;
StringInputBuffer(String fileName, String code) {
super(toURI(fileName), Kind.SOURCE);
this.code = code;
}
public CharBuffer getCharContent(boolean ignoreEncodingErrors) {
return CharBuffer.wrap(code);
}
}
/**
* A file object that stores Java bytecode into the classBytes map.
*/
private class ClassOutputBuffer extends SimpleJavaFileObject {
private String name;
ClassOutputBuffer(String name) {
super(toURI(name), Kind.CLASS);
this.name = name;
}
public OutputStream openOutputStream() {
return new FilterOutputStream(new ByteArrayOutputStream()) {
public void close() throws IOException {
out.close();
ByteArrayOutputStream bos = (ByteArrayOutputStream)out;
classBytes.put(name, bos.toByteArray());
}
};
}
}
public JavaFileObject getJavaFileForOutput(JavaFileManager.Location location,
String className,
Kind kind,
FileObject sibling) throws IOException {
if (kind == Kind.CLASS) {
return new ClassOutputBuffer(className);
} else {
return super.getJavaFileForOutput(location, className, kind, sibling);
}
}
static JavaFileObject makeStringSource(String fileName, String code) {
return new StringInputBuffer(fileName, code);
}
static URI toURI(String name) {
File file = new File(name);
if (file.exists()) {
return file.toURI();
} else {
try {
final StringBuilder newUri = new StringBuilder();
newUri.append("mfm:///");
newUri.append(name.replace('.', '/'));
if(name.endsWith(EXT)) newUri.replace(newUri.length() - EXT.length(), newUri.length(), EXT);
return URI.create(newUri.toString());
} catch (Exception exp) {
return URI.create("mfm:///com/sun/script/java/java_source");
}
}
}
}
MemoryClassLoader.java
package me.soulmachine.compiler;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
/**
* ClassLoader that loads .class bytes from memory.
*/
final class MemoryClassLoader extends URLClassLoader {
private Map<String, byte[]> classBytes;
public MemoryClassLoader(Map<String, byte[]> classBytes,
String classPath, ClassLoader parent) {
super(toURLs(classPath), parent);
this.classBytes = classBytes;
}
public MemoryClassLoader(Map<String, byte[]> classBytes, String classPath) {
this(classBytes, classPath, ClassLoader.getSystemClassLoader());
}
public MemoryClassLoader(Map<String, byte[]> classBytes) {
this(classBytes, null, ClassLoader.getSystemClassLoader());
}
public Class load(String className) throws ClassNotFoundException {
return loadClass(className);
}
public Iterable<Class> loadAll() throws ClassNotFoundException {
List<Class> classes = new ArrayList<Class>(classBytes.size());
for (String name : classBytes.keySet()) {
classes.add(loadClass(name));
}
return classes;
}
protected Class findClass(String className) throws ClassNotFoundException {
byte[] buf = classBytes.get(className);
if (buf != null) {
// clear the bytes in map -- we don't need it anymore
classBytes.put(className, null);
return defineClass(className, buf, 0, buf.length);
} else {
return super.findClass(className);
}
}
private static URL[] toURLs(String classPath) {
if (classPath == null) {
return new URL[0];
}
List<URL> list = new ArrayList<URL>();
StringTokenizer st = new StringTokenizer(classPath, File.pathSeparator);
while (st.hasMoreTokens()) {
String token = st.nextToken();
File file = new File(token);
if (file.exists()) {
try {
list.add(file.toURI().toURL());
} catch (MalformedURLException mue) {}
} else {
try {
list.add(new URL(token));
} catch (MalformedURLException mue) {}
}
}
URL[] res = new URL[list.size()];
list.toArray(res);
return res;
}
}
Explanations:
In order to represent a Java source file in memory instead of disk, I defined a StringInputBuffer class in the MemoryJavaFileManager.java.
To save the compiled .class files in memory, I implemented a class MemoryJavaFileManager. The main idea is to override the function getJavaFileForOutput() to store bytecodes into a map.
To load the bytecodes in memory, I have to implement a customized classloader MemoryClassLoader, which reads bytecodes in the map and turn them into classes.
Here is a unite test.
package me.soulmachine.compiler;
import org.junit.Test;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import static org.junit.Assert.assertEquals;
public class MemoryJavaCompilerTest {
private final static MemoryJavaCompiler compiler = new MemoryJavaCompiler();
#Test public void compileStaticMethodTest()
throws ClassNotFoundException, InvocationTargetException, IllegalAccessException {
final String source = "public final class Solution {\n"
+ "public static String greeting(String name) {\n"
+ "\treturn \"Hello \" + name;\n" + "}\n}\n";
final Method greeting = compiler.compileStaticMethod("greeting", "Solution", source);
final Object result = greeting.invoke(null, "soulmachine");
assertEquals("Hello soulmachine", result.toString());
}
}
Reference
JavaCompiler.java from Cloudera Morphlines
How to create an object from a string in Java (how to eval a string)?
InMemoryJavaCompiler
Java-Runtime-Compiler
动态的Java - 无废话JavaCompilerAPI中文指南
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.highgui.VideoCapture;
import org.opencv.objdetect.CascadeClassifier;
public class WebCam extends JPanel implements ActionListener{
private BufferedImage image;
public JButton button = new JButton("capture");
int count = 1;
public WebCam() {
super();
button.addActionListener((ActionListener) this);
this.add(button);
}
public BufferedImage getImage() {
return image;
}
public void setimage(BufferedImage newimage) {
image = newimage;
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (this.image == null) {
return;
}
g.drawImage(this.image, 0, 0, this.image.getWidth(), this.image.getHeight(), null);
}
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame("face capture");
frame.setSize(300,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
CascadeClassifier faceDetector = new CascadeClassifier("C:\\opencv\\sources\\data\\lbpcascades\\lbpcascade_frontalface.xml");
WebCam anan = new WebCam();
frame.add(anan);
frame.setVisible(true);
Mat webcam_image = new Mat();
MatToBufImg mat2Buf = new MatToBufImg();
VideoCapture capture = null;
try {
capture = new VideoCapture(0);
}
catch (Exception e){
}
if (capture.open(0)) {
while (true) {
capture.read(webcam_image);
if (!webcam_image.empty()) {
frame.setSize(webcam_image.width(), webcam_image.height());
MatOfRect faceDetections = new MatOfRect();
faceDetector.detectMultiScale(webcam_image, faceDetections);
for (Rect rect : faceDetections.toArray()) {
Core.rectangle(webcam_image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0));// mat2Buf, mat2Buf);
}
System.out.println("...............face detected: " + faceDetections.toArray().length);
if (faceDetections.toArray().length == 0) {
System.out.println("Face not detected!");
}
mat2Buf.setMatrix(webcam_image, ".jpg");
anan.setimage(mat2Buf.getBufferedImage());
anan.repaint();
}
else {
System.out.println("problem");
}
}
}
capture.release();
}
#Override
public void actionPerformed(ActionEvent e){
System.out.println("hellohellohellohellohello");
int width = 943;
int height = 640;
BufferedImage image = null;
File f = null;
String ans = JOptionPane.showInputDialog(null, "Color/Grey");
System.out.println(ans);
BufferedImage bi = image;
ImageIcon ii = null;
Image newimg = bi.getScaledInstance(320, 220, java.awt.Image.SCALE_SMOOTH);
ii = new ImageIcon(newimg);
Image i2 = ii.getImage();
image = new BufferedImage(i2.getWidth(null), i2.getHeight(null), BufferedImage.SCALE_SMOOTH);
image.getGraphics().drawImage(i2, 0, 0, null);
RenderedImage resim = null;
if (i2 instanceof RenderedImage) {
resim = (RenderedImage) i2;
} else {
BufferedImage anlikResim = null;
if (!ans.equalsIgnoreCase("color")) {
anlikResim = new BufferedImage(
ii.getIconWidth(),
ii.getIconHeight(),
BufferedImage.TYPE_BYTE_GRAY);
} else {
anlikResim = new BufferedImage(
ii.getIconWidth(),
ii.getIconHeight(),
BufferedImage.SCALE_SMOOTH);
}
Graphics2D g = anlikResim.createGraphics();
g.drawImage(i2, 0, 0, null);
g.dispose();
resim = anlikResim;
}
try {
f = new File("C:\\opencv\\build\\java\\x64\\");
ImageIO.write(resim, "jpg", f);
System.out.println("yes");
} catch (Exception ex) {
}
}
}
I am working on a face detection project. It used to work perfectly fine but suddenly ceased to work properly. When I run the program it gives a NullPointerException at line 120. How can I fix this problem?