Input via java.util.Scanner
I know it's possible for JDeveoper 10G to take input via BufferedReader, is the same possible using the scanner class as in:
Scanner input = new Scanner(System.in);
System.out.println("Enter your age");
int age = input.nextInt();
System.out.println("You are " + age);
JDeveloper can't seem to take imput from the scanner class. Is there a way arround this?
Andrew.
I am aware of that Shay, but it does not work for the Scanner Class, at least for me anyway.
Try the following example code in JDeveloper 10.1.3 I constructed this to put the Scanner though its paces for the Job I need.
It works very well when used from the command line, but cannot be read with JDeveloper even with those settings you describe turned on.
Scanner input = new Scanner(System.in);
System.out.println("Enter your age");
int age = input.nextInt();
System.out.println("You are " + age);
System.out.println("what is your name?");
String name = input.next();
System.out.println("Yout name is " + name);
System.out.println("Please enter your height");
double height = input.nextDouble();
System.out.println("So you are " + height + " tall.");
System.out.println("What sex are you M/F?");
char sex = input.next().charAt(0);
if (sex == 'm' || sex == 'M')
System.out.println("Ahh so your a male");
else if (sex == 'f' || sex == 'F')
System.out.println("Ah you your a femaile.");
System.out.println("You are English right? (True/alse)?");
boolean eng = input.nextBoolean();
System.out.println("Right so it's " + eng + " that your English. You are " + age + " years of age, and your name is " + name + ", your sex is " + sex + " and you are " + height + " tall.");
Message was edited by:
Scottie_UK
Similar Messages
-
Error when importing java.util.Scanner
Agh! I'm in an introduction to computer science course, and I am writing a program as an assignment that's due tomorrow.
I have imported java.util.Scanner before, but I've only run it on the Windows PCs in the lab, whereas I am currently on a Mac. I've updated to the latest version of Java (through the software update), and I'm running Tiger (also fully updated).
I'm using Dr. Java to write the programs, but I tried using the very same thing in Eclipse and it didn't work. Here's my program:
import java.util.Random;
import java.util.Scanner;
public class Password {
public static void main(String[] args) {
//create a Scanner object to read from the keyboard:
String password;
Scanner scanner = new Scanner(System.in);
Random randomizer = new Random();
System.out.println("Please enter a string containing candidate characters.");
String input = scanner.next();
int charLength = length(input);
System.out.print("Random password: ");
System.out.print(input.substring(randomizer.nextInt(charLength)));
System.out.print(input.substring(randomizer.nextInt(charLength)));
System.out.print(input.substring(randomizer.nextInt(charLength)));
System.out.println(input.substring(randomizer.nextInt(charLength)));
And, here's my errors:
4 errors found:
File: /Users/brianmoore/Desktop/Password.java [line: 11]
Error: cannot resolve symbol
symbol : class Scanner
location: package util
File: /Users/brianmoore/Desktop/Password.java [line: 18]
Error: cannot resolve symbol
symbol : class Scanner
location: class Password
File: /Users/brianmoore/Desktop/Password.java [line: 18]
Error: cannot resolve symbol
symbol : class Scanner
location: class Password
File: /Users/brianmoore/Desktop/Password.java [line: 22]
Error: cannot resolve symbol
symbol : method length (java.lang.String)
location: class Password
Any ideas?Ok. I figured it out. On the Dr. Java page, this is what helped me:
Please verify the following:
- Open "/Applications/Utilities/Java/J2SE 5.0/Java
Preferences";
make sure "J2SE 5.0" is at the top of the list under
"Java
Application Runtime"
- Open DrJava; go to Edit->Preferences; make sure
"Tools.jar
Location", "JSR-14 Location", and "JSR-14
Collections Path"
are all blank
- Open the Help->About dialog box; make sure the "DrJava
Version" listed is 20050601-0007 or later (that is, later
than
June 1, 2005)
- Go to the "System Properties" tab in the
"About" box; make
sure "java.version" is 1.4.2.
Let us know what you find out if you're still having
trouble.
Thanks for your help! -
The import "java.util.scanner" is not vaild
I am experiment with the java.util.scanner API after compiling the code below I received the following error:
The import "java.util.Scanner" is not valid, since it does not name a type in a package.
I declared a string variable should that suffice?
import java.util.Scanner;
public class Echo {
public static void main (String[] args)
String message;
Scanner scan = new Scanner (System.in);
System.out.println ("enter something:");
message = scan.nextLine();
System.out.println ("hey you entered: \"" + message + "\"");
}Most IDEs let you select and installed JDK for them to use. Check out that IDE's preferences.
Otherwise, start here and learn to do it with a simple text editor or programmer's editor, and the command line.
http://java.sun.com/docs/books/tutorial/getStarted/cupojava/ -
Regex & java.util.Scanner
I am trying to make a simple txt parser using regular expressions but the problem has
appeared.
The program's code is too long so I have stated only the part of the code implementing
the method data_types() which doesn't work properly, it reads only two types (String) and (Boolean). If someone could help me I would be very gratefull.Why method doesn't read the rest of data types in my data_xml.xml file?
here is the code >
class SimpleScann{
enum PARSE{
TABLE_NAME("(\\w*)"),COLUMN_NAME("(\\w*\\Q(\\E)"),DATA_TYPE("(\\Q(\\E\\w*\\Q)\\E)");
private String $pattern;
PARSE(String pattern){
$pattern=pattern;
public String PATTERN(){
return $pattern;
static void data_types() throws Exception{
File parse_file= new File("data_type.txt");
Scanner scann_input = new Scanner(parse_file);
int flag= Pattern.CASE_INSENSITIVE;
Pattern pattern=Pattern.compile(PARSE.DATA_TYPE.PATTERN(),flag);
Matcher matcher=null;
while(scann_input.hasNextLine()){
matcher=pattern.matcher(scann_input.nextLine());
if(matcher.find()){
System.out.printf("%s\n",matcher.group());
public static void main(String args[])
try{
data_types();
}catch(Exception e){
e.printStackTrace();
and here is the data_type.txt<table > Table radi
ako su zatvoreni tagovi <>
<column>
Ime(String), Prezime(String), JMBG(Integer) ,
Enabled(Boolean)
<\column>
best regards,
NikolaThe reason you're only matching two items is because you're reading the file one line at a time and applying the regex once per line. As Tim said, you can fix that by using while instead of if, but the real problem is much deeper: you're trying to write a scanner in the sense of a lexical analyzer, and that isn't what java.util.Scanner is for. I strongly recommend you start over, this time using Pattern and Matcher directly, not Scanner. If you happen to have a copy of MRE 3ed, there's an example of what you're trying to do on page 400. (Unfortunately, Friedl has just moved back to Japan, and hasn't had time to update the book's web site, or I could point you to the code online.) I don't have time to go into this right now, but you should pay particular attention to the find(int) method and the \G anchor.
-
What the HELL with java.util.Scanner
Hello people...
Somebody have a pointer that teaches how to work with Scanner, or everybody fells like me, as this API just don't work well!!!?
At this right moment I have the same JAR file, run something at linux and work well, but when at windows got an exception...http://java.sun.com/developer/JDCTechTips/2004/tt1201.html
http://java.sun.com/docs/books/tutorial/essential/io/scanning.html
~Tim -
Unexpected java.util.Scanner behaviour
Is it just me or do others find the following behaviour strange? It seems that in order to break out of the loop in the following, it's necessary to enter some character(s) unparseable as a double. Hitting return won't cause it to break:
public static void scanInts(String[] args) {
Scanner scanner = null;
List<Double> coefficients = new ArrayList<Double>();
double x = Double.NaN;
try {
scanner = new Scanner(System.in);
while(scanner.hasNextDouble()) {
double d = scanner.nextDouble();
System.out.println("double=" + d);
coefficients.add(d);
System.out.println("Now out of loop");
finally {
System.out.println(coefficients);
scanner.close();
}I don't think it's strange; Scanner is supposed to ignore extra whitespace and line breaks are whitespace. You can change this behaviour by setting the delimiter to something else, like:scanner.useDelimiter("[ ]*");
-
Hi there,
I have the following code:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Input {
public static String readString() {
return _readString(null, null);
public static String readString(String title) {
return _readString(title, null);
public static String readString(String title, String error) {
return _readString(title, error);
private static String _readString(String title, String error) {
Scanner input = new Scanner(System.in);
boolean loop = true;
String str = null;
while(loop) {
try {
if(title != null) {
System.out.print(title);
str = input.nextLine();
loop = false;
} catch(InputMismatchException e) {
if(error != null) {
System.out.println(error);
input.close();
return str;
public class Program {
public static void main(String[] args) {
String a;
a = Input.readString("VALUE: ");
System.out.println(a);
a = Input.readString("\nVALUE: ");
System.out.println(a);
}And the following output:
VALOR: Hello World!
Hello World!
VALUE: Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1516)
at Input._readString(Input.java:29)
at Input.readString(Input.java:11)
at Program.main(Program.java:21)The first value is read without any problems but the second throws that exception. Why is this happening? I "fixed" it by removing the input.close(); line but this makes no sense to me. First because I think that I should close the Scanner after using it and second because every time I call the _readString() method, a new Scanner instance will be created, so it doesn't make sense... At least for me, but that's why I'm posting on this forum section, cause I'm new to Java.
Can someone explain me why exactly does this happen and if possible, a better solution then to remove the input.close()? It just doesn't make any sense to me create a new Scanner instance every time I call the _readString() method and leave it there without closing it...First because I think that I should close the Scanner after using it and
second because every time I call the _readString() method, a new Scanner instance will be createdUmm, NO.
Let me see if I understand things in the Static world correctly.
Notice that you have everything declared as "Static" in your Class. A static is only initialized at programs start and everything in your JVM can then us it (well that stuff that has a reference to it). Since it's static, when you close the Scanner, you are closing the only instance that will ever exist in your object.
For things to work how you think they should, get rid of the Static declarations (excpet in main, where you have to keep them). -
Static class containing scanner throws java.util.NoSuchElementException
I use the scanner class pretty often in my coding and recently i have been trying to create a static method i can put in an external class to do the scanning for me and trap any errors.
I seem to be able to create the class successfully but i have a slight problem in that i cannot use the method twice in the same program without having it throw a java.util.NoSuchElementException
If anyone could figure out what error i have made and suggest a way to fix it i would be very grateful
code is as follows:
Scan.java:
// name information removed for privacy
// class info removed for privacy
Assignment: 4.3,
File Name: /ASSIGNMENTS/ASSIGNMENT_4/Part3/Scan.java
import java.util.Scanner;
public class Scan
public static double nextDouble (String prompt)
// variable to hold the result
double result = 0.0;
// variable to determine if input was ok
Boolean inputOK = false;
// do-while loop to get some input
do
// print the prompt. what do you want to ask for?
System.out.print ( prompt );
// Try to scan and capture the input and catch the exception
try
// create the scanner object
Scanner scan = new Scanner (System.in);
// parse the input`
result = scan.nextDouble();
// if we reach this step then good. we got good input let's exit the loop
inputOK = true;
// close the scanner
scan.close();
// oops we got an error!
catch (java.util.InputMismatchException e)
// inform the user of the error
System.out.println ("That is not a number! Try again. \n");
// input was not ok so we can't exit the loop yet
inputOK = false;
// keep looping as long as inputOK is false
} while (!inputOK);
// return out result
return result;
}Mathematics.java:
// name information removed for privacy
// class information removed for privacy
* Assignment: 4.3
* File Name: ASSIGNMENTS/ASSIGNMENT_4/Part3/Mathematics.java
// Import Scanner class
import java.util.Scanner;
//Class Body
public class Mathematics{
// Main method. AUTO EXECUTE
public static void main(String[] args)
// additional variable declarations removed for brevity
// Create double precision floating point variables
double coeff4 = 0.0, coeff3 = 0.0, coeff2 = 0.0, coeff1 = 0.0, cons = 0.0;
coeff4 = Scan.nextDouble("Enter the coefficient of x^4 (0.0 if none): ");
coeff3 = Scan.nextDouble("Enter the coefficient of x^3 (0.0 if none): ");
coeff2 = Scan.nextDouble("Enter the coefficient of x^2 (0.0 if none): ");
coeff1 = Scan.nextDouble("Enter the coefficient of x (0.0 if none): ");
cons = Scan.nextDouble("Enter the constant (0.0 if none): ");
// do fun things with input (code removed for brevity)
}output looks like this
dragonfly@Home:~/ASSIGNMENTS/ASSIGNMENT_4/Part3$ java Mathematics
Enter the coefficient of x^4 (0.0 if none): hello boys!
That is not a number! Try again.
Enter the coefficient of x^4 (0.0 if none): 1.2.
That is not a number! Try again.
Enter the coefficient of x^4 (0.0 if none): d
That is not a number! Try again.
Enter the coefficient of x^4 (0.0 if none): 1
Enter the coefficient of x^3 (0.0 if none): Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:817)
at java.util.Scanner.next(Scanner.java:1431)
at java.util.Scanner.nextDouble(Scanner.java:2335)
at Scan.nextDouble(Scan.java:23)
at Mathematics.main(Mathematics.java:34)
dragonfly@Home:~/ASSIGNMENTS/ASSIGNMENT_4/Part3$Through trial and error i seem to have hit upon a solution to my problem. i am stress testing it now but i think it will hold up admirably
import java.util.Scanner;
public class Scan
// scan in a double without a prompt. catch and handle any exceptions
public static double nextDouble ()
return nextDouble("");
// give the user a prompt and then scan in a double. catch and handle any exceptions
public static double nextDouble (String prompt)
// variable to hold the result
double result = 0.0;
// variable to determine if input was ok
boolean inputOK = false;
// do-while loop to get some input
do
// print the prompt. what do you want to ask for?
System.out.print ( prompt );
// Try to scan and capture the input and catch the exception
try
// Call private method to do the actual scanning
result = scanDouble();
// if we reach this step then good. we got good input let's exit the loop
inputOK = true;
// oops we got an error!
catch (java.util.InputMismatchException e)
// inform the user of the error
System.out.println ("That is not a number! Try again. \n");
// input was not ok so we can't exit the loop yet
inputOK = false;
// keep looping as long as inputOK is false
} while (!inputOK);
// return out result
return result;
// Helper method to nextDouble
private static double scanDouble()
// hold the result
double result=0.0;
// create the scanner object
Scanner scan = new Scanner (System.in);
// parse the input
// If input was not of proper type this call will fail with :
// java.util.InputMismatchException
// and return control to calling method
result = scan.nextDouble();
// Return our findings
return result ;
} -
Errormessage: "java.util.NoSuchElementException"
Why can't I compile the following code?
Im using MAC OSX 10.4.10 with the latest J2SE 5.0 Preferences
import java.util.Scanner;
class gumballs {
public static void main(String args[]) {
Scanner myScanner = new Scanner(System.in);
int gumballs;
int kids;
int gumballsPerKid;
System.out.print("How many gumballs? How many kids? ");
gumballs = myScanner.nextInt();
kids = myScanner.nextInt();
gumballsPerKid = gumballs / kids;
System.out.print("Each kid gets ");
System.out.print(gumballsPerKid);
System.out.println(" gumballs.");
} I get the following error when I try to compile the code
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:817)
at java.util.Scanner.next(Scanner.java:1431)
at java.util.Scanner.nextInt(Scanner.java:2040)
at java.util.Scanner.nextInt(Scanner.java:2000)
at gumballs.main(gumballs.java:14)
How many gumballs? How many kids?
Program exited with status 1.Please help me! im just a newbie trying to learn java..
ThanksIm on XP and getting the same error message :(
It compiles fine but when I run it and I am done inputing it gives me that same error message.
And yes I am running the latest version of JDK
Also I am having a strange probleming trying to run my files in the command prompt. I can get it to compile fine javac helloworldapp.java and it creates the class. I know my Universal variables are set correctly but when I try java helloworldapp after I have compiled I get a similar error message. I dont know if this is at all related I just started using Java last night so I am a total newb. I would appreciate if one of you pro's could help me out.
thank you -
Java.util.inputmismatchException
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 Trials.GradeBook.inputGrades(GradeBook.java:48)
at Trials.GradeBookTest.main(GradeBookTest.java:18)
could you plz xplain y i get this error message during building processimport java.util.Scanner;
public class GradeBook {
private String courseName;
private int total;
private int gradeCounter;
private int aGrade;
private int bGrade;
private int cGrade;
private int dGrade;
private int fGrade;
// constructor of the class GradeBook
public GradeBook(String name1) {
courseName=name1;
// initialize the value of the field courseName
public void setCourseName(String name){
courseName=name;
// get the value of the field and return it to method caller
public String getCourseName(){
return courseName;
// input the grades from user useing sentinel control loop
public void inputGrades(){
int grade;
Scanner input = new Scanner(System.in);
System.out.printf("%s\n%s\n%s\n",
"Enter the integer grades between 0-100:",
"Type end-of-file key to terminate the input",
"(i.e <Ctrl>z then press Enter on Windows)");
while(input.hasNext()){
grade = input.nextInt();
total += grade;
++gradeCounter;
// call a method to increment appropriate grade counter
incrementGradeCounter(grade);
// mehtod incrementGradeCoutner counts using switch-case loop
public void incrementGradeCounter(int grade){
switch(grade/10){
case 10:
case 9:
++aGrade;
break;
case 8:
++bGrade;
break;
case 7:
++cGrade;
break;
case 6:
++dGrade;
break;
default:
++fGrade;
break;
// create a method that displays welcome message to grade book user
public void displayMessage(){
System.out.printf("\nWelcome to the Grade Book for %s\n",
getCourseName());
public void displayReport(){
if ( gradeCounter != 0 ){
System.out.printf("The total of %d grade entered is %d\n",
gradeCounter,total);
System.out.printf("The class average is %.2f",
(double)total/gradeCounter);
System.out.printf("%s\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n",
"Number of students who recieved each grade",
"A: ",aGrade,
"B: ",bGrade,
"C: ",cGrade,
"D: ",dGrade,
"F: ",fGrade);
else
System.out.println("Sorry! no grade was entered\n" +
"THANK YOU FOR USING THE GRADE BOOK");
public static void main(String args[]) {
// create an object of Class GradeBook with its own contructor
GradeBook myGradeBook = new GradeBook("CS101 Java Programming");
myGradeBook.displayMessage();
myGradeBook.inputGrades();
myGradeBook.displayReport();
}} -
Please help - Java.util Error! Have no clue! - Please Help
Hey guys,
Im very new to java,
With my code here :
import.java.util.Scanner;
public class delta{
public static void main(String args[]){
Scanner done = new Scanner(System.in.());
System.out.println(done.nextLine);
}I am unable to compile due to a Java.utill error!, can someone please tell me where i am going wrong? or provide me with a guide on how to setup netbeans because i think that is where i am going wrong !
-thanks!815788 wrote:
its
package <error>.java.util does not exist.it also doesn't let me compile because of this.And, to fill in the information you didn't yet post, this referred to your "import" line, right? Please don't hoard information. Tell us what the problem is.
As to the fix, look at your "import" statement and compare it to "import" statements in your textbook or tutorial or notes or whatever you're learning from. -
Doubt on util.Scanner.java
Hello Everybody,
I have a doubt about util.Scanner.java. I searched in java API, but there is no such class definition found. BUt, i saw in a program, importing
this util.Scanner.java to accept commond line arguments. egample:
import util.java.Scanner;
public class Accept{
public void getNumbers()
Scanner input=new Scanner(System.in)
... ... ... ... I don't understand how does this code work s?? Can anyone please explain me??
Thanks for taking time.
Regards,
AshviniIt's not included until 5.0. It might theoretically be possible to extract that class from rt.jar and put it into your classpath, but I doubt it would be that simple, if it would even work at all. It probably relies on other 5.0 classes, and may rely on 5.0-only features. Even if it doesn't, the class itself may be marked as 5.0, which would cause them to be rejected by a < 5.0 VM.
It shouldn't be too difficult to write the most commonly used methods yourself, or maybe you could find something similar at sourceforge or jakarta or someplace. -
Summary:
JDK 1.7.0_09 and wsimport and xjc that comes with it.
Global JAXB binding to map xs:date to java.util.Date
I have the following external bindings file:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
elementFormDefault="qualified" attributeFormDefault="unqualified"
jaxb:extensionBindingPrefixes="xjc" jaxb:version="2.1">
<xs:annotation>
<xs:appinfo>
<jaxb:globalBindings>
<xjc:serializable />
<jaxb:javaType name="java.util.Date" xmlType="xs:date" parseMethod="au.com.xxx.jaxb.DateAdapter.parseDate" printMethod="au.com.xxx.jaxb.DateAdapter.printDate" />
</jaxb:globalBindings>
</xs:appinfo>
</xs:annotation>
</xs:schema>The au.com.xxx.jaxb.DateAdapter code is as follows:
package au.com.xxx.jaxb;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.xml.bind.DatatypeConverter;
public class DateAdapter {
public static Date parseDate(String s) {
return DatatypeConverter.parseDate(s).getTime();
public static String printDate(Date dt) {
Calendar cal = new GregorianCalendar();
cal.setTime(dt);
return DatatypeConverter.printDate(cal);
}When I run the following wsimport from the command line, I get:
salvojo@AUD20901BL /cygdrive/c/workspace/JSF/insurance
$ /cygdrive/c/java/jdk1.7.0_09/x64/bin/wsimport -keep -s gen-src -b external/wsdl/jaxb-bindings.xml -wsdllocation /wsdl/Member.wsdl -d WebContent/WEB-INF/classes external/wsdl/Member.wsdl
parsing WSDL...
Generating code...
Compiling code...
C:\workspace\JSF\insurance\gen-src\org\w3\_2001\xmlschema\Adapter1.java:13: error: package au.com.xxx.jaxb does not exist
return (au.com.xxx.jaxb.DateAdapter.parseDate(value));
^
C:\workspace\JSF\insurance\gen-src\org\w3\_2001\xmlschema\Adapter1.java:17: error: package au.com.xxx.jaxb does not exist
return (au.com.xxx.jaxb.DateAdapter.printDate(value));
^
2 errors
compilation failed, errors should have been reportedWhich means that wsimport or xjc needs to know the classpath to find au.com.xxx.jaxb.DateAdapter.
But how do I pass the classpath from wsimport to the JAXB compiler ?
There is the -B option in wsimport, but I could not get it to work.
If I read it correctly, I should be able to pass the -classpath option to the JAXB compiler from wsimport via -B.
I tried:
salvojo@AUD20901BL /cygdrive/c/workspace/JSF/insurance
$ /cygdrive/c/java/jdk1.7.0_09/x64/bin/wsimport -keep -s gen-src -B"-classpath WebContent/WEB-INF/classes" -b external/wsdl/jaxb-bindings.xml -wsdllocation /wsdl/Member.wsdl -d WebContent/WEB-INF/classes external/wsdl/Member.wsdl
no such JAXB option: -classpath WebContent/WEB-INF/classes
Usage: wsimport [options] <WSDL_URI>
where [options] include:
-b <path> specify jaxws/jaxb binding files or additional schemas
(Each <path> must have its own -b)
-B<jaxbOption> Pass this option to JAXB schema compiler
-catalog <file> specify catalog file to resolve external entity references
supports TR9401, XCatalog, and OASIS XML Catalog format.
-d <directory> specify where to place generated output files
<...snipped...>... where WebContent/WEB-INF/classes is the classpath where au.com.xxx.jaxb.DateAdapter.class could be found. Obviously it did not like it.
Also, why is wsimport generate org.w3._2001.xmlschema.Adapter1.java ? All it is doing is wrapping up the exact same call that I have specified in my DateAdapter. How can I tell wsimport or xjc to NOT create that extra Adapter1.java and simply directly use my DateAdapter ??create additional column of type LONG to represent date.
dateFormat is of type java.util.Date:
long newLongDate = dateFormat.getTime();
select object(b) from MyEntity b where b.MYLONGDATE > ?1 and b.MYLOGDATE <= ?2 -
Java.util.NoSuchElementException: No line found
Hey there...I am using a program that scans in strings from a file. Here is my code for that.
case 1:
System.out.println("Option 1 - Create new Sport Stacker");
getSportStackerInfo( line );
break;Calls...
public static void getSportStackerInfo( Scanner line )
name = line.nextLine();
birthplace = line.nextLine();
}Okay, I have to scan a lot more, but I can't get to that point because I get the No line found error. The name scans fine, but then I get the no line on birthplace, so I can't get past it. Is there any way to keep it from doing this? Here's the first few lines of my txt file...
5
1
John Smith
Male
16
4
638
12
yes
noThank you!Try this program:
import java.util.*;
import java.io.File;
import java.io.IOException;
public class ScannerHelp
public static void main( String args[] )
Scanner input = new Scanner( System.in );
print( "Enter filename: " );
String filename = input.nextLine();
Scanner scan = null;
try
scan = loadFile( filename );
catch ( IOException e )
e.printStackTrace();
String line = null;
while ( (line=scan.nextLine()) != null )
println( line );
public static Scanner loadFile( String filename )
throws IOException
return new Scanner( new File( filename ) );
public static void printf( String str, Object... args )
System.out.printf( str, args );
public static void println( String line )
System.out.println( line );
public static void print( String str )
System.out.print( str );
} -
Need help with java file scanner and objects
Hi, i've got an assignment that asks me to do these, but i cant seem to get around in solving it. Any help will be much appreciated. TYVM!
Create a class called TVProgram that can store some important details of a television program:
- name of the show
- the channel the show is on
- the start time (in 24-hour format)
- the end time (in 24-hour format)
Write a program that uses this class.
Your program will read a list of TV programs, making up a schedule for an evening's TV: for you convenience, you will be able to download a sample file listing. The listing will consist of one line for each of the above fields, in the above order, for each program, followed by a line containing only the "#" character. For example, here is the start of such a file.
At the Movies
ABC
1800
1830
The Einstein Factor
ABC
1830
1900
Your program should start with a little menu to prompt whether to read from standard input or a file:
Please choose a number for the way you will input the TV schedule:
1. Read from standard input
2. Input from a file
Your program should first read the complete schedule, then loop through all the programs in the schedule and prompt the user as to whether they want to record the program or not. For example, the program should print:
At the Movies is showing on ABC from 1800 to 18.30.
Do you want to record it: type Y or N.
If the user types Y then the program sets this T Vprogram to be recorded. If the user types N, the program goes to the next entry and prompts the user again. If the user types something other than a Y or N (or y or n), then the program should prompt for a proper answer:
Do you want to record it: type Y or N.
Once the complete schedule has been shown to the user, the program loops through those that the user has said they want to record and checks for any clashes---i.e. any times at which the user wants to record two programs at the same time. For any clashes, your program should show these to the user and insist that only one be selected for being recorded. For example:
At 1830 you want to record both 1. The Einstein Factor on ABC and 2. The Biggest Loser on Ten.
Please pick option 1 or 2 to record.
Again, if the user selects an option other than 1 or 2 in the above, then the program should make the user to make another selection until they type a legal value.
If the schedule is in time-start order (see "Assumptions" below), then a simple way to check for clashes is:
- as you loop through the schedule of shows, keep track of the latest end-time the user wants to record;
- if any program the user says they want to record has a start-time before this latest end-time, then this is a clash.
There are different ways to keep track of clashes: you can keep an array (a list of clashes) of arrays (each of these is the list of clashing programs); you could create a Clash class.
Finally, after going through all clashes, print out the list of programs that the user still wants recorded.
Here is the list of programs that will be recorded for you:
From 1830 to 1930, The Biggest Loser, on Ten.
From 1930 to 2030, Who Do You Think You Are, on SBS
-----* @(#)TVProgram.java
* @author Okky Satya
* @version 1.00 2008/3/29
import java.util.*;
import java.io.*;
public class TVProgram {
private String name;
private String chnl;
private int strt;
private int ends;
public TVProgram(String showName, String channel, int start, int end ){
this.name = showName;
this.chnl = channel;
this.strt = start;
this.ends = end;
public static void readFileInput() {
List prog = new ArrayList();
Scanner inputFile = null;
try
inputFile = new Scanner(new File("tv_schedule"));
catch (FileNotFoundException fe)
System.out.println("File not found!");
System.exit(0);
while(inputFile.hasNext()== true){
while (inputFile.nextLine()!="##")
new TVProgram;
public static void readInput(){
public static void loopInput(){
public static void showList(){
public static void checkUserList(){
public static void main(String[] args){
int menuChoice = 0;
System.out.println("Please choose a number for the way you will input the TV schedule:\n 1. Read from standard input\n 2. Input from a file");
switch(menuChoice){
case 1:
readInput();
break;
case 2:
readFileInput();
break;
loopInput();
checkUserList();
showList();
}
Maybe you are looking for
-
A HOST command in PL/SQL?
Hello guys! :) I need to execute some SFTP commands on the database server to another SFTP server. In oracle forms theres a built in called "HOST" which executes native commands on the server. Is there something similar to that in PL/SQL? Also, im wo
-
I'm using Motion 4 and PS CS5. I've created a psd with grouped layers. I want to import it into Motion with the groups and layers intact. When I do File, Import I get the option to merge the layers, all layers or individual layers. In the individual
-
Where do I change the settings for spotlight?
I've looked in basic settings, through all the layers of screens and not found spotlight settings. I can't find it within the spotlight application - hoping for a icon of tools but nothing. It must be somewhere - can someone lead me there? thanks.
-
Text determination for Bulk Shipment or TD shipment
Hello experts, Please help to understand how can we do Text determination in bulk shipments. I have looked into VOTXN, but that is for LE shipments. I also looked at the default texts for Shipment header, but not able to get the object. Can anybody h
-
Gamers: Does anyone play Soldier of Fortune II?
I was finally able to get a copy of my favorite game after switching to my Mac. The problem is that the game keeps crashing. It makes it through the first cinematic but then crashes each time. I've tried re-installing it many times. The system requir