So I have my BufferedImages:
private BufferedImage sdk1, sdk2, sdk3, sdk4, sdk5, sdk6, sdk7, sdk8, sdk9, sdk10, bc;
And my Array values set:
ArrayList<Card> deck1 = new ArrayList(50);
deck1.add(CardList.Spade);
I was wondering, can I assign an image to "Spade" in my Array list? So when it's used on input of the Scanner, it will display an image in a JFrame.
Scanner monSummon = new Scanner(System.in);
int whichMonsterPOS1 = monSummon.nextInt();
Sorry if I can't explain it anymore, and thanks in advance.
You Could
Use some kind of Map, keyed to an instance of Card...
private Map cardImages;
//...
cardImages = new HashMap<Card, BufferedImage>(25);
//...
Card card = ...;
sdk1 = ...;
cardImages.put(card, sdk1);
You Could
Provide a Image property for your Card, this would allow you to create a specific implementation of the required card, supplying the image property directly, for example...
public class AceOfSpadesCard extends Card {
private BufferedImage img;
public AceOfSpadesCard() {
img = ...;
}
public BufferedImage getImage() {
return img;
}
}
In this case, I would make Card abstract and make the getImage method abstract
Or, if that's to much, simply supply a parameter via the Cards constructor.
An example Card class instance that also contains references for the Image to be drawn. Then it's just a matter of putting a set of Cards in an ArrayList (or build a Deck model you can then manipulate) and calling paint on the Card's bufferedImage.
package model.playing;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import model.AbstractCard;
public class PlayingCard extends AbstractCard {
private String[] values = {"ace", "two", "three", "four", "five", "six", "seven",
"eight", "nine", "ten", "jack", "queen", "king"};
private BufferedImage drawableTarget;
private BufferedImage drawableBackTarget;
public PlayingCard(String suit, int value, String desc) throws Exception {
setFlipped(false);
setSuit(suit);
if(null == getSuit()) {
throw new Exception("Suit not found!");
} else if(getSuit().equals("joker")) {
throw new Exception("That's not how you create a joker!");
}
if(value < 14) {
setValue(value);
} else {
throw new Exception("Invalid value, expecting 13 or less!");
}
setDescription(desc);
}
// removed Joker instantiation to keep short
public BufferedImage returnDrawable() {
URL url = null;
BufferedImage img = null;
if(isFlipped()) {
if(null != getDrawableTarget()) {
img = getDrawableTarget();
} else {
url = getClass().getResource("/suits/" + getSuit()
+ "/" + getValues()[getValue() - 1] + ".png");
try {
img = ImageIO.read(url);
setDrawableTarget(img);
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
if(null != getDrawableBackTarget()) {
img = getDrawableBackTarget();
} else {
url = getClass().getResource("/suits/back.png");
try {
img = ImageIO.read(url);
setDrawableBackTarget(img);
} catch (IOException e) {
e.printStackTrace();
}
}
}
return img;
}
// removed all getters and setters to save on space; they're not important
}
Related
My task is to create random villain object and write to file. Then I create class that for each created villain will create appropriate superHero and rewrite file to new folder.I use pattern to catch required stats and matcher to create hero object with same stats. However if Villain objects is more than one, my code creates hero only for first one...
In the attached example code how can I create superHero for each Villain if there is more than one line of villains.
Thanks for help
public class ShieldMonitoring {
private static final Pattern VILLAIN_LINE = Pattern.compile("Villain .* with superpower (.*) at level (.*)");
public static void main(String[] args) {
List<String> lines = loadFromFile();
if (lines.isEmpty()) {
} else {
System.out.println(lines.size()-1+" people saved by:");
}
SuperHero hero = findHero(lines);
if(hero != null) {
try (BufferedWriter output = new BufferedWriter(new FileWriter("Battlezone/battle-zone-1.txt", true))) {
output.write("Defeated by");
output.newLine();
output.write(hero.toString());
output.newLine();
System.out.println(hero.toString());
} catch (IOException e) {
System.out.println(e.getMessage());
}
new File("Battlezone/battle-zone-1.txt").renameTo(new File("Saved-the-world-again/battle-zone-1.txt"));
}
}
private static SuperHero findHero(List<String> lines) {
for (String line : lines) {
Matcher matcher = VILLAIN_LINE.matcher(line);
if (matcher.matches()) {
String power = matcher.group(1);
int level = Integer.valueOf(matcher.group(2));
SuperThing superThing = new SuperThing();
for(SuperHero hero : superThing.getHero()) {
if(hero.getHeroLevel() == level && hero.getSuperpower().equals(power)) {
return hero;
}
}
}
}
return null;
}
public static List<String> loadFromFile() {
try {
File VillainFile = new File("Battlezone/battle-zone-1.txt");
if (!VillainFile.exists()) {
return Collections.emptyList();
}
try (BufferedReader buffReader = new BufferedReader(new FileReader(VillainFile))) {
return buffReader.lines()
.collect(Collectors.toList());
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
return Collections.emptyList();
}
}
}
SuperHero hero = findHero(lines);
In the above line, you are just finding one hero for all the lines/villains. Essentially, if you need to find a hero for every line/villain, you must modify the method to find and return heroes (a list of SuperHero objects). So you can modify the above line as:
List<SuperHero> hero = findHeroes(lines);
And implement the findHeroes method similarly, by iterating over the lines, adding a hero to a list and returning the list of heroes as below:
private static List<SuperHero> findHeroes(List<String> lines) {
List<SuperHero> heroes = new ArrayList<SuperHero>();
for (String line : lines) {
Matcher matcher = VILLAIN_LINE.matcher(line);
if (matcher.matches()) {
String power = matcher.group(1);
int level = Integer.valueOf(matcher.group(2));
SuperThing superThing = new SuperThing();
for(SuperHero hero : superThing.getHero()) {
if(hero.getHeroLevel() == level && hero.getSuperpower().equals(power)) {
heroes.add(hero);
}
}
}
}
return heroes;
}
I am doing a memory game and in one of my method, I'm trying to create all cards by using File, but it could not run. It always goes to "Picture path is empty", but I want it to run.
/*
Create all Cards.
*/
public static List<Card> createAllCards(String dirPath){
//System.out.println("create all cards");
List<Card> cardList = new ArrayList<>();
File file = new File(dirPath);
File[] pictures = file.listFiles();
//System.out.println("file:" + Arrays.toString(pictures));
int index;
String type = "";
String cardPath;
if (pictures != null){
for (File picture : pictures) {
index = picture.getName().lastIndexOf(".");
if (picture.isFile()){
if (index > 0) {
type = picture.getName().substring(index + 1);
System.out.println("output:" + type);
if (type.equals("png")){
cardPath = picture.getPath();
//cardPath = cardPath.replaceAll("\\\\","\\\\\\\\");
cardList.add(new Card(picture.getName(),cardPath));
}
}
}
}
}else {
System.out.println("Picture path is empty");
}
return cardList;
}
}
The java.io.File class is obsolete. The java.nio.file package is its replacement.
The File class was part of Java 1.0 and did a poor job of reporting errors. Many of its methods return null or false, which tells you nothing about what actually went wrong. The classes in java.nio.file will actually throw exceptions telling you exactly what went wrong.
Specifically, you want to use the Path and Files classes:
try (DirectoryStream<Path> pictures =
Files.newDirectoryStream(Paths.get(dirPath), "*.png")) {
for (Path picture : pictures) {
if (Files.isRegularFile(picture)) {
cardList.add(
new Card(picture.getFileName().toString(), cardPath));
}
}
} catch (IOException e) {
e.printStackTrace();
}
This probably won’t make your program work, but it will give you the information you need to resolve the problem.
Okay, I used your code and modified this, as per your requirement.
Have a look:
NOTE: My photos folder is in the room directory
import java.io.File;
import java.util.ArrayList;
import java.util.List;
class Card{
String photoName,cardPath;
public Card(String name, String cardPath2) {
this.photoName = name;
this.cardPath = cardPath2;
}
}
public class readPhotos {
public static List<Card> createAllCards(String dirPath){
//System.out.println("create all cards");
List<Card> cardList = new ArrayList<>();
File file = new File(dirPath);
File[] pictures = file.listFiles();
//System.out.println("file:" + Arrays.toString(pictures));
int index;
String type = "";
String cardPath;
if (pictures != null){
for (File picture : pictures) {
index = picture.getName().lastIndexOf(".");
if (picture.isFile()){
if (index > 0) {
type = picture.getName().substring(index + 1);
System.out.println("output:" + type);
if (type.equals("png")){
cardPath = picture.getPath();
//cardPath = cardPath.replaceAll("\\\\","\\\\\\\\");
cardList.add(new Card(picture.getName(),cardPath));
}
}
}
}
}else {
System.out.println("Picture path is empty");
}
return cardList;
}
public static void main(String...args)
{
List<Card> cardList = readPhotos.createAllCards("./photos/");
System.out.println(cardList);
}
}
add your photos path accordingly... when calling the method readPhotos.createAllCards("./photos/");
I am trying to save a javafx.scene.shape.Path to a file (at least its elements) however since Path is non-serializable and its PathElement as well it has proven very difficult.
Could someone inform me of a way to either convert the object to a String (preferred), JSON or something else?
Here are all the ways I have tried saving the object:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import javafx.scene.shape.Path;
import javafx.scene.shape.Polygon;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
class Test {
public static void main(String[] args) {
GsonBuilder builder = new GsonBuilder();
Path path;
Gson gson = builder.create();
{
Rectangle rectangle = new Rectangle(100, 100);
Polygon polygon = new Polygon(0, 0, 50, 50, 0, 50);
path = (Path) Shape.subtract(rectangle, polygon);
}
try {
String completePathObject = gson.toJson(path);
System.out.println(completePathObject);
} catch (IllegalArgumentException e) {
e.printStackTrace();
// java.lang.IllegalArgumentException: class com.sun.javafx.util.WeakReferenceQueue$ListEntry declares multiple JSON fields named next
}
try {
String pathObjectElements = gson.toJson(path.getElements());
System.out.println(pathObjectElements);
} catch (IllegalArgumentException e) {
e.printStackTrace();
// java.lang.IllegalArgumentException: class com.sun.javafx.util.WeakReferenceQueue$ListEntry declares multiple JSON fields named next
}
try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("test.set"))) {
objectOutputStream.writeObject(path);
} catch (IOException e) {
e.printStackTrace();
// java.io.NotSerializableException: javafx.scene.shape.Path
}
try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("test.set"))) {
objectOutputStream.writeObject(path.getElements());
} catch (IOException e) {
e.printStackTrace();
// java.io.NotSerializableException: javafx.scene.shape.Path$2
}
}
}
Nodes contain a lot of properties you'd need to convert to a form that can be written to a file.
Since your last attempt indicates you'll be satisfied with writing the path elements to the file, you could convert the PathElements to parts of a SVG path and also implement logic for parsing the elements PathElements from a svg path string.
The following doesn't accept all possible SVG paths and may accept some invalid paths:
public class SVGConverter {
private enum PathElementType {
ARC('a', ArcTo.class, ArcTo::new,
ArcTo::radiusXProperty,
ArcTo::radiusYProperty,
ArcTo::XAxisRotationProperty,
ArcTo::largeArcFlagProperty,
ArcTo::sweepFlagProperty,
ArcTo::xProperty,
ArcTo::yProperty),
CLOSE_PATH('z', ClosePath.class, ClosePath::new),
CUBIC_CURVE('c', CubicCurveTo.class, CubicCurveTo::new,
CubicCurveTo::controlX1Property,
CubicCurveTo::controlY1Property,
CubicCurveTo::controlX2Property,
CubicCurveTo::controlY2Property,
CubicCurveTo::xProperty,
CubicCurveTo::yProperty),
H_LINE_TO('h', HLineTo.class, HLineTo::new,
HLineTo::xProperty),
LINE_TO('l', LineTo.class, LineTo::new,
LineTo::xProperty, LineTo::yProperty),
MOVE_TO('m', MoveTo.class, MoveTo::new,
MoveTo::xProperty, MoveTo::yProperty),
QUAD_CURVE_TO('q', QuadCurveTo.class, QuadCurveTo::new,
QuadCurveTo::controlXProperty, QuadCurveTo::controlYProperty,
QuadCurveTo::xProperty, QuadCurveTo::yProperty),
V_LINE_TO('v', VLineTo.class, VLineTo::new,
VLineTo::yProperty);
private final char letter;
private final String typeName;
private final Supplier<? extends PathElement> factory;
private final Function[] propertyGetters;
<T extends PathElement> PathElementType(char letter, Class<T> type, Supplier<T> factory, Function<T, ? extends Property<?>>... propertyGetters) {
this.letter = letter;
this.typeName = type.getName();
this.factory = factory;
this.propertyGetters = propertyGetters;
}
}
private final Map<String, PathElementType> ELEMENT_TYPES_BY_TYPE;
private final Map<Character, PathElementType> ELEMENT_TYPES_BY_LETTER;
public SVGConverter() {
ELEMENT_TYPES_BY_LETTER = new HashMap<>();
ELEMENT_TYPES_BY_TYPE = new HashMap<>();
for (PathElementType et : PathElementType.values()) {
ELEMENT_TYPES_BY_LETTER.put(et.letter, et);
ELEMENT_TYPES_BY_TYPE.put(et.typeName, et);
}
}
public String pathToSvg(Path path) {
StringBuilder sb = new StringBuilder();
for (PathElement element : path.getElements()) {
PathElementType elementType = ELEMENT_TYPES_BY_TYPE.get(element.getClass().getName());
if (elementType == null) {
throw new IllegalArgumentException("Unknown PathElement type: " + element.getClass().getName());
}
// specify path element type
char c = elementType.letter;
if (element.isAbsolute()) {
c = Character.toUpperCase(c);
}
sb.append(c);
// write property values
for (Function f : elementType.propertyGetters) {
Property property = (Property) f.apply(element);
sb.append((property instanceof BooleanProperty)
// special treatment for booleans to convert true/false to 1/0
? (((BooleanProperty) property).get() ? "1" : "0")
: property.getValue().toString()).append(' ');
}
}
// trim, if necessary
int lastIndex = sb.length() - 1;
if (lastIndex >= 0 && sb.charAt(lastIndex) == ' ') {
sb.deleteCharAt(lastIndex);
}
return sb.toString();
}
private static final String NUMBER_PATTERN_STRING = "[+-]?\\d*\\.\\d*(?:[eE][+-]?\\d+)?";
private static final Pattern NUMBER_PATTERN = Pattern.compile("(?<![\\d.+-])(" + NUMBER_PATTERN_STRING + ')');
private static final Pattern SVG_PATTERN = Pattern.compile("([aAcChHlLvmMqQVzZ])((?:\\s*" + NUMBER_PATTERN_STRING + "(?:[\\s,]+" + NUMBER_PATTERN_STRING + ")*)?)");
// parses doubles from number sequence
private static double[] getNumberMatches(Matcher m, int count) {
double[] result = new double[count];
for (int i = 0; i < count; i++) {
if (!m.find()) {
throw new IllegalArgumentException("missing numbers");
}
result[i] = Double.parseDouble(m.group(1));
}
if (m.find()) {
throw new IllegalArgumentException("too many numbers");
}
return result;
}
public Path svgToPath(String svg) {
Path path = new Path();
Matcher matcher = SVG_PATTERN.matcher(svg);
while (matcher.find()) {
// find out path element type
char c = matcher.group(1).charAt(0);
PathElementType elementType = ELEMENT_TYPES_BY_LETTER.get(Character.toLowerCase(c));
if (elementType == null) {
throw new IllegalArgumentException("Unknown path type " + c);
}
PathElement element = (PathElement) elementType.factory.get();
element.setAbsolute(Character.isUpperCase(c));
// retrieve parameters
if (elementType.propertyGetters.length > 0) {
Matcher numberMatcher = NUMBER_PATTERN.matcher(matcher.group(2));
double[] numbers = getNumberMatches(numberMatcher, elementType.propertyGetters.length);
for (int i = 0; i < elementType.propertyGetters.length; i++) {
Property property = (Property) elementType.propertyGetters[i].apply(element);
property.setValue((property instanceof BooleanProperty)
? (numbers[i] == 1) // convert to boolean (true iff 1.0)
: numbers[i]);
}
}
path.getElements().add(element);
}
return path;
}
}
Note: This does not restore any kind of bindings that may have existed before converting to string of course.
I have created a small console application to do OCR on a .tiff image file, I have done this using tess4j.
public class JavaApplication10 {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
File imageFile = new File("C:\\Users\\Manesh\\Desktop\\license_plate.tiff");
Tesseract instance = Tesseract.getInstance(); // JNA Interface Mapping
// Tesseract1 instance = new Tesseract1(); // JNA Direct Mapping
try
{
String result = instance.doOCR(imageFile); //Empty result
System.out.println("hahahaha");
System.out.println("The result is: " + result);
}
catch (TesseractException e)
{
System.out.println("error:" + e);
}
}
}
I'm not getting any value inside result, when I looked into the code of Tesseract class and inserted a couple of System.out.println those are also not getting printed in the console. My Tesseract code is given below.
public class Tesseract
{
private static Tesseract instance;
private final static Rectangle EMPTY_RECTANGLE = new Rectangle();
private String language = "eng";
private String datapath = "tessdata";
private int psm = TessAPI.TessPageSegMode.PSM_AUTO;
private boolean hocr;
private int pageNum;
private int ocrEngineMode = TessAPI.TessOcrEngineMode.OEM_DEFAULT;
private Properties prop = new Properties();
public final static String htmlBeginTag =
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\""
+ " \"http://www.w3.org/TR/html4/loose.dtd\">\n"
+ "<html>\n<head>\n<title></title>\n"
+ "<meta http-equiv=\"Content-Type\" content=\"text/html;"
+ "charset=utf-8\" />\n<meta name='ocr-system' content='tesseract'/>\n"
+ "</head>\n<body>\n";
public final static String htmlEndTag = "</body>\n</html>\n";
private Tesseract()
{
System.setProperty("jna.encoding", "UTF8");
}
public static synchronized Tesseract getInstance()
{
if (instance == null)
{
instance = new Tesseract();
}
return instance;
}
public void setDatapath(String datapath)
{
this.datapath = datapath;
}
public void setLanguage(String language)
{
this.language = language;
}
public void setOcrEngineMode(int ocrEngineMode)
{
this.ocrEngineMode = ocrEngineMode;
}
public void setPageSegMode(int mode)
{
this.psm = mode;
}
public void setHocr(boolean hocr)
{
this.hocr = hocr;
prop.setProperty("tessedit_create_hocr", hocr ? "1" : "0");
}
public void setTessVariable(String key, String value)
{
prop.setProperty(key, value);
}
public String doOCR(File imageFile) throws TesseractException
{
System.out.println("hiiiiiii "); //not getting printed
return doOCR(imageFile, null);
}
public String doOCR(File imageFile, Rectangle rect) throws TesseractException
{
try
{
System.out.println("be: "); //not getting printed
return doOCR(ImageIOHelper.getIIOImageList(imageFile), rect);
}
catch (IOException ioe)
{
throw new TesseractException(ioe);
}
}
public String doOCR(BufferedImage bi) throws TesseractException
{
return doOCR(bi, null);
}
public String doOCR(BufferedImage bi, Rectangle rect) throws TesseractException
{
IIOImage oimage = new IIOImage(bi, null, null);
List<IIOImage> imageList = new ArrayList<IIOImage>();
imageList.add(oimage);
return doOCR(imageList, rect);
}
public String doOCR(List<IIOImage> imageList, Rectangle rect) throws TesseractException
{
StringBuilder sb = new StringBuilder();
pageNum = 0;
for (IIOImage oimage : imageList)
{
pageNum++;
try
{
ByteBuffer buf = ImageIOHelper.getImageByteBuffer(oimage);
RenderedImage ri = oimage.getRenderedImage();
String pageText = doOCR(ri.getWidth(), ri.getHeight(), buf, rect, ri.getColorModel().getPixelSize());
sb.append(pageText);
}
catch (IOException ioe)
{
//skip the problematic image
System.err.println(ioe.getMessage());
}
}
if (hocr)
{
sb.insert(0, htmlBeginTag).append(htmlEndTag);
}
return sb.toString();
}
public String doOCR(int xsize, int ysize, ByteBuffer buf, Rectangle rect, int bpp) throws TesseractException
{
TessAPI api = TessAPI.INSTANCE;
TessAPI.TessBaseAPI handle = api.TessBaseAPICreate();
api.TessBaseAPIInit2(handle, datapath, language, ocrEngineMode);
api.TessBaseAPISetPageSegMode(handle, psm);
Enumeration em = prop.propertyNames();
while (em.hasMoreElements())
{
String key = (String) em.nextElement();
api.TessBaseAPISetVariable(handle, key, prop.getProperty(key));
}
int bytespp = bpp / 8;
int bytespl = (int) Math.ceil(xsize * bpp / 8.0);
api.TessBaseAPISetImage(handle, buf, xsize, ysize, bytespp, bytespl);
if (rect != null && !rect.equals(EMPTY_RECTANGLE))
{
api.TessBaseAPISetRectangle(handle, rect.x, rect.y, rect.width, rect.height);
}
Pointer utf8Text = hocr ? api.TessBaseAPIGetHOCRText(handle, pageNum - 1) : api.TessBaseAPIGetUTF8Text(handle);
String str = utf8Text.getString(0);
api.TessDeleteText(utf8Text);
api.TessBaseAPIDelete(handle);
return str;
}
}
I'm using tesseract for the first time please tell me what I'm doing wrong.
For Tesseract you have to pass the exact image you want to do OCR on, for example, suppose you are reading the chest numbers of players, if you pass the cropped and gray scaled image of the chest number only it will read the text, where as if you pass the whole image it will not read. You can do this using.
String doOCR(BufferedImage img, Rectangle rect);
Well i'm passing the cropped image directly so I'm not using the above method, My code looks like this rite now.
public class JavaApplication10 {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
try
{
File imageFile = new File("C:\\Users\\Manesh\\Desktop\\116.jpg"); //This is a cropped image of a chest number.
BufferedImage img = ImageIO.read(imageFile);
//BufferedImageOp grayscaleConv = new ColorConvertOp(colorFrame.getColorModel().getColorSpace(), grayscaleConv.filter(colorFrame, grayFrame);
Tesseract instance = Tesseract.getInstance(); // JNA Interface Mapping
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
ColorConvertOp op = new ColorConvertOp(cs, null);
op.filter(img, img); // gray scaling the image
// Tesseract1 instance = new Tesseract1(); // JNA Direct Mapping
try
{
String result = instance.doOCR(img);
System.out.println("hahahaha");
System.out.println("The result is: " + result);
}
catch (TesseractException e)
{
System.out.println("error:" + e);
}
}
catch (IOException ex)
{
Logger.getLogger(JavaApplication10.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
This is what I found please feel free to correct me if I'm wrong anywhere.
Here's my code:
public String generateEISReports_PDF(){
surveyReportService.setSurveyReportDA(surveyReportDA);
surveyReportList = surveyReportService.getSurveyReport(surveyType, surveyDate, projectCode, employeeCode);
if(surveyReportList != null){
System.out.println(surveyReportList + "testing");
System.out.println(surveyReportList.size() + "size ito");
for (SurveyReport surveyReport : surveyReportList) {
System.out.println(surveyReport.getRiskRank().toString() + "asdf");
surveyReports.add(surveyReport);
}
}
this.compileTheJasperReports();
return SUCCESS;
}
I am getting the whole row values with this code as an object. I want to iterate the field values in every list of objects. How can I do that?
By using reflection you can achieve that. Following is the code. This might help you.
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class SurveyReport {
public int localServeryCont; // if you make it private then changes have to be done in 'SurveyIterator' inner class.
public String surveyReporterName;
public static void main(String[] args) {
List<SurveyReport> surveyReportList = new ArrayList<SurveyReport>();
SurveyReport sr = new SurveyReport(); //first object creation
sr.localServeryCont = 10;
sr.surveyReporterName = "AAA";
surveyReportList.add(sr);
sr = new SurveyReport(); //second object creation
sr.localServeryCont = 100;
sr.surveyReporterName = "BBB";
surveyReportList.add(sr); //two objects are in the list-object.
for (SurveyReport surveyReport : surveyReportList) {
Iterator<String> itr = surveyReport.iterator(); //You can work around with 'java.lang.Iterable' to use 'foreach' loop
while (itr.hasNext()) { //this is what you might be expecting
System.out.println("SurveyReport's object's values : " + itr.next());
}
}
}
public Iterator<String> iterator() { //here is method to get iterator object.
return new SurveyIterator();
}
private class SurveyIterator implements Iterator<String> { //creating 'SurveyIterator' INNER class
private int totalAvailableField = SurveyReport.class.getDeclaredFields().length;
int cursor = 0;
Field[] surveyReportFields = SurveyReport.class.getFields();
#Override
public boolean hasNext() {
return cursor != totalAvailableField;
}
#Override
public String next() {
String next = null;
try {
next = (surveyReportFields[cursor].get(SurveyReport.this)).toString();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
cursor++;
return next;
}
#Override
public void remove() {
throw new UnsupportedOperationException();
}
}
}