Help with using Scanner Class

Hi there - I'm a newbie to Java and may have posted this in the wrong forum previously.
I am trying to modify a program so instead of using a BufferReader, a scanner class will be used. It is basically a program to read in a name and then display the variable in a line of text.
Being new to Java and a weak programmer, I am getting in a mess with this and missing something somewhere. I don't think I'm using scanner in the correct way.
Any help or pointers would be good. There are 2 programs of code being used. 'Sample' and 'Run Sample'
Thanks in advance.
Firstly, this program will run named 'Sample'
<code>
* Sample.java
* Class description and usage here.
* Created on 15 October 2006
package internetics;
* @author John
* @version 1.2
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
// import com.ralph.*;
public class Sample extends JFrame
implements java.awt.event.ActionListener{
private JButton jButton1; // this button is for pressing
private JLabel jLabel1;
private String name;
/** Creates new object ChooseFile */
public Sample() {
initComponents();
name = "";
selectInput();
public Sample(String name) {
this();
this.name = name;
private void initComponents() {
Color bright = Color.red;
jButton1 = new JButton();
jLabel1= new JLabel();
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
exitForm(evt);
getContentPane().setLayout(new java.awt.GridLayout(2, 1));
jButton1.setBackground(Color.white);
jButton1.setFont(new Font("Verdana", 1, 12));
jButton1.setForeground(bright);
jButton1.setText("Click Me!");
jButton1.addActionListener(this);
jLabel1.setFont(new Font("Verdana", 1, 18));
jLabel1.setText("05975575");
jLabel1.setOpaque(true);
getContentPane().add(jButton1);
getContentPane().add(jLabel1);
pack();
public void actionPerformed(ActionEvent evt) {
System.out.print("Talk to me " name " : ");
try {
jLabel1.setText(input.readLine());
} catch (IOException ioe) {
jLabel1.setText("Ow! You pushed my button");
System.err.println("IO Error: " + ioe);
/** Exit this Application */
private void exitForm(WindowEvent evt) {
System.exit(0);
/** Initialise and Scan input Stream */
private void selectInput() {
input = new Scanner(new InputStreamReader(System.in));
/**int i = sc.nextInt(); */
/** Getter for name prompt */
public String getName() {
return name;
/** Setter for name prompt */
public void setName(String name) {
this.name = name;
* @param args the command line arguments
public static void main(String args[]) {
new Sample("John").show();
</code>
and this is the second program called 'RunSample will run.
<code>
class RunSample {
public static void main(String args[]) {
new internetics.Sample("John").show();
</code>

The compiler I'm using is showing errors in these areas of the code. I've read the tutorials and still can't get it. They syntax for the scanner must be in the wrong format??
the input.readLine appears incorrect below.
  public void actionPerformed(ActionEvent evt) {
    System.out.print("Talk to me " +name+ " : ");
    try {
        jLabel1.setText(input.readLine());
    } catch (IOException ioe) {
      jLabel1.setText("Ow! You pushed my button");
      System.err.println("IO Error: " + ioe);
    }and also here...
the input is showing errors
  /** Initialise and Scan input Stream */
  private void selectInput() {
    input = new Scanner(new InputStreamReader(System.in));
   /**int i = sc.nextInt(); */
  }Thanks

Similar Messages

  • Need help with using selected class with includes...

    Hi guys,
    I'm using PHP includes for my site and in the header include I have my main navigation - so it's drawn in to whatever page the user goes to from header.php.
    I want to have a 'selected' <li> class for the navigation so the relevant button is highlighted depending on which page/section the user is on...
    How would I go about implementing it into header.php - is there a way I can put a bit of PHP in each of the pages to make the appropiate <li> in header.php use the 'selected' class?
    Thank you and I hope to hear from you.
    SM

    I'm sure there will be an easier way than this for PHP but if you give each menu item a class, you can then give each <body> a different id (or class) to determine where the user is.
    Eg:
    CSS
    nav li.menu_home a{style here} /* class is 'menu_home' for home menu item */
    #home nav li.menu_home a{style here} /* the id of 'home' is added to the body tag on the home page, <body id="home"> */
    HTML
    <body id="home">
    <!-- navigation include -->
    <nav>
    <ul>
    <li class="menu_home"><a href="">Home</a></li>
    </ul>
    </nav>
    <!-- end navigation include -->
    </body>
    Or you could try searching for a javascript method.

  • Help using scanner class to count chars in file

    Hi all, I am learning Java right now and ran into a problem. I need to use the Scanner class to accurately count the number of chars in a file including the line feed chars 10&13.
    This what I have and it currently reports a 201 byte file as having 194 chars:
         File file = new File(plainFile);
         Scanner inputFile = new Scanner(file);
         numberOfChars = 0;
         String line;
         //count characters in file
         while (inputFile.hasNextLine())
              line = inputFile.nextLine();
              numberOfChars += line.length();
    I know there are other ways using BufferedReader, etc but I have to use Scanner class to do this.
    Thanks in advance!

    raichle wrote:
    Wow guys, thanks for the help! I've got a RTFMWell, what's wrong to have a look at the API docs for the Scanner class?
    and directions that go against the specs I said.Is that so strange to suggest a better option? What if I ask a carpenter "how do I build a table with a my stapler?". Should I give the man an attitude if he tells me I'd better use a saw and hammer?
    I'm also aware that it "eats" those chars and obviously looking for a way around that.
    I've looked through the java docs, but as I said, I'm new to this and they're difficult to understand. The class I am auditing req's that this be done using Scanner, but I don't see why you demand an explanation.
    Can anybody give me some constructive help?Get lost?

  • Help using scanner.class someone help me

    ive been working on some code and the thing is i am stuck on how do i count the number of intergers between 1 and 5. for example lets say i inputted using a scanner.class 1,2,2,3,3,3 i want my program to then say how many 2's I have entered and and how many 3's i have entered. So basically if using a scanner.class (keyboard class) in java instead of hardwiring the numbers into an array how do i count out the number of intergers and display them in my output

    hardwiring the numbers into an array how do i count
    out the number of intergers and display them in my
    outputTry this.
            Scanner sc = new Scanner(System.in);
            System.out.println("Enter numbers:");
            int i = 0;
            int count = 0;
            Map <Integer, Integer> intMap = new TreeMap <Integer, Integer>();
            while( true ) {
                i = sc.nextInt();
                if(i < 0 || i > 5) break;
                // Code to count the numbers entered.
                if(intMap.containsKey(new Integer(i))) {
                    count = intMap.get(new Integer(i)).intValue();
                    count++;
                } else {
                    count = 1;
                intMap.put(new Integer(i), new Integer(count));
            System.out.println(intMap);At forum users: Pardon me for all my variable names and poor coding style and lack of comments and...

  • Please help with writing a class

    i need help getting started with this assignment. i haven't done anything with writing classes, so i don't know where to start.
    i need to create a bank account class that will keep a name, balance, up to 50 deposits, and up to 50 withdrawls. i need to include 2 arrays for the deposits and withdrawls.
    Here's what i know:
    I need a constructor that takes zero arguments. This constructor would initialize the numeric value to zero.
    I need a 2nd constructor that takes one argument, a name as a String value. This constructor would initialize the numeric value to zero.
    I need a 3rd constructor that takes two arguments, a name as a String value and a starting "balance" as a double value

    Sorry, I was watching a movie with my wife ...imagine that. Study my examples here and try to understand what I have done. You will follow the same methodology for the rest of the program. Use main to test the methods in your program.
    public class mdlAccount {
      String name;
      double balance;
      int currentDeposit = 0;
      int currentWithdrawl = 0;
      double[] deposits = new double[50];
      double[] withdrawals = new double[50];
      public mdlAccount() {
        name = "";
        balance = 0.0;
      public mdlAccount(String name) {
        this.name = name;
        balance = 0.0;
      public mdlAccount(String name, double balance) {
        this.name = name;
        this.balance = balance;
      // When the instructor says: Have a method that does deposits...
      // You need to create a method, similar to the constructors,
      // but with a return value, even if it returns void (nothing).
      // Like this:
      public void deposit( double amount ) {
        // Do some error checking.
        if ( currentDeposit < 50 && amount > 0 ) { // > is a greater than sign
          // If all is ok, add to the balance...
          balance += amount;
          // and add the entry to the array of deposits
          deposits[currentDeposit] = amount;
          // Finally, add 1 to the currentDeposit variable.
          currentDeposit++;
      // We need the 'return the balance' method so we can see if
      // the program runs correctly. This time we return a double,
      // instead of void. (void means don't return anything at all).
      public double getBalance() {
        return balance;
    // Now you create the next method for withdrawals...
    //  if ( currentWithdrawl < 50 ) {
    //    deposits[currentWithdrawl] = amount;
    //    currentWithdrawl++;
      // You want a main method so this class can be executed.
      // You can remove it later if you want to use this class
      // from within another larger program.
      public static void main(String[] args) {
        mdlAccount acct = new mdlAccount( "GumB", 100.0 );
        System.out.println("Initial balance is " + acct.getBalance());
        acct.deposit( 50.0 );
        System.out.println("Current balance is " + acct.getBalance());

  • Help needed regarding Scanner class

    hello
    i'm really desperate for help, i'll mention that this is homework,but i need a small guidance.
    i need to code a calculator,we need to use the Scanner class to break the expression to tokens(we CANNOT use other classes).
    my main problem is about getting those tokens from the input string.
    i tried breaking a string to tokens for hours but just couldnt do it.
    a legal expression is something like:
    xyzavbx1111+log(abc11*(2+5))+sin(4.5)
    iilegal is : xx333aaaa111+2 or log()+2
    where the alphanumerics are variables(sequence of letters followed by numbers)
    i managed to get the tokens out of a string that looks like that:
    String expression = "ax11111+32/3+4*2^2"
    by doing:
    _token = new Scanner(expression);
    while(hasNext(_token)) getNextToken(_token,"\\d+(\\.\\d+)?|(\\+)|(\\-)|(\\*)|(\\/)|(\\^)|([a-zA-Z]+(\\d+));
    public static boolean hasNext(Scanner s) {
    return s.hasNext();
    public static String getNextToken(Scanner s,String str) {
    return s.findInLine(str);
    but i can't get the tokens when i have sin ,cos or log in the expression
    either it just ignores it or i'm looping infinitely.
    my question is how can i make the regular expression include the sin log and cos?
    I also know that when i'll use the "matches" method ,i'll be able to spot illegal arguments like 5//2+ because it doesnt match the pattern.
    so any help conecrning the regular expression would be great thanks alot.

    thx , but i already got it,after trying tons of combinations
    i'll post the format i used in case someone will find this thread in the future ,while looking for something similar
    the format is:
    "(\\s)|(log)|(sin)|(cos)|(\\d+(\\.\\d+)?)|(\\+)"+
    "|(\\-)|(\\*)|(\\/)|(\\^)|([a-zA-Z]+(\\d+))|(\\()|(\\))|(\\s)";
    which includes white spaces between arguments and operators

  • Help with designing basic class

    Ok, I'm trying to learn java by implementing a Recipe program that I will eventually put up on my web page. My thought was to create a base class called recipe that would essentially be a collection of strings and such. This would then be tied to a database with getFromDatabase() methods etc... However I'm I just want to clarify a few things and make sure I'm headed in the right direction.
    I figure I should create my class something like this:
    public class Recipe
      public String recipeName;
      // more strings like serves source, etc...
      public int rating; // 1-5
      // Ingredient list
      // Category list
      public String directions;
      public Recipe(String recipeName)
      this.recipeName = recipeName;
    }The above is pretty much what I think is right with what I have so far. For the ingredients, I created a special class called ingredient that looks like:
    public class Ingredient
      public String qty;
      public String amt;
      public String desc;
      public Ingredient(String quant, String ammount, String description)
        this.qty = quant;
        this.amt = ammount;
        this.desc = description;
      public Ingredient()
        this.qty = "";
        this.amt = "";
        this.desc = "";
      public String toString()
        String tempstring = new String(this.qty + " " + this.amt + " " + this.desc);
        return tempstring;
    }Then in my recipe class I have:
    public List ingredients = Collections.synchronizedList(new LinkedList());and then I have two overloaded addIngredient methods to add an Ingredient object to this list.
    So am I on the right track? Should I not even bother with a special class just for ingredients?
    Also while I have your attention, if I were to try and get a list of recipes in the database (ie, SELECT recipename FROM recipes;) where should I put this method? Thank you for any help.
    -Chris

    You only use get() and set() methods for data you need to change, I didn't think that I had to point that out.
    The guy is obviously a beginner, there is no need to saturate him with loads of information that isn't too important to him right now; however, it is good to get him used to the get and set methods for the variables that might need changing, and keeping (most of) the variables private (or protected as the case may be).
    Please tell me how setting variables to private does not contribute to information hiding? @_@
    Because, the last time I heard, private variables can't be accessed by other classes.
    Not only that, the get() and set() methods DO hide information, mainly the inner workings of the code. Consider:
    public class Foo {
      private int x;
      public int getX() {
        return x;
      public void setX(int anInt){
        x = anInt;
    public class Bar {
      private Foo mFoo = new Foo();
      public int process(){
        int intialValue = myFoo.getX();
        return initialValue * 4;
    }And say for whatever reason the way Foo handled the way x was stored had to change:
    public class Foo {
      public String x = "0"; // x no longer an int
      public int getX() {
        return Integer.parseInt(x); // convert when needed
      public void setX(int anInt){
        x = new Integer(anInt).toString(); // convert back
    public class Bar {
      private Foo mFoo = new Foo();
      public int process(){
        int intialValue = myFoo.getX(); // none the wiser
        return initialValue * 4;
    }Note, because of the get and set methods, we didn't have to change Bar. I'd say this was a kind of data hiding, no?
    I do know a bit about what I'm saying. I may not be an expert, but what I said was on the wholecorrect, especially considering the OP is a beginner. I never claimed what I told him was the WHOLE of tight encapsulation, but it is a part of it. He doesn't need to know more than what I told him ATM.

  • Help with using multiple hard drives

    Is there a way to install the OS on an "external" (expresscard SSD) drive, but have all of the library and data files on the primary hard disk? I LOVE the speed on my SSD, but it's a pain finding stuff now. Is this something a RAID configuration could help with?

    mwmmartin wrote:
    I have a 1 TB hard drive; but I have a 500GB and 250GB usb external hard drives.
    Wouldn't it be cool if I could make the two external hard drives a RAID drive and use Time Machine to use all the 750GB of external memory to do my backups???
    You can, but I would +*strongly recommend against+* it. See +Concatenated RAID+ in the Help for Disk Utility.
    There are several potential problems:
    Depending on how much data is on your 1 TB drive, 750 GB may not be enough to back it up. See #1 in Time Machine - Frequently Asked Questions (or use the link in *User Tips* at the top of this forum).
    To set up a +Concatenated RAID+ set, both drives will be erased.
    When (not if) either drive fails, you'll lose all the data on both.
    Both drives must be connected any time you do a backup or want to browse your backups.
    Especially with USB, if one drive wakes from sleep, or spins up, quickly enough, but the other one doesn't, the backup may fail and/or your backups may be corrupted.
    For now, it looks like my only solution is to go buy a bigger external hard drive and spend more money,,,
    That's your best solution +*by far.+* Anything else is taking a large risk with your backups.

  • Problems with the Scanner class and the decimal point

    I'm creating a GUI so to get the user input (double value) I use a jText field and the Scanner to read that value:
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
            String time = jTextTime.getText();
           double t = new Scanner(time).nextDouble();
            String cy = Double.toString(t);
            jTextCycles.setText(cy);
        }                                  The problem is that the decimal point it's a comma so if I write:
    1.2
    t = (Error InputMismatchException)
    1.236
    t = 1236.0
    1,2
    t = 1.2
    So I try using the parse method to get the double value:
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
            String time = jTextTime.getText();
           double t = Double.parseDouble(time);
            String cy = Double.toString(t);
            jTextCycles.setText(cy);
        }                            In this case the method parseDouble() takes the dot as the decimal point so if i write:
    1.2
    t = 1.2
    1.236
    t = 1.236
    1,2
    t = (Error InputMismatchException)
    � What can I do to Scanner class to accept the dot as the decimal point?
    I think that the problem is becouse in some countries (I'm from Colombia) the decimal point is a comma and in others is the dot.
    Thanks

    From the Javadocs for Scanner:
    Localized numbers
    An instance of this class is capable of scanning numbers in the standard formats as well as in the formats of the scanner's locale. A scanner's initial locale is the value returned by the Locale.getDefault() method; it may be changed via the useLocale(java.util.Locale) method.
    If you change your locale to one of those that does use a comma for a decimal point, it should work.

  • I need help with the https class please.

    Hello, i need add an authentication field in my GET request using HTTPS to authenticate users. I put the authentication field using the setRequestProperty method, but it doesn't appear when i print all properties using the getRequestProperties method. I wrote the following code:
    try{
    URL url = new URL ("https://my_url..");
    URLConnection conexion;
    conexion = url.openConnection();
    conexion.setRequestProperty("Authorization",my_urlEncoder_string);
    conexion.setRequestProperty("Host",my_loginServer);
    HttpsURLConnection httpsConexion = (HttpsURLConnection) conexion;
    httpsConexion.setRequestMethod("GET");
    System.out.println("All properties\r\n: " + httpsConexion.getRequestProperties());
    }catch ....
    when i run the program it show the following text:
    All properties: {Host=[my_loginServer]}
    Only the Host field is added to my HttpsURLConnection. The authentication field doesnt appear in standar output. How can i add to my HttpsURLConnection an Authentication field?
    thanks

    I have moved this to the main Dreamweaver forum, as the other forum is intended to deal with the Getting Started video tutorial.
    The best way to get help with layout problems is to upload the files to a website and post the URL in the forum. Someone can then look at the code, and identify the problem. Judging from your description, it sounds as though the Document window is narrow, which would result in the final menu tab dropping down to the next row. Try turning on Live view or previewing the page in a browser. Design view gives only an approximate idea of the final layout. Live view renders the page as it should look in a browser.

  • Help for using java class in forms 9i

    hi
    i have been trying to use java class in forms9i but unable to execute ,i have encountered exceptions,for which exception handlers have been declared like ora_java.java_error and exception_thrown but failed to handle run time errors , i have tried all ways from my side.
    my java class returns a simple string
    i need help on various work arounds
    thanks in advance
    yash

    sir
    i have written a simple java class which returns a string hello imported using a java importer in forms 9i
    and i call my class in when button press trigger
    i have also imported java.lang.Exception for my exception handlers,i have no compile errors,but when i run my forms i get run time error and my exception handlers fail to trap it . ihave no idea how to proceed .
    should i use bean area in form and call the class using fbean from custom item rigger if so please explain
    can i get sample code example for calling a java class methods from forms.
    thanks
    yash

  • Need help with using Solaris FLAR across disparate platforms

    All,
    I need help with what needs to be done to use solaris Flash for disaster recovery between the disparate Server platforms listed below.
    I am concerned about the platform specific files that would be missing?
    Note: All our servers are installed with the SUNWCprog cluster through Custom jumpstart and We use disksuite for mirroring the operating system drives.
    Primary Server     Recovery Server
    Sun Fire 6800     Sun Fire E2900
    Sun Fire E2900     Sun Fire 6800
    Sun Fire-880     Sun Fire-V440
    Sun Fire-V440     Sun Fire-880
    Sun Fire 4800     Sun Fire-880
    Sun Fire-V890     Sun Fire 4800          
    Me

    jds2n,
    Is it possible to get around installing the Entire Distribution + OEM and include only the platform specific files?
    Just a thought
    Example:
    I would like to create a Flash Archive of a E2900 server which i plan to use to recover a 6900.
    The 2900 was installed with a developer cluster.
    When creating the Flash archive of the 2900 is it possible to add the 6900 platform specific files and drivers
    from the Solaris CD?
    Thanks

  • Need help with using Email Activation Agent

    Hi,
    please, help me with using E-mail Activation Agent.
    I used email activation agent to start business processes by email, but after that letter disappear from email-server.
    Where letter was located?
    Can I get and read letter for processing?

    Mail/Preferences/General - do you have Unibox set as your default e-mail application?

  • Please help with the URL class

    Hello,
    I am trying to write a Java app that will take a url and download it.
    I believe you can do this with the URL class but I don't understand how to. For example, if the http url location points to a picture file, how would I code the app to retrieve this picture and save it to a specified directory?
    Also, is there a way that my java app could open another program, let's say Microsoft Internet Explorer?
    Please be as specific as possible, thanks!

    You'll see below an example to download a file
    private static String copyFile (String url, String nomFichier){
         // construction du fichier de sortie
         File outputFile = new File(repertoire + "\\fichiers\\" + nomFichier);
         // si le fichier existe d�j�, il ne sert � rien de le t�l�charger !
    if (outputFile.exists())
         return "fichiers/" + nomFichier;
              try {     
         HttpURLConnection connect = (HttpURLConnection)new URL(url).openConnection();
    boolean connected = false;
    while (!connected){
    try {
    connect.connect();
    connected = true;
         catch (java.io.IOException e1) { System.out.print("...Tentative de connection"); }     
    DataInputStream reader = new DataInputStream(
    connect.getInputStream());
         FileOutputStream out = new FileOutputStream(outputFile);
         int length = 1024;
         byte[] buf = new byte[length];
         int offset = 0;
         long offsetCourant = 0;
         int nb=0;
         while ((nb=reader.read(buf,offset,length))!= -1) {
              out.write(buf,0,nb);
         out.close();
         catch (java.net.MalformedURLException e) { System.out.println("pb d'url"); }
         catch (java.io.IOException e1) { System.out.println(e1.getMessage()); }
         return "fichiers/" + nomFichier;
    }

  • Help with using a web page from disk after saved from web

    Hi, I almost forgot the little I learned about web page development, so, I'm a total noob when it comes to this and I need your help.
    I saved as a complete web page on my hard disk this web page but when I open it in Firefox or IE, it doesn't display as much as I need it. I'm mostly interested  in displaying the logo images as they appear on the original web page. The browsers just show them briefly when refreshing but hide them right away. I can see the image files downloaded to my hard drive and if I open the page in Dreamweaver it displays these images  in the preview pane but I can't make them show in the browsers. From Dreamweaver I saved the page as in the folder where the images are and this also updated the code with the relative image links but the browsers still don't show them.
    I will greatly appreciate your help with this.

    I'm sorry, but your post is very confusing
    I saved as a complete web page on my hard disk this web page
    Does this include site definitions?
    when I open it in Firefox or IE, it doesn't display as much as I need it.
    I dont know what this means...are there images that are not being displayed?  Is there styling that is not being rendered?
    . I'm mostly interested  in displaying the logo images as they appear on the original web page. The browsers just show them briefly when refreshing but hide them right away.
    Again, I dont know what this means?
    I can see the image files downloaded to my hard drive and if I open the page in Dreamweaver it displays these images  in the preview pane but I can't make them show in the browsers. From Dreamweaver I saved the page as in the folder where the images are and this also updated the code with the relative image links but the browsers still don't show them.I will greatly appreciate your help with this.
    Do you have a link to the page, and perhaps some explanation that is more clear as to what your issue is.
    Gary

Maybe you are looking for