Search Results

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

Page 17/35 | < Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >

  • Memento with optional state?

    - by Korey Hinton
    EDIT: As pointed out by Steve Evers and pdr, I am not correctly implementing the Memento pattern, my design is actually State pattern. Menu Program I built a console-based menu program with multiple levels that selects a particular test to run. Each level more precisely describes the operation. At any level you can type back to go back one level (memento). Level 1: Server Type? [1] Server A [2] Server B Level 2: Server environment? [1] test [2] production Level 3: Test type? [1] load [2] unit Level 4: Data Collection? [1] Legal docs [2] Corporate docs Level 4.5 (optional): Load Test Type [2] Multi TIF [2] Single PDF Level 5: Command Type? [1] Move [2] Copy [3] Remove [4] Custom Level 6: Enter a keyword [setup, cleanup, run] Design States PROBLEM: Right now the STATES enum is the determining factor as to what state is BACK and what state is NEXT yet it knows nothing about what the current memento state is. Has anyone experienced a similar issue and found an effective way to handle mementos with optional state? static enum STATES { SERVER, ENVIRONMENT, TEST_TYPE, COLLECTION, COMMAND_TYPE, KEYWORD, FINISHED } Possible Solution (Not-flexible) In reference to my code below, every case statement in the Menu class could check the state of currentMemo and then set the STATE (enum) accordingly to pass to the Builder. However, this doesn't seem flexible very flexible to change and I'm struggling to see an effective way refactor the design. class Menu extends StateConscious { private State state; private Scanner reader; private ServerUtils utility; Menu() { state = new State(); reader = new Scanner(System.in); utility = new ServerUtils(); } // Recurring menu logic public void startPromptingLoop() { List<State> states = new ArrayList<>(); states.add(new State()); boolean redoInput = false; boolean userIsDone = false; while (true) { // get Memento from last loop Memento currentMemento = states.get(states.size() - 1) .saveMemento(); if (currentMemento == null) currentMemento = new Memento.Builder(0).build(); if (!redoInput) System.out.println(currentMemento.prompt); redoInput = false; // prepare Memento for next loop Memento nextMemento = null; STATES state = STATES.values()[states.size() - 1]; // get user input String selection = reader.nextLine(); switch (selection) { case "exit": reader.close(); return; // only escape case "quit": nextMemento = new Memento.Builder(first(), currentMemento, selection).build(); states.clear(); break; case "back": nextMemento = new Memento.Builder(previous(state), currentMemento, selection).build(); if (states.size() <= 1) { states.remove(0); } else { states.remove(states.size() - 1); states.remove(states.size() - 1); } break; case "1": nextMemento = new Memento.Builder(next(state), currentMemento, selection).build(); break; case "2": nextMemento = new Memento.Builder(next(state), currentMemento, selection).build(); break; case "3": nextMemento = new Memento.Builder(next(state), currentMemento, selection).build(); break; case "4": nextMemento = new Memento.Builder(next(state), currentMemento, selection).build(); break; default: if (state.equals(STATES.CATEGORY)) { String command = selection; System.out.println("Executing " + command + " command on: " + currentMemento.type + " " + currentMemento.environment); utility.executeCommand(currentMemento.nickname, command); userIsDone = true; states.clear(); nextMemento = new Memento.Builder(first(), currentMemento, selection).build(); } else if (state.equals(STATES.KEYWORD)) { nextMemento = new Memento.Builder(next(state), currentMemento, selection).build(); states.clear(); nextMemento = new Memento.Builder(first(), currentMemento, selection).build(); } else { redoInput = true; System.out.println("give it another try"); continue; } break; } if (userIsDone) { // start the recurring menu over from the beginning for (int i = 0; i < states.size(); i++) { if (i != 0) { states.remove(i); // remove all except first } } reader = new Scanner(System.in); this.state = new State(); userIsDone = false; } if (!redoInput) { this.state.restoreMemento(nextMemento); states.add(this.state); } } } }

    Read the article

  • JBoss 7.1.1 + Spring 3.1 + JPA 2 (Hibernate 3.6.8) > Cannot parse beans.xml

    - by Mashrur
    Trying to deploy a JSF 2 app with Spring 3.1 + JPA 2 (Hibernte 3.6.8) into JBoss 7.1.1 AS. The app was working fine on tomcat 7. Now, I have already added and changed some configurations. Added jboss-deployment-structure.xml <jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.1"> <deployment> <exclusions> <module name="org.apache.log4j" /> <module name="javax.faces.api" slot="main"/> <module name="com.sun.jsf-impl" slot="main"/> <module name="org.hibernate"/> <module name="org.javassist" /> <module name="javaee.api" /> <module name="org.hibernate.validator" /> <module name="org.jboss.as.web" /> <module name="org.jboss.logging" /> <module name="javax.persistence.api" /> <module name="org.jboss.interceptor" /> </exclusions> </deployment> </jboss-deployment-structure> 2. Inside web.xml added these lines: <persistence-unit-ref> <persistence-unit-ref-name>persistence/persistenceUnit</persistence-unit-ref-name> <persistence-unit-name>persistenceUnit</persistence-unit-name> </persistence-unit-ref> 3. Inside applicationContext.xml, changed bean definition for entityManagerFactory by adding this property <property name="persistenceXmlLocation" value="classpath*:META-INF/persistence.xml"/> Now, do I still need to do something more than these which is obvious to you? Because, while I am trying to deploy it from eclipse indigo SR2, getting this 14:10:32,046 INFO [org.jboss.modules] JBoss Modules version 1.1.1.GA 14:10:33,054 INFO [org.jboss.msc] JBoss MSC version 1.0.2.GA 14:10:33,200 INFO [org.jboss.as] JBAS015899: JBoss AS 7.1.1.Final "Brontes" starting 14:10:36,375 INFO [org.xnio] XNIO Version 3.0.3.GA 14:10:36,384 INFO [org.jboss.as.server] JBAS015888: Creating http management service using socket-binding (management-http) 14:10:36,432 INFO [org.xnio.nio] XNIO NIO Implementation Version 3.0.3.GA 14:10:36,462 INFO [org.jboss.remoting] JBoss Remoting version 3.2.3.GA 14:10:36,587 INFO [org.jboss.as.logging] JBAS011502: Removing bootstrap log handlers 14:10:36,714 INFO [org.jboss.as.security] (ServerService Thread Pool -- 44) JBAS013101: Activating Security Subsystem 14:10:36,735 INFO [org.jboss.as.naming] (MSC service thread 1-2) JBAS011802: Starting Naming Service 14:10:37,043 INFO [org.jboss.as.mail.extension] (MSC service thread 1-6) JBAS015400: Bound mail session [java:jboss/mail/Default] 14:10:37,208 INFO [org.jboss.as.connector] (MSC service thread 1-7) JBAS010408: Starting JCA Subsystem (JBoss IronJacamar 1.0.9.Final) 14:10:37,295 INFO [org.jboss.as.security] (MSC service thread 1-7) JBAS013100: Current PicketBox version=4.0.7.Final 14:10:37,740 INFO [org.jboss.as.connector.subsystems.datasources] (ServerService Thread Pool -- 27) JBAS010403: Deploying JDBC-compliant driver class org.h2.Driver (version 1.3) 14:10:38,792 INFO [org.jboss.ws.common.management.AbstractServerConfig] (MSC service thread 1-3) JBoss Web Services - Stack CXF Server 4.0.2.GA 14:10:38,833 INFO [org.apache.coyote.http11.Http11Protocol] (MSC service thread 1-2) Starting Coyote HTTP/1.1 on http-localhost-127.0.0.1-8080 14:10:39,534 INFO [org.jboss.as.server.deployment.scanner] (MSC service thread 1-1) JBAS015012: Started FileSystemDeploymentService for directory F:\work\softwares\Application Servers\JBoss\jboss-as-7.1.1.Final\jboss-as-7.1.1.Final\standalone\deployments 14:10:39,618 INFO [org.jboss.as.remoting] (MSC service thread 1-3) JBAS017100: Listening on localhost/127.0.0.1:4447 14:10:39,623 INFO [org.jboss.as.remoting] (MSC service thread 1-2) JBAS017100: Listening on /127.0.0.1:9999 14:10:39,698 INFO [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 1) JBAS015014: Re-attempting failed deployment treasury.war 14:10:39,706 INFO [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 1) JBAS015003: Found com.misl.treasury.ui.war in deployment directory. To trigger deployment create a file called com.misl.treasury.ui.war.dodeploy 14:10:40,105 INFO [org.jboss.as.connector.subsystems.datasources] (MSC service thread 1-2) JBAS010400: Bound data source [java:jboss/datasources/ExampleDS] 14:10:40,399 INFO [org.jboss.as.server.deployment] (MSC service thread 1-1) JBAS015876: Starting deployment of "com.misl.treasury.ui.war" 14:10:40,405 INFO [org.jboss.as.server.deployment] (MSC service thread 1-7) JBAS015876: Starting deployment of "treasury.war" 14:10:55,283 WARN [org.jboss.as.server.deployment] (MSC service thread 1-7) JBAS015893: Encountered invalid class name 'com.sun.faces.vendor.Tomcat6InjectionProvider:org.apache.catalina.util.DefaultAnnotationProcessor' for service type 'com.sun.faces.spi.injectionprovider' 14:10:55,289 WARN [org.jboss.as.server.deployment] (MSC service thread 1-7) JBAS015893: Encountered invalid class name 'com.sun.faces.vendor.Jetty6InjectionProvider:org.mortbay.jetty.plus.annotation.InjectionCollection' for service type 'com.sun.faces.spi.injectionprovider' 14:10:55,428 INFO [org.jboss.as.jpa] (MSC service thread 1-7) JBAS011401: Read persistence.xml for persistenceUnit 14:10:55,843 WARN [org.jboss.as.server.deployment] (MSC service thread 1-4) JBAS015893: Encountered invalid class name 'com.sun.faces.vendor.Tomcat6InjectionProvider:org.apache.catalina.util.DefaultAnnotationProcessor' for service type 'com.sun.faces.spi.injectionprovider' 14:10:55,849 WARN [org.jboss.as.server.deployment] (MSC service thread 1-4) JBAS015893: Encountered invalid class name 'com.sun.faces.vendor.Jetty6InjectionProvider:org.mortbay.jetty.plus.annotation.InjectionCollection' for service type 'com.sun.faces.spi.injectionprovider' 14:10:56,010 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-2) MSC00001: Failed to start service jboss.deployment.unit."com.misl.treasury.ui.war".POST_MODULE: org.jboss.msc.service.StartException in service jboss.deployment.unit."com.misl.treasury.ui.war".POST_MODULE: Failed to process phase POST_MODULE of deployment "com.misl.treasury.ui.war" at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:119) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final] at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.2.GA.jar:1.0.2.GA] at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.2.GA.jar:1.0.2.GA] at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) [rt.jar:1.6.0_23] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) [rt.jar:1.6.0_23] at java.lang.Thread.run(Thread.java:662) [rt.jar:1.6.0_23] Caused by: java.lang.NoClassDefFoundError: javax/servlet/ServletOutputStream at java.lang.Class.getDeclaredConstructors0(Native Method) [rt.jar:1.6.0_23] at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389) [rt.jar:1.6.0_23] at java.lang.Class.getConstructor0(Class.java:2699) [rt.jar:1.6.0_23] at java.lang.Class.getConstructor(Class.java:1657) [rt.jar:1.6.0_23] at org.jboss.as.web.deployment.jsf.JsfManagedBeanProcessor.deploy(JsfManagedBeanProcessor.java:108) at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:113) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final] ... 5 more Caused by: java.lang.ClassNotFoundException: javax.servlet.ServletOutputStream from [Module "deployment.com.misl.treasury.ui.war:main" from Service Module Loader] at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:190) at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:468) at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:456) at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:423) at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:398) at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:120) ... 11 more 14:10:56,628 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-4) MSC00001: Failed to start service jboss.deployment.unit."treasury.war".PARSE: org.jboss.msc.service.StartException in service jboss.deployment.unit."treasury.war".PARSE: Failed to process phase PARSE of deployment "treasury.war" at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:119) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final] at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.2.GA.jar:1.0.2.GA] at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.2.GA.jar:1.0.2.GA] at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) [rt.jar:1.6.0_23] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) [rt.jar:1.6.0_23] at java.lang.Thread.run(Thread.java:662) [rt.jar:1.6.0_23] Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: SAXException parsing vfs:/F:/work/softwares/Application Servers/JBoss/jboss-as-7.1.1.Final/jboss-as-7.1.1.Final/bin/content/treasury.war/WEB-INF/beans.xml at org.jboss.as.weld.deployment.BeansXmlParser.parse(BeansXmlParser.java:100) at org.jboss.as.weld.deployment.processors.BeansXmlProcessor.parseBeansXml(BeansXmlProcessor.java:133) at org.jboss.as.weld.deployment.processors.BeansXmlProcessor.deploy(BeansXmlProcessor.java:97) at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:113) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final] ... 5 more Caused by: org.xml.sax.SAXParseException: Premature end of file. at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:196) at org.apache.xerces.util.ErrorHandlerWrapper.fatalError(ErrorHandlerWrapper.java:175) at org.apache.xerces.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:394) at org.apache.xerces.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:322) at org.apache.xerces.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:281) at org.apache.xerces.impl.XMLScanner.reportFatalError(XMLScanner.java:1459) at org.apache.xerces.impl.XMLDocumentScannerImpl$PrologDispatcher.dispatch(XMLDocumentScannerImpl.java:903) at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:324) at org.apache.xerces.parsers.XML11Configuration.parse(XML11Configuration.java:845) at org.apache.xerces.parsers.XML11Configuration.parse(XML11Configuration.java:768) at org.apache.xerces.parsers.XMLParser.parse(XMLParser.java:108) at org.apache.xerces.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1196) at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:555) at org.apache.xerces.jaxp.SAXParserImpl.parse(SAXParserImpl.java:289) at org.jboss.as.weld.deployment.BeansXmlParser.parse(BeansXmlParser.java:94) ... 8 more 14:10:56,670 INFO [org.jboss.as] (MSC service thread 1-1) JBAS015951: Admin console listening on http://127.0.0.1:9990 14:10:56,672 ERROR [org.jboss.as] (MSC service thread 1-1) JBAS015875: JBoss AS 7.1.1.Final "Brontes" started (with errors) in 25527ms - Started 143 of 222 services (2 services failed or missing dependencies, 76 services are passive or on-demand) 14:10:56,671 INFO [org.jboss.as.server] (DeploymentScanner-threads - 2) JBAS015871: Deploy of deployment "treasury.war" was rolled back with no failure message 14:10:56,679 INFO [org.jboss.as.server] (DeploymentScanner-threads - 2) JBAS015870: Deploy of deployment "com.misl.treasury.ui.war" was rolled back with failure message {"JBAS014671: Failed services" => {"jboss.deployment.unit.\"com.misl.treasury.ui.war\".POST_MODULE" => "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"com.misl.treasury.ui.war\".POST_MODULE: Failed to process phase POST_MODULE of deployment \"com.misl.treasury.ui.war\""}} 14:10:56,851 INFO [org.jboss.as.server.deployment] (MSC service thread 1-8) JBAS015877: Stopped deployment com.misl.treasury.ui.war in 172ms 14:10:57,068 INFO [org.jboss.as.server.deployment] (MSC service thread 1-7) JBAS015877: Stopped deployment treasury.war in 395ms 14:10:57,070 INFO [org.jboss.as.controller] (DeploymentScanner-threads - 2) JBAS014774: Service status report JBAS014777: Services which failed to start: service jboss.deployment.unit."treasury.war".PARSE: org.jboss.msc.service.StartException in service jboss.deployment.unit."treasury.war".PARSE: Failed to process phase PARSE of deployment "treasury.war" service jboss.deployment.unit."com.misl.treasury.ui.war".POST_MODULE: org.jboss.msc.service.StartException in service jboss.deployment.unit."com.misl.treasury.ui.war".POST_MODULE: Failed to process phase POST_MODULE of deployment "com.misl.treasury.ui.war" 14:10:57,079 ERROR [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 1) {"JBAS014653: Composite operation failed and was rolled back. Steps that failed:" => {"Operation step-2" => {"JBAS014671: Failed services" => {"jboss.deployment.unit.\"com.misl.treasury.ui.war\".POST_MODULE" => "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"com.misl.treasury.ui.war\".POST_MODULE: Failed to process phase POST_MODULE of deployment \"com.misl.treasury.ui.war\""}}}} 14:10:57,087 ERROR [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 1) JBAS014654: Composite operation was rolled back And by the way, JBOSS_HOME\modules\javax\api\main folder only contains a module.xml, no jars. Tried to add jboss-servlet-api_3.0_spec-1.0.0.Final.jar file in that directory and updated module.xml too. But, it shows a very long trail of stacktraces :) I have even removed beans.xml. No change. I have never tried JBoss before. Any help would be highly appreciated.

    Read the article

  • Getting list of bluetooth devices nearby on iphone sdk

    - by Michael Cindric
    Hi Guys, I need to be able to search for all bluetooth devices nearby and just get there ids. I don't need to pair at all. I am using iphone 2.3 beta. Is this possible l have tried using GameKit and no luck does anyone know how to do this. BOOL result = NO; if (!session) { session = [[GKSession alloc] initWithSessionID:@"SCANNER" displayName:nil sessionMode:GKSessionModePeer]; self.session.delegate = self; [self.session setDataReceiveHandler:self withContext:nil]; self.session.available = YES; result = YES; } it dies on [self.session setDataReceiveHandler:self withContext:nil]; with the following error Scanner[42754:207] Error: 30500 -- Invalid parameter for -setDataReceiveHandler:withContext:. then ~ DNSServiceRegister callback: Ref=471fa40, Flags=2, ErrorType=0 name=00rusor1A..iPhone Simulator regtype=_q1eu29voete9jf._udp. domain=local.

    Read the article

  • Running a Java program with a .dll from Adobe AIR's native process

    - by Donny
    I would like to be able to operate a scanner from my AIR application. Since there's no support for this natively, I'm trying to use the NativeProcess class to start a jar file that can run the scanner. The Java code is using the JTwain library to operate the scanner. The Java application runs fine by itself, and the AIR application can start and communicate with the Java application. The problem seems to be that any time I attempt to use a function from JTwain (which relies on the JTwain.dll), the application dies IF AIR STARTED IT. I'm not sure if there's some limit about referencing dll files from the native process or what. I've included my code below Java code- while(true) { try { System.out.println("Start"); text = in.readLine(); Source source = SourceManager.instance().getCurrentSource(); System.out.println("Java says: "+ text); } catch (IOException e) { System.err.println("Exception while reading the input. " + e); } catch (Exception e) { System.out.println("Other exception occured: " + e.toString()); } finally { } } } Air application- import mx.events.FlexEvent; private var nativeProcess:NativeProcess; private var npInfo:NativeProcessStartupInfo; private var processBuffer:ByteArray; private var bLength:int = 0; protected function windowedapplication1_applicationCompleteHandler(event:FlexEvent):void { var arg:Vector.<String> = new Vector.<String>; arg.push("-jar"); arg.push(File.applicationDirectory.resolvePath("Hello2.jar").nativePath); processBuffer = new ByteArray; npInfo = new NativeProcessStartupInfo; npInfo.executable = new File("C:/Program Files/Java/jre6/bin/javaw.exe"); npInfo.arguments = arg; nativeProcess = new NativeProcess; nativeProcess.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onStandardOutputData); nativeProcess.start(npInfo); } private function onStandardOutputData(e:ProgressEvent):void { tArea.text += nativeProcess.standardOutput.readUTFBytes(nativeProcess.standardOutput.bytesAvailable); } protected function button1_clickHandler(event:MouseEvent):void { tArea.text += 'AIR app: '+tInput.text + '\n'; nativeProcess.standardInput.writeMultiByte(tInput.text + "\n", 'utf-8'); tInput.text = ''; } protected function windowedapplication1_closeHandler(event:Event):void { nativeProcess.closeInput(); } ]]> </fx:Script> <s:Button label="Send" x="221" y="11" click="button1_clickHandler(event)"/> <s:TextInput id="tInput" x="10" y="10" width="203"/> <s:TextArea id="tArea" x="10" width="282" height="88" top="40"/> I would love some explanation about why this is dying. I've done enough testing that I know absolutely that the line that kills it is the SourceManager.instance().getCurrentSource(). I would love any suggestions. Thanks.

    Read the article

  • The Collatz Sequence problem

    - by Gandalf StormCrow
    I'm trying to solve this problem, its not a homework question, its just code I'm submitting to uva.onlinejudge.org so I can learn better java trough examples. Here is the problem sample input : 3 100 34 100 75 250 27 2147483647 101 304 101 303 -1 -1 Here is simple output : Case 1: A = 3, limit = 100, number of terms = 8 Case 2: A = 34, limit = 100, number of terms = 14 Case 3: A = 75, limit = 250, number of terms = 3 Case 4: A = 27, limit = 2147483647, number of terms = 112 Case 5: A = 101, limit = 304, number of terms = 26 Case 6: A = 101, limit = 303, number of terms = 1 The thing is this has to execute within 3sec time interval otherwise your question won't be accepted as solution, here is with what I've come up so far, its working as it should just the execution time is not within 3 seconds, here is code : import java.util.Scanner; class Main { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int start; int limit; int terms; int a = 0; while (stdin.hasNext()) { start = stdin.nextInt(); limit = stdin.nextInt(); if (start > 0) { terms = getLength(start, limit); a++; } else { break; } System.out.println("Case "+a+": A = "+start+", limit = "+limit+", number of terms = "+terms); } } public static int getLength(int x, int y) { int length = 1; while (x != 1) { if (x <= y) { if ( x % 2 == 0) { x = x / 2; length++; }else{ x = x * 3 + 1; length++; } } else { length--; break; } } return length; } } And yes here is how its meant to be solved : An algorithm given by Lothar Collatz produces sequences of integers, and is described as follows: Step 1: Choose an arbitrary positive integer A as the first item in the sequence. Step 2: If A = 1 then stop. Step 3: If A is even, then replace A by A / 2 and go to step 2. Step 4: If A is odd, then replace A by 3 * A + 1 and go to step 2. And yes my question is how can I make it work inside 3 seconds time interval?

    Read the article

  • Piping input to a Java app with Perl

    - by user319479
    I need to write a Perl script that pipes input into a Java program. This is related to this, but that didn't help me. My issue is that the Java app doesn't get the print statements until I close the handle. What I found online was that $| needs to be set to something greater than 0, in which case newline characters will flush the buffer. This still doesn't work. This is the script: #! /usr/bin/perl -w use strict; use File::Basename; $|=1; open(TP, "| java -jar test.jar") or die "fail"; sleep(2); print TP "this is test 1\n"; print TP "this is test 2\n"; print "tests printed, waiting 5s\n"; sleep(5); print "wait over. closing handle...\n"; close TP; print "closed.\n"; print "sleeping for 5s...\n"; sleep(5); print "script finished!\n"; exit And here is a sample Java app: import java.util.Scanner; public class test{ public static void main( String[] args ){ Scanner sc = new Scanner( System.in ); int crashcount = 0; while( true ){ try{ String input = sc.nextLine(); System.out.println( ":: INPUT: " + input ); if( "bananas".equals(input) ){ break; } } catch( Exception e ){ System.out.println( ":: EXCEPTION: " + e.toString() ); crashcount++; if( crashcount == 5 ){ System.out.println( ":: Looks like stdin is broke" ); break; } } } System.out.println( ":: IT'S OVER!" ); return; } } The Java app should respond to receiving the test prints immediately, but it doesn't until the close statement in the Perl script. What am I doing wrong? Note: the fix can only be in the Perl script. The Java app can't be changed. Also, File::Basename is there because I'm using it in the real script.

    Read the article

  • Java System.in issue

    - by theo
    `public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { if (sc.next().equals("exit")){ System.out.println("EXITING"); System.exit(0); } else { System.out.println("IM STILL WORKING ok?"); } } } }` So here is a piece of code i was writing the other day to try and figure sth out (doesn't really matter what). The result of executing this code is : eIM STILL WORKING ok? eIM STILL WORKING ok? exit IM STILL WORKING ok? exit EXITING Can somebody kindly explain why this has happened?

    Read the article

  • How do I sort an array of Person Objects by using compareto()?

    - by Adam
    Here is my code: > import java.util.Scanner; import java.util.Arrays; /** This class tests the Person class. */ public class PersonDemo { public static void main(String[] args) { int count = 0; Scanner in = new Scanner(System.in); boolean more = false; Person first = null; Person last = null; while (more) { System.out.println( "Please enter the person's name or a blank line to quit"); String name = in.nextLine(); if (name.equals("")) more = false; else { Person p = new Person(name); //new person object created with inputted name Person[] people = new Person[10]; //new array of 10 person objects people[count] = p; //declare person object with index of variable count as the new person object first = people[count]; // I have no idea what to do here. This is where I'm stuck. last = people[count]; // I can't figure out what to do with this either. first.compareTo(p); //call compareTo method on first and new person object last.compareTo(p); //call compareTo method on last and new person object count++; // increase count variable } } System.out.println("First: " + first.toString()); System.out.println("Last: " + last.toString()); } } And the Person class: /** A person with a name. */ public class Person implements Comparable { /** * Constructs a Person with a name. * @param aName the person's name */ public Person(String aName) { name = aName; } public String getName() { return name; } @Override public int compareTo(Object otherObject) { Person other = (Person)otherObject; if (name.compareTo(other.name) < 0) return -1; if (name.compareTo(other.name) > 0) return 1; return 0; } /** Returns a string representation of the object. @return name of Person */ public String toString() { return "[name=" + name + "]"; } private String name; }

    Read the article

  • Split a line from a para in java

    - by John
    Hi... I am having problem splitting a para into line.... i need to first read a file then split in into lines if i get a . or ! or ? I also need to remove any extra white space... This is wad i've written so far.... try { Scanner line = new Scanner(mFile); mLine = line.nextLine(); String Matrix[]=mLine.split("\\."); for (int i = 0; i < Matrix.length; ++i) { System.out.println(Matrix[i]); } Input: Hi. My name is John. Who are you ? Output: Hi My name is John Who are you

    Read the article

  • find words in a hashset or treeset?

    - by icelated
    I am piping in a file and storing it into a treeset. I am trying to count unique words.. I am placing words that i dont want into a hashset. "a","the", "and" I want to check to see if the file contains those words, before i place them into the TreeSet.. i know i need some sort of if(word == find) ? i just dont know how to do it.. Sorry about formatting. its hard to get it correct after you paste. this is what i have.. import java.util.Scanner; import java.util.ArrayList; import java.util.TreeSet; import java.util.Iterator; import java.util.HashSet; public class Project1 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String word; String grab; int count = 0; int count2 =0; int count3 =0; int count4 =0; int number; TreeSet<String> a = new TreeSet<String>(); HashSet<String> find = new HashSet<String>(); System.out.println("Project 1\n"); find.add("a"); find.add("and"); find.add("the"); while (sc.hasNext()) { word = sc.next(); word = word.toLowerCase(); for(int i = 0; i < word.length(); i++ ) { if(Character.isDigit(word.charAt(i))) { count3++; } } //if( a.contains("a") ) //|| word.matches("and") || word.matches("the")|| word.contains("$")) //{ // count2++; // } a.add(word); if (word.equals("---")) { break; } } System.out.println("a size"); System.out.println(a.size()); // count = count2 - count; System.out.println("unique words"); System.out.println(a.size() - count2 - count3); System.out.println("\nbye..."); } }

    Read the article

  • "from _json import..." - python

    - by RoseOfJericho
    Hello, all. I am inspecting the JSON module of python 3.1, and am currently in /Lib/json/scanner.py. At the top of the file is the following line: from _json import make_scanner as c_make_scanner There are five .py files in the module's directory: __init__ (two leading and trailing underscores, it's formatting as bold), decoder, encoder, scanner and tool. There is no file called "json". My question is: when doing the import, where exactly is "make_scanner" coming from? Yes, I am very new to Python!

    Read the article

  • MC75 using symbol.imaging.device libraries for program

    - by Christy
    UPDATE: I found another library in the Windows Mobile - CameraCaptureDialog - this did the job - never did figure out the zero length available devices... Hi all, I have a .net application running on a symbol mc75 (motorola) using the scanner. I am now trying to add functionality for the camera and I am running into issues. To find the 'devices' you are supposed to use the library's 'available devices' function. With the barcode it is symbol.barcode.devices.availabledevices and it returns two items (you can scan from the scanner or using the camera device) However, when I do the camera library it does not find any devices - symbol.imaging.devices.availabledevices returns 0 I can take a picture using the software on the mc75, so I know the functionality is there, I just can't figure out how to get to it programmatically.... Does anyone have any ideas? Thanks for any help!

    Read the article

  • Recommendation for serial communications in Access 2007

    - by bglenn
    I need to communicate with a bar code scanner connected over a serial port in Microsoft Access. In older versions of Access I was able to use a wrapper around MSCOMM32.ocx that no longer seems to work. I can't use wedge communication because I need to use ACK/NACK which is only supported through the RS232 interface and I need to send messages to the scanner, which is also only supported through the RS232 interface. Are there any controls in widespread use that support serial communication in Access 2007? EDIT: In case anyone comes across this, the newest version of MSCOMM32.ocx (I believe dated 3/09) still works fine as of this writing. It is older versions of MSCOMM32.ocx that do not work.

    Read the article

  • Read entire file in Scala?

    - by Brendan OConnor
    What's a simple and canonical way to read an entire file into memory in Scala? (Ideally, with control over character encoding.) The best I can come up with is: scala.io.Source.fromPath("file.txt").getLines.reduceLeft(_+_) or am I supposed to use one of Java's god-awful idioms, the best of which (without using an external library) seems to be: import java.util.Scanner import java.io.File new Scanner(new File("file.txt")).useDelimiter("\\Z").next() From reading mailing list discussions, it's not clear to me that scala.io.Source is even supposed to be the canonical I/O library. I don't understand what its intended purpose is, exactly. ... I'd like something dead-simple and easy to remember. For example, in these languages it's very hard to forget the idiom ... Ruby open("file.txt").read Ruby File.read("file.txt") Python open("file.txt").read()

    Read the article

  • Java: opening and reading from a file without locking it.

    - by rogue780
    I need to be able to mimic 'tail -f' with Java. I'm trying to read a log file as it's being written by another process, but when I open the file to read it, it locks the file and the other process can't write to it anymore. Any help would be greatly appreciated! Here is the code that I'm using currently: public void read(){ Scanner fp = null; try{ fp = new Scanner(new FileReader(this.filename)); fp.useDelimiter("\n"); }catch(java.io.FileNotFoundException e){ System.out.println("java.io.FileNotFoundException e"); } while(true){ if(fp.hasNext()){ this.parse(fp.next()); } } }

    Read the article

  • java timer on current instance

    - by hspim
    import java.util.Scanner; import java.util.Timer; import java.util.TimerTask; public class Boggle { Board board; Player player; Timer timer; boolean active; static Scanner in = new Scanner(System.in); public Boggle() { board = new Board(4); timer = new Timer(); } public void newGame() { System.out.println("Please enter your name: "); String line = in.nextLine(); player = new Player(line); active = true; board.shuffle(); System.out.println(board); timer.schedule(new timesUP(), 20000); while(active) { String temp = in.nextLine(); player.addGuess(temp); } } public void endGame() { active = false; int score = Scoring.calculate(player, board); System.out.println(score); } class timesUP extends TimerTask { public void run() { endGame(); } } public static void main(String[] args) { Boggle boggle = new Boggle(); boggle.newGame(); } } I have the above class which should perform a loop for a given length of time and afterwards invoke an instance method. Essentially I need the loop in newGame() to run for a minute or so before endGame() is invoked on the current instance. However, using the Timer class I'm not sure how I would invoke the method I need on the current instance since I can't pass any parameters to the timertasks run method? Is there an easy way to do this or am I going about this the wrong way? (note: this is a console project only, no GUI) ========== code edited I've changed the code to the above following the recommendations, and it works almost as I expect however the thread still doesnt seem to end properly. I was the while loop would die and control would eventually come back to the main method. Any ideas?

    Read the article

  • Accidentally created a virus?

    - by Workshop Alex
    I've seen it happen reasonabley often: I write an application in Delphi and when I compile it, the virus-scanner tells me that I've created a virus and thus immediately deletes the executable again. It's annoying but reasonable easy to fix by doing a full rebuild, deleting the *.dcu files first and sometimes by simply waiting. It happens with Delphi 6, 7, 2005 and 2007, as far as I know. And Symantec, Kaspersky, McAfee and NOD32 have all been guilty of reporting these false positives. I know it's because Delphi adds timestamps to its DCU files and these timestamps end up in the final executable and apparently appear to be part of some random virus signature. I don't want to disable the virus-scanner, not even for a single folder or file. And I'm not really for a solution, but am wondering about the following: Do these false positives also occur with other compilers? Does it also happen with .NET executables? Do others also notice similar problems with Delphi?

    Read the article

  • How do I read input character-by-character in Java?

    - by Jergason
    I am used to the c-style getchar(), but it seems like there is nothing comparable for java. I am building a lexical analyzer, and I need to read in the input character by character. I know I can use the scanner to scan in a token or line and parse through the token char-by-char, but that seems unwieldy for strings spanning multiple lines. Is there a way to just get the next character from the input buffer in Java, or should I just plug away with the Scanner class? Edit: forgot to say where the input is coming from. The input is a file, not the keyboard.

    Read the article

  • Finding the average of two number using classes and methods

    - by Have alook
    I want to use methods inside class. Q: find the average of two number using classes and methods. import java.util.*; class aaa { int a,b,sum,avrg; void average() { System.out.println("The average is ="+avrg); avrg=(sum/2); } } class ave { public static void main(String args[]){ aaa n=new aaa(); Scanner m=new Scanner(System.in); System.out.println("write two number"); n.a=m.nextInt(); n.b=m.nextInt(); n.average(); } }

    Read the article

  • Brother MFC + Windows 7 [closed]

    - by juFo
    I'm using Windows 7 64bit (RTM version). I bought myself a new Brother MFC6490CW but I'm having troubles with installing the drivers. When I set compatibility to Windows Vista Service Pack 2 I can only install the scanner functionality from the Brother Solution Center and not the printer driver: Printer (driver) FAILED FAILED Scanner (driver) Installed Connected PC-FAX send FAILED FAILED PC-FAX receive Installed Connected Remote Setup Installed Connected Anybody who was a fix for this? The brother drivers for windows 7 will be released at the end of October and I can't wait so long. Need my printer.. Tnx in advance.

    Read the article

  • Java: charAt convert to int?

    - by sling
    Hi, I would like to key in my nirc number eg.S1234567I and then put 1234567 individualy as a integer as indiv1 as charAt(1), indiv2 as charAt(2), indiv as charAt(3), etc. However, when I do as the codes below, I cant seem to get even the first the number out? Any idea? Scanner console = new Scanner(System.in); System.out.println("Enter your NRIC number: "); String nric = console.nextLine(); int indiv1 = nric.charAt(1); System.out.println(indiv1);

    Read the article

  • Static method not called

    - by Smile
    I'm trying to call a static method (printABC()) in this class but it's not working. If I uncomment both of the lines marked T_T (1 and 2), it works! Why does it fail with only one of the lines? import java.util.Scanner; class pro0009 { static Scanner in = new Scanner(System.in); static int A,B,C; static void printABC(){ String ABC = in.nextLine(); ABC=ABC.replace("A"," "+A+" "); ABC=ABC.replace("B"," "+B+" "); ABC=ABC.replace("C"," "+C+" "); //System.out.print(ABC.substring(1)); System.out.print(ABC); } public static void main(String[] args){ int x = in.nextInt(); //1 int y = in.nextInt(); //2 int z = in.nextInt(); //3 if(x<y){//1<2 if(x<z){ //1<3 if(y<z){//x<y<z 2<3 //1<2<3 A=x; B=y; C=z; printABC();//T_T 1 System.out.println("Here"); //pro0009.printABC();//T_T 2 //System.out.println("Here2"); }else{ //x<z<y A=x; B=z; C=y; } }else{//z<x<y A=z; B=x; C=y; } }else{//y<x if(y<z){ if(x<z){//y<x<z A=y; B=x; C=z; }else{//y<z<x A=y; B=z; C=x; } }else{//z<y<x A=z; B=y; C=x; } } } }

    Read the article

  • Convert NSData into Hex NSString

    - by Dawson
    With reference to the following question: Convert NSData into HEX NSSString I have solved the problem using the solution provided by Erik Aigner which is: NSData *data = ...; NSUInteger capacity = [data length] * 2; NSMutableString *stringBuffer = [NSMutableString stringWithCapacity:capacity]; const unsigned char *dataBuffer = [data bytes]; NSInteger i; for (i=0; i<[data length]; ++i) { [stringBuffer appendFormat:@"%02X", (NSUInteger)dataBuffer[i]]; } However, there is one small problem in that if there are extra zeros at the back, the string value would be different. For eg. if the hexa data is of a string @"3700000000000000", when converted using a scanner to integer: unsigned result = 0; NSScanner *scanner = [NSScanner scannerWithString:stringBuffer]; [scanner scanHexInt:&result]; NSLog(@"INTEGER: %u",result); The result would be 4294967295, which is incorrect. Shouldn't it be 55 as only the hexa 37 is taken? So how do I get rid of the zeros? EDIT: (In response to CRD) Hi, thanks for clarifying my doubts. So what you're doing is to actually read the 64-bit integer directly from a byte pointer right? However I have another question. How do you actually cast NSData to a byte pointer? To make it easier for you to understand, I'll explain what I did originally. Firstly, what I did was to display the data of the file which I have (data is in hexadecimal) NSData *file = [NSData dataWithContentsOfFile:@"file path here"]; NSLog(@"Patch File: %@",file); Output: Next, what I did was to read and offset the first 8 bytes of the file and convert them into a string. // 0-8 bytes [file seekToFileOffset:0]; NSData *b = [file readDataOfLength:8]; NSUInteger capacity = [b length] * 2; NSMutableString *stringBuffer = [NSMutableString stringWithCapacity:capacity]; const unsigned char *dataBuffer = [b bytes]; NSInteger i; for (i=0; i<[b length]; ++i) { [stringBuffer appendFormat:@"%02X", (NSUInteger)dataBuffer[i]]; } NSLog(@"0-8 bytes HEXADECIMAL: %@",stringBuffer); As you can see, 0x3700000000000000 is the next 8 bytes. The only changes I would have to make to access the next 8 bytes would be to change the value of SeekFileToOffset to 8, so as to access the next 8 bytes of data. All in all, the solution you gave me is useful, however it would not be practical to enter the hexadecimal values manually. If formatting the bytes as a string and then parsing them is not the way to do it, then how do I access the first 8 bytes of the data directly and cast them into a byte pointer?

    Read the article

< Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >