Search Results

Search found 874 results on 35 pages for 'scanner'.

Page 10/35 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • Image Line Trace Math Help Hard To Explain

    - by Ozzy
    Hi all, sorry for the confusing title, its really hard for me to explain what i want. So i created this image :) Ok so the two RED dots are points on an image. The distance between them isnt important. What I want to do is, Using the coordinates for the two dots, work out the angle of the space between them (as shown by the black line between the red dots) Then once the angle is found, on the last red dot, create two points which cross the angle of the first line. Then from that, scan a Half semicircle and get the coordinates of every pixel of the image that the orange line passes. I dnot know if this makes any sense to you lot so i drew another picture: As you can see in the second picture, my idea is applied to a line drawn on a black canavs. The two red dots are the starting coordinates then at the end of the two dots, a less then half semicircle is created. The part that is orange shows the pixels of the image that should be recorded. I have no clue how to start this, so if anyone has any ideas on how i can or on what i need to do, any help is much appreciated :)

    Read the article

  • Read data matrix barcodes on iPhone?

    - by Saurabh
    Hi All, Is there any Open Source project I can use to read data matrix codes (not QR codes, I know I can use ZXing project to read QR Codes) on iPhone? Any JAVA Open Source would also be helpful (I'll convert that into a web service and use on iPhone). Any help would be much appreciated! Thanks Saurabh

    Read the article

  • Error when decoding image C# asp

    - by Wayneio
    I am trying to use MessagingToolkit to decode an image in C#/ASP. I have managed to encode a qr using this package, but when i try to decode, using the code below it comes up with 2 errors (at the bottom of the page) I believe this is because I am not getting the image correctly after uploading, but can someone point out exactly where I have gone wrong. Thanks. protected void CreateCode_OnClick(object sender, EventArgs e) { string path = "C:\\Users\\Wayneio\\Documents\\Visual Studio 2012\\Projects\\BAMSystem\\BAMSystem\\"; if (QRUpload.HasFiles == true) { FileInfo fi = new FileInfo(QRUpload.FileName); string extA = fi.Extension; if (extA == ".jpg" || extA == ".png") { QRCodeDecoder decoder = new QRCodeDecoder(); QRUpload.SaveAs(path + QRUpload.FileName); System.Drawing.Image myImg = System.Drawing.Image.FromFile(path + QRUpload.FileName); decoder.Decode(myImg); } else { error.Text = "You have uploaded a " + extA + " file. Please upload either a PNG or a JPG"; } } else { error.Text = "You have not uploaded an image."; } } Error1: Error 2 Argument 1: cannot convert from 'System.Drawing.Image' to 'MessagingToolkit.QRCode.Codec.Data.QRCodeImage' c:\users\wayneio\documents\visual studio 2012\Projects\BAMSystem\BAMSystem\default.aspx.cs 38 35 BAMSystem Error2: Error 1 The best overloaded method match for 'MessagingToolkit.QRCode.Codec.QRCodeDecoder.Decode(MessagingToolkit.QRCode.Codec.Data.QRCodeImage)' has some invalid arguments c:\users\wayneio\documents\visual studio 2012\Projects\BAMSystem\BAMSystem\default.aspx.cs 38 20 BAMSystem P.S if anyone has documentation on this MessagingToolkit QR package, it would be useful

    Read the article

  • Running a Java program with input from a file

    - by Katy
    I am writing a program that reads the input from a file and then prints it to the screen. When I run it without taking the input from the file, it works perfectly fine. However, every time I try to run it from the file it gives me an "Exception in thread "main" java.util.NoSuchElementException: No line found at" error that occurs every place the input is suppose to be read. I have no idea what is going on.

    Read the article

  • pleasae help in j2me

    - by samira
    hello i am a student and i am doing my senior project it is about developing an application in j2me for scanning a barcode and extract the number of the barcode in a message to be send. please i search the net but i cant found something usefull i am new at j2me if someone could help me with sourch code and how to create it i will be very thankfull my email is [email protected] thanks in advanced

    Read the article

  • WP7 BarcodeManager - Invalid cross-thread access

    - by rpf
    I'm trying to use Windows Phone 7 Silverlight ZXing Barcode Scanning Library but I'm having some problems. I'm using a background worker to check the image, but when I do this: WP7BarcodeManager.ScanBarcode(this.Image, BarcodeResults_Finished); The code throws an exception: Invalid cross-thread access. Here is my code... void photoChooserTask_Completed(object sender, PhotoResult e) { if (e.TaskResult == TaskResult.OK) { ShowImage(); System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage(); bmp.SetSource(e.ChosenPhoto); imgCapture.Source = bmp; this.Image = new BitmapImage(); this.Image.SetSource(e.ChosenPhoto); progressBar.Visibility = System.Windows.Visibility.Visible; txtStatus.Visibility = System.Windows.Visibility.Collapsed; worker.RunWorkerAsync(); } else ShowMain(); } void worker_DoWork(object sender, DoWorkEventArgs e) { try { Thread.Sleep(2000); WP7BarcodeManager.ScanMode = com.google.zxing.BarcodeFormat.UPC_EAN; WP7BarcodeManager.ScanBarcode(this.Image, BarcodeResults_Finished); } catch (Exception ex) { Debug.WriteLine("Error processing image.", ex); } } How can I solve this?

    Read the article

  • Printer image correction

    - by Matthew Shinal
    Here is my problem: my printer and scanner (HP psc2410xi) prints darker than the photos taken and teh scanner has a background fuzz. I want to create and install files to have the printer lighten the photos it prints (yellow becomes dark yellow, etc) and delete the "fuzz" from the scanner image (you can see it on a blank scan and yes I did clean the scanner). I'm thinking there is a way to take a printed image, scan that in, and subtract the two images from each other to get the correction factor.

    Read the article

  • How to scan multiple pages from a book under Linux?

    - by rumtscho
    I want the process to look like: I choose the correct scan settings (dpi, color depth, etc) I lay the first page on the scanner and trigger the process The scanner scans the page and waits for me to position the next page correctly I confirm that the next page is ready for scanning Repeat the above two steps until I tell the scanner that there are no more pages to come The scanner saves everything into a single PDF. I tried both xsane and gscan2pdf. First problem: they want me to know how many pages will be scanned. This is already a nuisance, but I can do the counting if needed. The main problem is that in step 3, the scanner does not pause. It is probably optimised for being fed loose sheets. The next scan process is triggered automatically as soon as the CCD has returned to the start position. The time the scanner needs to return the CCD is very short and I can't turn the page and position the book properly. Is there a software which can do the scan process in the way I described above, or did I just miss a setting available in xsane or gscan2pdf to make the scanner pause? If it makes any difference, the scanner is an Epson Stylus SX620FW, I run it using the manufacturer-provided driver.

    Read the article

  • Traversing Java Object Arrays [migrated]

    - by Sundi
    Please Help. Program does not read Array rentBooks[] in the for() loop this option is selected when choosing option 2 then option 4 in the menu The Array reads perfectly when reading the items after the setBook() Method import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import java.io.*; import java.util.Locale; import java.text.SimpleDateFormat ; class Library { protected static String Author; protected static String Title; SimpleDateFormat PublicationDate; int itemCode; int available = 1; } class Book extends Library { protected static String PublisherName; protected static String Edition; static Book[] rentBooks = new Book[5]; //Book[] rentBooks = new Book[5]; int count = 0; public Book() { String start= "start"; showBook.main(anza); } public void setBook( String Auth, String Titl, String PublishName) { this.Author = Auth; this.Title = Titl; this.PublisherName = PublishName; } public void getBook() { //System.out.println("*************BOOKS*************************"); System.out.println( "\n\nThe Author of the first Book is "+ this.Author ); System.out.println( "The Title of the book is "+ this.Title); System.out.println( "The Publisher of the book is "+ this.PublisherName ); // System.out.println( "The Edition of the book is "+ Edition ); } } class showBook{ static Book[] rentBooks = new Book[5]; static Book[] rentBooks2 = new Book[5]; static int a,b; //for ( a=0; a < 5; a++ ) //rentBooks2[a] = new Book(); public static void main(String[] args) { File file = new File("Book2.txt"); //Book libraryBooks = new Book(); int j; //initialise Array Class Objects for( j = 0; j < 5; j++) { rentBooks[j] = new Book(); } int i = 0; try{ Scanner scanner = new Scanner(file); scanner.useDelimiter(","); String loan=""; int loan2; while( scanner.hasNextLine()) { //Should the Books be Stored in An Array? // At the moment you have separate objects stored in unknown location String Author = scanner.next(); String Title = scanner.next(); String PublisherName = scanner.next(); if ( i < 4) { System.out.println(i); rentBooks[i].setBook(Author, Title, PublisherName); rentBooks[i].getBook(); // MEMBERS SHOWN i++; } public class readBook4{ public static void main(String[] args) { int number =0; System.out.println( "Please select one of the choices below " ); System.out.println( "Select option 1 to list all items in the library "); System.out.println( "Select option 2 to list the items by category"); System.out.println( "Select option 3 to choose item available in the library "); System.out.println( "Select option 7 to exit " ); InputStreamReader isr = new InputStreamReader( System.in); BufferedReader buffer = new BufferedReader( isr); String input = ""; try { input = buffer.readLine(); number = Integer.parseInt(input); //int number = Integer.parseInt( Edition); if ( number == 1 ) { System.out.println( " \nThanks you are reading "+ input); //showStudent.main(args); showPeriodical.main(args); showDVD.main(args); // showBook.main(args); } if ( number == 2 ) { //jht.cls(); int number2; System.out.println( "Please select one of the choices below " ); System.out.println( "Select option 4 to list Books only "); System.out.println( "Select option 5 to list the Periodicals only"); System.out.println( "Select option 6 to list DVDs only"); InputStreamReader isr2 = new InputStreamReader(System.in); BufferedReader buffer2 = new BufferedReader(isr2); String input2 = ""; try { input2 = buffer2.readLine(); buffer.close(); } catch(IOException e) { System.out.println("An input error has occured"); } //System.out.println("Thanks, you are reading" + input2); number2 = Integer.parseInt(input2); if ( number2 == 4 ) { showBook.main(args); } if ( number2 == 5 ) { showPeriodical.main(args); } if ( number2 == 6 ) { showDVD.main(args); } // readBook4.main(args); } if( number == 3 ) { //showBook.main(args); showBook.availableBooks(); showDVD.availableDVD(); showPeriodical.availablePeriodical(); } if ( number == 7 ) { showStudent.main(args); } buffer.close(); } catch( IOException e ) { System.out.println( " An input error has occured "); } //System.out.println( " \nThanks you are reading "+ input); } } } //buffer.close(); scanner.close(); } catch( FileNotFoundException e) { System.out.println("File not Found"); } for ( i=0; i < 5; i++ ) rentBooks[i].getBook(); //ARRAY NOT SHOWN } }

    Read the article

  • Trouble calling a method from an external class

    - by Bradley Hobbs
    Here is my employee database program: import java.util.*; import java.io.*; import java.io.File; import java.io.FileReader; import java.util.ArrayList; public class P { //Instance Variables private static String empName; private static String wage; private static double wages; private static double salary; private static double numHours; private static double increase; // static ArrayList<String> ARempName = new ArrayList<String>(); // static ArrayList<Double> ARwages = new ArrayList<Double>(); // static ArrayList<Double> ARsalary = new ArrayList<Double>(); static ArrayList<Employee> emp = new ArrayList<Employee>(); public static void main(String[] args) throws Exception { clearScreen(); printMenu(); question(); exit(); } public static void printArrayList(ArrayList<Employee> emp) { for (int i = 0; i < emp.size(); i++){ System.out.println(emp.get(i)); } } public static void clearScreen() { System.out.println("\u001b[H\u001b[2J"); } private static void exit() { System.exit(0); } private static void printMenu() { System.out.println("\t------------------------------------"); System.out.println("\t|Commands: n - New employee |"); System.out.println("\t| c - Compute paychecks |"); System.out.println("\t| r - Raise wages |"); System.out.println("\t| p - Print records |"); System.out.println("\t| d - Download data |"); System.out.println("\t| u - Upload data |"); System.out.println("\t| q - Quit |"); System.out.println("\t------------------------------------"); System.out.println(""); } public static void question() { System.out.print("Enter command: "); Scanner q = new Scanner(System.in); String input = q.nextLine(); input.replaceAll("\\s","").toLowerCase(); boolean valid = (input.equals("n") || input.equals("c") || input.equals("r") || input.equals("p") || input.equals("d") || input.equals("u") || input.equals("q")); if (!valid){ System.out.println("Command was not recognized; please try again."); printMenu(); question(); } else if (input.equals("n")){ System.out.print("Enter the name of new employee: "); Scanner stdin = new Scanner(System.in); empName = stdin.nextLine(); System.out.print("Hourly (h) or salaried (s): "); Scanner stdin2 = new Scanner(System.in); wage = stdin2.nextLine(); wage.replaceAll("\\s","").toLowerCase(); if (!(wage.equals("h") || wage.equals("s"))){ System.out.println("Input was not h or s; please try again"); } else if (wage.equals("h")){ System.out.print("Enter hourly wage: "); Scanner stdin4 = new Scanner(System.in); wages = stdin4.nextDouble(); Employee emp1 = new HourlyEmployee(empName, wages); emp.add(emp1); printMenu(); question();} else if (wage.equals("s")){ System.out.print("Enter annual salary: "); Scanner stdin5 = new Scanner(System.in); salary = stdin5.nextDouble(); Employee emp1 = new SalariedEmployee(empName, salary); printMenu(); question();}} else if (input.equals("c")){ for (int i = 0; i < emp.size(); i++){ System.out.println("Enter number of hours worked by " + emp.get(i) + ":"); } Scanner stdin = new Scanner(System.in); numHours = stdin.nextInt(); System.out.println("Pay: " + emp1.computePay(numHours)); System.out.print("Enter number of hours worked by " + empName); Scanner stdin2 = new Scanner(System.in); numHours = stdin2.nextInt(); System.out.println("Pay: " + emp1.computePay(numHours)); printMenu(); question();} else if (input.equals("r")){ System.out.print("Enter percentage increase: "); Scanner stdin = new Scanner(System.in); increase = stdin.nextDouble(); System.out.println("\nNew Wages"); System.out.println("---------"); // System.out.println(Employee.toString()); printMenu(); question(); } else if (input.equals("p")){ printArrayList(emp); printMenu(); question(); } else if (input.equals("q")){ exit(); } } } Here is one of the class files: public abstract class Employee { private String name; private double wage; protected Employee(String name, double wage){ this.name = name; this.wage = wage; } public String getName() { return name; } public double getWage() { return wage; } public void setName(String name) { this.name = name; } public void setWage(double wage) { this.wage = wage; } public void percent(double wage, double percent) { wage *= percent; } } And here are the errors: P.java:108: cannot find symbol symbol : variable emp1 location: class P System.out.println("Pay: " + emp1.computePay(numHours)); ^ P.java:112: cannot find symbol symbol : variable emp1 location: class P System.out.println("Pay: " + emp1.computePay(numHours)); ^ 2 errors I'm trying to the get paycheck to print out but i'm having trouble with how to call the method. It should take the user inputed numHours and calculate it then print on the paycheck for each employee. Thanks!

    Read the article

  • Java Array Index Out of Bounds Exception

    - by user1302023
    I need help debugging the following program: I'm getting a run time error that reads: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 at SearchEngine.main(SearchEngine.java:126) import java.util.*; import java.io.*; public class SearchEngine { public static int getNumberOfWords (File f) throws FileNotFoundException { int numWords = 0; Scanner scan = new Scanner(f); while (scan.hasNext()) { numWords++; scan.next(); } scan.close(); return numWords; } public static void readInWords (File input, String [] x) throws FileNotFoundException { Scanner scan = new Scanner(input); int i = 0; while (scan.hasNext() && i<x.length) { x[i] = scan.next(); i++; } scan.close(); } public static int getNumOfDistinctWords (File input, String [] x) throws FileNotFoundException { Scanner scan = new Scanner(input); int count = 0; int i = 1; while (scan.hasNext() && i<x.length) { if (!x[i].equals(x[i-1])) { count++; } i++; } scan.close(); return count; } public static void readInDistinctWords (String [] x, String [] y) { int i = 1; int k = 0; while (i<x.length) { if (!x[i].equals(x[i-1])) { y[k] = x[i]; k++; } i++; } } public static int getNumberOfLines (File input) throws FileNotFoundException { int numLines = 0; Scanner scan = new Scanner(input); while (scan.hasNextLine()) { numLines++; scan.nextLine(); } scan.close(); return numLines; } public static void readInLines (File input, String [] x) throws FileNotFoundException { Scanner scan = new Scanner(input); int i = 0; while (scan.hasNextLine() && i<x.length) { x[i] = scan.nextLine(); i++; } scan.close(); } public static void main(String [] args) { try { //gets file name System.out.println("Enter the name of the text file you wish to search"); Scanner kb = new Scanner(System.in); String fileName = kb.nextLine(); String TXT = ".txt"; if (!fileName.endsWith(TXT)) { fileName = fileName.concat(TXT); } File input = new File(fileName); //First part of creating index System.out.println("Creating vocabArray"); int NUM_WORDS = getNumberOfWords(input); //System.out.println(NUM_WORDS); String [] wordArray = new String[NUM_WORDS]; readInWords(input, wordArray); Arrays.sort(wordArray); int NUM_DISTINCT_WORDS = getNumOfDistinctWords(input, wordArray); String [] vocabArray = new String[NUM_DISTINCT_WORDS]; readInDistinctWords(wordArray, vocabArray); System.out.println("Finished creating vocabArray"); System.out.println("Creating concordanceArray"); int NUM_LINES = getNumberOfLines(input); String [] concordanceArray = new String[NUM_LINES]; readInLines(input, concordanceArray); System.out.println("Finished creating concordanceArray"); System.out.println("Creating invertedIndex"); int [][] invertedIndex = new int[NUM_DISTINCT_WORDS][10]; int [] wordCountArray = new int[NUM_DISTINCT_WORDS]; int lineNum = 0; while (lineNum<concordanceArray.length) { Scanner scan = new Scanner(concordanceArray[lineNum]); while (scan.hasNext()) { int wordPos = Arrays.binarySearch(vocabArray, scan.next()); wordCountArray[wordPos]+=1; for(int i = 0; i < invertedIndex.length; i++) { for(int j = 0; j < invertedIndex[i].length; j++) { if (invertedIndex[i][j] == 0) { invertedIndex[i][j] = lineNum; break; } } } } lineNum++; } System.out.println("Finished creating invertedIndex"); } catch (FileNotFoundException exception) { System.out.println("File Not Found"); } } //main } //class

    Read the article

  • Difference between ruby StringScanner post_match and rest?

    - by zhon
    What is the difference between ruby's StringScanner#post_match and StringScanner#rest? scanner = StringScanner.new('Say hello to...') scanner.scan(/\w+/) #=> 'Say' scanner.scan(/\s+/) #=> ' ' scanner.rest #=> 'hello to...' scanner.post_match #=> 'hello to...' scanner.rest.class #=> String scanner.post_match.class #=> String I don't see a difference. It seems like both return a string containing everything after the match.

    Read the article

  • Help me with this java program

    - by aser
    The question : Input file: customer’s account number, account balance at beginning of month, transaction type (withdrawal, deposit, interest), transaction amount Output: account number, beginning balance, ending balance, total interest paid, total amount deposited, number of deposits, total amount withdrawn, number of withdrawals package sentinel; import java.io.*; import java.util.*; public class Ex7 { /** * @param args the command line arguments */ public static void main(String[] args) throws FileNotFoundException { int AccountNum; double BeginningBalance; double TransactionAmount; int TransactionType; double AmountDeposited=0; int NumberOfDeposits=0; double InterestPaid=0.0; double AmountWithdrawn=0.0; int NumberOfWithdrawals=0; boolean found= false; Scanner inFile = new Scanner(new FileReader("Account.in")); PrintWriter outFile = new PrintWriter("Account.out"); AccountNum = inFile.nextInt(); BeginningBalance= inFile.nextDouble(); while (inFile.hasNext()) { TransactionAmount=inFile.nextDouble(); TransactionType=inFile.nextInt(); outFile.printf("Account Number: %d%n", AccountNum); outFile.printf("Beginning Balance: $%.2f %n",BeginningBalance); outFile.printf("Ending Balance: $%.2f %n",BeginningBalance); outFile.println(); switch (TransactionType) { case '1': // case 1 if we have a Deposite BeginningBalance = BeginningBalance + TransactionAmount; AmountDeposited = AmountDeposited + TransactionAmount; NumberOfDeposits++; outFile.printf("Amount Deposited: $%.2f %n",AmountDeposited); outFile.printf("Number of Deposits: %d%n",NumberOfDeposits); outFile.println(); break; case '2':// case 2 if we have an Interest BeginningBalance = BeginningBalance + TransactionAmount; InterestPaid = InterestPaid + TransactionAmount; outFile.printf("Interest Paid: $%.2f %n",InterestPaid); outFile.println(); break; case '3':// case 3 if we have a Withdraw BeginningBalance = BeginningBalance - TransactionAmount; AmountWithdrawn = AmountWithdrawn + TransactionAmount; NumberOfWithdrawals++; outFile.printf("Amount Withdrawn: $%.2f %n",AmountWithdrawn); outFile.printf("Number of Withdrawals: %d%n",NumberOfWithdrawals); outFile.println(); break; default: System.out.println("Invalid transaction Tybe: " + TransactionType + TransactionAmount); } } inFile.close(); outFile.close(); } } But is gives me this : Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:840) at java.util.Scanner.next(Scanner.java:1461) at java.util.Scanner.nextInt(Scanner.java:2091) at java.util.Scanner.nextInt(Scanner.java:2050) at sentinel.Ex7.main(Ex7.java:36) Java Result: 1

    Read the article

  • Read from file in eclipse

    - by Buzkie
    I'm trying to read from a text file to input data to my java program. However, eclipse continuosly gives me a Source not found error no matter where I put the file. I've made an additional sources folder in the project directory, the file in question is in both it and the bin file for the project and it still can't find it. I even put a copy of it on my desktop and tried pointing eclipse there when it asked me to browse for the source lookup path. No matter what I do it can't find the file. here's my code in case it's pertinent: System.out.println(System.getProperty("user.dir")); File file = new File("file.txt"); Scanner scanner = new Scanner(file); in addition, it says the user directory is the project directory and there is a copy there too. I have no clue what to do. Thanks, Alex after attempting the suggestion below and refreshing again, I was greeted by a host of errors. FileNotFoundException(Throwable).<init>(String) line: 195 FileNotFoundException(Exception).<init>(String) line: not available FileNotFoundException(IOException).<init>(String) line: not available FileNotFoundException.<init>(String) line: not available URLClassPath$JarLoader.getJarFile(URL) line: not available URLClassPath$JarLoader.access$600(URLClassPath$JarLoader, URL) line: not available URLClassPath$JarLoader$1.run() line: not available AccessController.doPrivileged(PrivilegedExceptionAction<T>) line: not available [native method] URLClassPath$JarLoader.ensureOpen() line: not available URLClassPath$JarLoader.<init>(URL, URLStreamHandler, HashMap) line: not available URLClassPath$3.run() line: not available AccessController.doPrivileged(PrivilegedExceptionAction<T>) line: not available [native method] URLClassPath.getLoader(URL) line: not available URLClassPath.getLoader(int) line: not available URLClassPath.access$000(URLClassPath, int) line: not available URLClassPath$2.next() line: not available URLClassPath$2.hasMoreElements() line: not available ClassLoader$2.hasMoreElements() line: not available CompoundEnumeration<E>.next() line: not available CompoundEnumeration<E>.hasMoreElements() line: not available ServiceLoader$LazyIterator.hasNext() line: not available ServiceLoader$1.hasNext() line: not available LocaleServiceProviderPool$1.run() line: not available AccessController.doPrivileged(PrivilegedExceptionAction<T>) line: not available [native method] LocaleServiceProviderPool.<init>(Class<LocaleServiceProvider>) line: not available LocaleServiceProviderPool.getPool(Class<LocaleServiceProvider>) line: not available NumberFormat.getInstance(Locale, int) line: not available NumberFormat.getNumberInstance(Locale) line: not available Scanner.useLocale(Locale) line: not available Scanner.<init>(Readable, Pattern) line: not available Scanner.<init>(ReadableByteChannel) line: not available Scanner.<init>(File) line: not available code used: System.out.println(System.getProperty("user.dir")); File file = new File(System.getProperty("user.dir") + "/file.txt"); Scanner scanner = new Scanner(file);

    Read the article

  • Spring, JPA, Hibernate, Jetty 7 Integration

    - by Jewel
    Have anyone successfully run any spring and JPA application in jetty 7? I am getting following exception. This application throws no error in jetty 6. INFO [main] org.eclipse.jetty.util.log - Logging to org.slf4j.impl.Log4jLoggerAdapter(org.eclipse.jetty.util.log) via org.eclipse.jetty.util.log.Slf4jLog INFO [main] org.eclipse.jetty.util.log - jetty-7.1.2.v20100523 INFO [main] org.eclipse.jetty.util.log - Deployment monitor G:\_Java\_Jetty\jetty-distribution-7.1.2.v20100523\contexts at interval 5 INFO [main] org.eclipse.jetty.util.log - Deployment monitor G:\_Java\_Jetty\jetty-distribution-7.1.2.v20100523\webapps at interval 5 INFO [main] org.eclipse.jetty.util.log - Deployable added: G:\_Java\_Jetty\jetty-distribution-7.1.2.v20100523\webapps\gwtrpc-spring.war INFO [main] org.eclipse.jetty.util.log - Copying WEB-INF/lib jar:file:/G:/_Java/_Jetty/jetty-distribution-7.1.2.v20100523/webapps/gwtrpc-spring.war!/WEB-INF/lib/ to C:\Documents and Settings\Jewel2\Local Settings\Temp\Jetty_0_0_0_0_8080_gwtrpc.spring.war__gwtrpc.spring__az1wdj\webinf\WEB-INF\lib INFO [main] org.eclipse.jetty.util.log - Copying WEB-INF/classes from jar:file:/G:/_Java/_Jetty/jetty-distribution-7.1.2.v20100523/webapps/gwtrpc-spring.war!/WEB-INF/classes/ to C:\Documents and Settings\Jewel2\Local Settings\Temp\Jetty_0_0_0_0_8080_gwtrpc.spring.war__gwtrpc.spring__az1wdj\webinf\WEB-INF\classes INFO [main] /gwtrpc-spring - Initializing Spring root WebApplicationContext INFO [main] org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization started INFO [main] org.springframework.web.context.support.XmlWebApplicationContext - Refreshing Root WebApplicationContext: startup date [Thu Jun 10 00:13:32 GMT+06:00 2010]; root of context hierarchy INFO [main] org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/applicationContext.xml] INFO [main] org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@467991: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,greetingServiceImpl,testService,testService2,taskExecutor,dataSource,entityManagerFactory,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,transactionManager,org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor#0]; root of factory hierarchy INFO [main] org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor - Initializing ExecutorService 'taskExecutor' INFO [main] org.springframework.jdbc.datasource.DriverManagerDataSource - Loaded JDBC driver: com.mysql.jdbc.Driver INFO [main] org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean - Building JPA container EntityManagerFactory for persistence unit 'gwtrpc-spring-data-source' INFO [main] org.hibernate.cfg.annotations.Version - Hibernate Annotations 3.4.0.GA INFO [main] org.hibernate.cfg.Environment - Hibernate 3.3.1.GA INFO [main] org.hibernate.cfg.Environment - hibernate.properties not found INFO [main] org.hibernate.cfg.Environment - Bytecode provider name : javassist INFO [main] org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling INFO [main] org.hibernate.annotations.common.Version - Hibernate Commons Annotations 3.1.0.GA INFO [main] org.hibernate.ejb.Version - Hibernate EntityManager 3.4.0.GA INFO [main] org.hibernate.ejb.Ejb3Configuration - Processing PersistenceUnitInfo [ name: gwtrpc-spring-data-source ...] INFO [main] org.springframework.beans.factory.support.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@467991: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,greetingServiceImpl,testService,testService2,taskExecutor,dataSource,entityManagerFactory,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,transactionManager,org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor#0]; root of factory hierarchy INFO [main] org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor - Shutting down ExecutorService 'taskExecutor' ERROR [main] org.springframework.web.context.ContextLoader - Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: gwtrpc-spring-data-source] class or package not found at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1403) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:545) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:871) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:423) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:272) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:196) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47) at org.eclipse.jetty.server.handler.ContextHandler.startContext(ContextHandler.java:636) at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:188) at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:995) at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:579) at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:381) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:55) at org.eclipse.jetty.deploy.bindings.StandardStarter.processBinding(StandardStarter.java:36) at org.eclipse.jetty.deploy.AppLifeCycle.runBindings(AppLifeCycle.java:182) at org.eclipse.jetty.deploy.DeploymentManager.requestAppGoal(DeploymentManager.java:497) at org.eclipse.jetty.deploy.DeploymentManager.addApp(DeploymentManager.java:135) at org.eclipse.jetty.deploy.providers.ScanningAppProvider$1.fileAdded(ScanningAppProvider.java:61) at org.eclipse.jetty.util.Scanner.reportAddition(Scanner.java:436) at org.eclipse.jetty.util.Scanner.reportDifferences(Scanner.java:349) at org.eclipse.jetty.util.Scanner.scan(Scanner.java:306) at org.eclipse.jetty.util.Scanner.start(Scanner.java:242) at org.eclipse.jetty.deploy.providers.ScanningAppProvider.doStart(ScanningAppProvider.java:136) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:55) at org.eclipse.jetty.deploy.DeploymentManager.startAppProvider(DeploymentManager.java:562) at org.eclipse.jetty.deploy.DeploymentManager.doStart(DeploymentManager.java:212) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:55) at org.eclipse.jetty.server.Server.doStart(Server.java:209) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:55) at org.eclipse.jetty.xml.XmlConfiguration$1.run(XmlConfiguration.java:1018) at java.security.AccessController.doPrivileged(Native Method) at org.eclipse.jetty.xml.XmlConfiguration.main(XmlConfiguration.java:983) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.eclipse.jetty.start.Main.invokeMain(Main.java:447) at org.eclipse.jetty.start.Main.start(Main.java:605) at org.eclipse.jetty.start.Main.parseCommandLine(Main.java:238) at org.eclipse.jetty.start.Main.main(Main.java:77) Caused by: javax.persistence.PersistenceException: [PersistenceUnit: gwtrpc-spring-data-source] class or package not found at org.hibernate.ejb.Ejb3Configuration.addNamedAnnotatedClasses(Ejb3Configuration.java:1093) at org.hibernate.ejb.Ejb3Configuration.addClassesToSessionFactory(Ejb3Configuration.java:871) at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:758) at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:425) at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:131) at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:225) at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:308) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1460) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1400) ... 45 more Caused by: java.lang.ClassNotFoundException: WEB-INF.classes.org.gwtrpcspring.example.server.Person at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClassInternal(Unknown Source) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Unknown Source) at org.hibernate.util.ReflectHelper.classForName(ReflectHelper.java:135) at org.hibernate.ejb.Ejb3Configuration.classForName(Ejb3Configuration.java:1009) at org.hibernate.ejb.Ejb3Configuration.addNamedAnnotatedClasses(Ejb3Configuration.java:1081) ... 53 more WARN [main] org.eclipse.jetty.util.log - Failed startup of context WebAppContext@149f041@149f041/gwtrpc-spring,file:/C:/Documents and Settings/Jewel2/Local Settings/Temp/Jetty_0_0_0_0_8080_gwtrpc.spring.war__gwtrpc.spring__az1wdj/webinf/;jar:file:/G:/_Java/_Jetty/jetty-distribution-7.1.2.v20100523/webapps/gwtrpc-spring.war!/;,G:\_Java\_Jetty\jetty-distribution-7.1.2.v20100523\webapps\gwtrpc-spring.war org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: gwtrpc-spring-data-source] class or package not found at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1403) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:545) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:871) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:423) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:272) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:196) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47) at org.eclipse.jetty.server.handler.ContextHandler.startContext(ContextHandler.java:636) at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:188) at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:995) at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:579) at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:381) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:55) at org.eclipse.jetty.deploy.bindings.StandardStarter.processBinding(StandardStarter.java:36) at org.eclipse.jetty.deploy.AppLifeCycle.runBindings(AppLifeCycle.java:182) at org.eclipse.jetty.deploy.DeploymentManager.requestAppGoal(DeploymentManager.java:497) at org.eclipse.jetty.deploy.DeploymentManager.addApp(DeploymentManager.java:135) at org.eclipse.jetty.deploy.providers.ScanningAppProvider$1.fileAdded(ScanningAppProvider.java:61) at org.eclipse.jetty.util.Scanner.reportAddition(Scanner.java:436) at org.eclipse.jetty.util.Scanner.reportDifferences(Scanner.java:349) at org.eclipse.jetty.util.Scanner.scan(Scanner.java:306) at org.eclipse.jetty.util.Scanner.start(Scanner.java:242) at org.eclipse.jetty.deploy.providers.ScanningAppProvider.doStart(ScanningAppProvider.java:136) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:55) at org.eclipse.jetty.deploy.DeploymentManager.startAppProvider(DeploymentManager.java:562) at org.eclipse.jetty.deploy.DeploymentManager.doStart(DeploymentManager.java:212) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:55) at org.eclipse.jetty.server.Server.doStart(Server.java:209) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:55) at org.eclipse.jetty.xml.XmlConfiguration$1.run(XmlConfiguration.java:1018) at java.security.AccessController.doPrivileged(Native Method) at org.eclipse.jetty.xml.XmlConfiguration.main(XmlConfiguration.java:983) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.eclipse.jetty.start.Main.invokeMain(Main.java:447) at org.eclipse.jetty.start.Main.start(Main.java:605) at org.eclipse.jetty.start.Main.parseCommandLine(Main.java:238) at org.eclipse.jetty.start.Main.main(Main.java:77) Caused by: javax.persistence.PersistenceException: [PersistenceUnit: gwtrpc-spring-data-source] class or package not found at org.hibernate.ejb.Ejb3Configuration.addNamedAnnotatedClasses(Ejb3Configuration.java:1093) at org.hibernate.ejb.Ejb3Configuration.addClassesToSessionFactory(Ejb3Configuration.java:871) at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:758) at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:425) at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:131) at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:225) at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:308) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1460) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1400) ... 45 more Caused by: java.lang.ClassNotFoundException: WEB-INF.classes.org.gwtrpcspring.example.server.Person at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClassInternal(Unknown Source) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Unknown Source) at org.hibernate.util.ReflectHelper.classForName(ReflectHelper.java:135) at org.hibernate.ejb.Ejb3Configuration.classForName(Ejb3Configuration.java:1009) at org.hibernate.ejb.Ejb3Configuration.addNamedAnnotatedClasses(Ejb3Configuration.java:1081) ... 53 more INFO [main] org.eclipse.jetty.util.log - Started [email protected]:8080 And this is my applicationContext.xml file <?xml version="1.0" encoding="UTF-8"?> <beans> <context:annotation-config /> <context:component-scan base-package="org.gwtrpcspring.example.server" /> <bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"> <property name="corePoolSize" value="5" /> <property name="maxPoolSize" value="10" /> <property name="queueCapacity" value="25" /> </bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/test" /> <property name="username" value="jewel" /> <property name="password" value="jewel" /> </bean> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" /> <!-- <property name="databasePlatform" value="org.hibernate.dialect.HSQLDialect" /> --> <property name="showSql" value="false" /> <property name="generateDdl" value="true" /> </bean> </property> </bean> <tx:annotation-driven /> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" /> </beans>

    Read the article

  • Looking for Go equivalent of scanf.

    - by Stephen Hsu
    I'm looking for the Go equivalent of scanf(). I tried with following code: 1 package main 2 3 import ( 4 "scanner" 5 "os" 6 "fmt" 7 ) 8 9 func main() { 10 var s scanner.Scanner 11 s.Init(os.Stdin) 12 s.Mode = scanner.ScanInts 13 tok := s.Scan() 14 for tok != scanner.EOF { 15 fmt.Printf("%d ", tok) 16 tok = s.Scan() 17 } 18 fmt.Println() 19 } I run it with input from a text with a line of integers. But it always output -3 -3 ... And how to scan a line composed of a string and some integers? Changing the mode whenever encounter a new data type? The Package documentation: Package scanner A general-purpose scanner for UTF-8 encoded text. But it seems that the scanner is not for general use. Updated code: func main() { n := scanf() fmt.Println(n) fmt.Println(len(n)) } func scanf() []int { nums := new(vector.IntVector) reader := bufio.NewReader(os.Stdin) str, err := reader.ReadString('\n') for err != os.EOF { fields := strings.Fields(str) for _, f := range fields { i, _ := strconv.Atoi(f) nums.Push(i) } str, err = reader.ReadString('\n') } r := make([]int, nums.Len()) for i := 0; i < nums.Len(); i++ { r[i] = nums.At(i) } return r }

    Read the article

  • Adding text read from a file to an array list in java

    - by user1824856
    I am having trouble putting text read from a file into an array list. My text looks like this: 438;MIA;JFK;10:55;1092;447 638;JFK;MIA;19:45;1092;447 689;ATL;DFW;12:50;732;448 etc... My code looks like this: package filesexample; import java.io.*; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.ArrayList; /** * * @author */ public class FilesExample { /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { File file = new File ("/Schedule.txt"); try { Scanner scanner= new Scanner(file);; while (scanner.hasNextLine()) { String line = scanner.nextLine(); Scanner lineScanner= new Scanner(line); lineScanner.useDelimiter(";"); while(lineScanner.hasNext()){ String part = lineScanner.next(); System.out.print(part + " "); } System.out.println(); } }catch (FileNotFoundException e){ e.printStackTrace(); } } } Some help on getting started would be much appreciated thank you!

    Read the article

  • creating objects from trivial graph format text file. java. dijkstra algorithm.

    - by user560084
    i want to create objects, vertex and edge, from trivial graph format txt file. one of programmers here suggested that i use trivial graph format to store data for dijkstra algorithm. the problem is that at the moment all the information, e.g., weight, links, is in the sourcecode. i want to have a separate text file for that and read it into the program. i thought about using a code for scanning through the text file by using scanner. but i am not quite sure how to create different objects from the same file. could i have some help please? the file is v0 Harrisburg v1 Baltimore v2 Washington v3 Philadelphia v4 Binghamton v5 Allentown v6 New York # v0 v1 79.83 v0 v5 81.15 v1 v0 79.75 v1 v2 39.42 v1 v3 103.00 v2 v1 38.65 v3 v1 102.53 v3 v5 61.44 v3 v6 96.79 v4 v5 133.04 v5 v0 81.77 v5 v3 62.05 v5 v4 134.47 v5 v6 91.63 v6 v3 97.24 v6 v5 87.94 and the dijkstra algorithm code is Downloaded from: http://en.literateprograms.org/Special:Downloadcode/Dijkstra%27s_algorithm_%28Java%29 */ import java.util.PriorityQueue; import java.util.List; import java.util.ArrayList; import java.util.Collections; class Vertex implements Comparable<Vertex> { public final String name; public Edge[] adjacencies; public double minDistance = Double.POSITIVE_INFINITY; public Vertex previous; public Vertex(String argName) { name = argName; } public String toString() { return name; } public int compareTo(Vertex other) { return Double.compare(minDistance, other.minDistance); } } class Edge { public final Vertex target; public final double weight; public Edge(Vertex argTarget, double argWeight) { target = argTarget; weight = argWeight; } } public class Dijkstra { public static void computePaths(Vertex source) { source.minDistance = 0.; PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>(); vertexQueue.add(source); while (!vertexQueue.isEmpty()) { Vertex u = vertexQueue.poll(); // Visit each edge exiting u for (Edge e : u.adjacencies) { Vertex v = e.target; double weight = e.weight; double distanceThroughU = u.minDistance + weight; if (distanceThroughU < v.minDistance) { vertexQueue.remove(v); v.minDistance = distanceThroughU ; v.previous = u; vertexQueue.add(v); } } } } public static List<Vertex> getShortestPathTo(Vertex target) { List<Vertex> path = new ArrayList<Vertex>(); for (Vertex vertex = target; vertex != null; vertex = vertex.previous) path.add(vertex); Collections.reverse(path); return path; } public static void main(String[] args) { Vertex v0 = new Vertex("Nottinghill_Gate"); Vertex v1 = new Vertex("High_Street_kensignton"); Vertex v2 = new Vertex("Glouchester_Road"); Vertex v3 = new Vertex("South_Kensignton"); Vertex v4 = new Vertex("Sloane_Square"); Vertex v5 = new Vertex("Victoria"); Vertex v6 = new Vertex("Westminster"); v0.adjacencies = new Edge[]{new Edge(v1, 79.83), new Edge(v6, 97.24)}; v1.adjacencies = new Edge[]{new Edge(v2, 39.42), new Edge(v0, 79.83)}; v2.adjacencies = new Edge[]{new Edge(v3, 38.65), new Edge(v1, 39.42)}; v3.adjacencies = new Edge[]{new Edge(v4, 102.53), new Edge(v2, 38.65)}; v4.adjacencies = new Edge[]{new Edge(v5, 133.04), new Edge(v3, 102.53)}; v5.adjacencies = new Edge[]{new Edge(v6, 81.77), new Edge(v4, 133.04)}; v6.adjacencies = new Edge[]{new Edge(v0, 97.24), new Edge(v5, 81.77)}; Vertex[] vertices = { v0, v1, v2, v3, v4, v5, v6 }; computePaths(v0); for (Vertex v : vertices) { System.out.println("Distance to " + v + ": " + v.minDistance); List<Vertex> path = getShortestPathTo(v); System.out.println("Path: " + path); } } } and the code for scanning file is import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; public class DataScanner1 { //private int total = 0; //private int distance = 0; private String vector; private String stations; private double [] Edge = new double []; /*public int getTotal(){ return total; } */ /* public void getMenuInput(){ KeyboardInput in = new KeyboardInput; System.out.println("Enter the destination? "); String val = in.readString(); return val; } */ public void readFile(String fileName) { try { Scanner scanner = new Scanner(new File(fileName)); scanner.useDelimiter (System.getProperty("line.separator")); while (scanner.hasNext()) { parseLine(scanner.next()); } scanner.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } public void parseLine(String line) { Scanner lineScanner = new Scanner(line); lineScanner.useDelimiter("\\s*,\\s*"); vector = lineScanner.next(); stations = lineScanner.next(); System.out.println("The current station is " + vector + " and the destination to the next station is " + stations + "."); //total += distance; //System.out.println("The total distance is " + total); } public static void main(String[] args) { /* if (args.length != 1) { System.err.println("usage: java TextScanner2" + "file location"); System.exit(0); } */ DataScanner1 scanner = new DataScanner1(); scanner.readFile(args[0]); //int total =+ distance; //System.out.println(""); //System.out.println("The total distance is " + scanner.getTotal()); } }

    Read the article

  • Can anyone recommend a command line virus scanner that is open source and works with linux/php/apach

    - by Scarface
    Hey guys recently I have had the 'priveledge' of trying to set up an anti virus scanner to scan file uploads to my VPN server. I just finished trying to set up ClamAV but it slowed my server down to a hault once initiated so I had to kill it. Does anyone have any recommendations to a program that will accomplish my task and can be executed in php (other than clamAv)? Any advice greatly appreciated.

    Read the article

  • inputMismatchException Java reading doubles from plain text file

    - by user939287
    Using double variable = inputFile.nextDouble(); Gives the mismatch error and I can't figure out why... Anyone know what's up? The input file is just a bunch of doubles like 5.0... Okay here is the code snippet String fileName; Scanner scanner = new Scanner(System.in); System.out.println("\nEnter file name that contains the matrix and vector: "); fileName = scanner.nextLine(); Scanner inputFile = new Scanner(fileName); double a1 = inputFile.nextDouble(); the input file is a plain text document .txt in this format 5.0 4.0 -3.0 4.0 2.0 5.0 6.0 5.0 -2.0 -13.0 4.0 12.0 I don't understand why it wouldn't take those as doubles... As far as what its expecting the format of the file to be... I suppose binary? isn't that the default? I didn't specify in the code...

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >