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...

Similar Messages

  • 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 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

  • Need help using my class

    I recently made a class called time that let me store times and return their values. I needed to do this for another class called flight, which uses the class time to store times. My question is, how would i use my time class in the flight class. Whenever i try to make a new time.
    //i.e.
    Time x = new Time(0,0,0);It says that the class Flight cannot find the Time class within it. Does anyone know how i can use my time class inside of my Flight class without making Flight an extension of Time, if it is even possible. My Time code is posted below.
    public class Time{
        private int Hours;
        private int Minutes;
        private int Seconds;
       public Time(int newHours, int newMinutes, int newSeconds){
            setTime(newHours, newMinutes, newSeconds);
       public int getHours(){
            return Hours;
       public int getMinutes(){
           return Minutes;
       public int getSeconds(){
           return Seconds;
    public int setHours(int newHour){
        Hours = newHour;
        return Hours;
    public int setMinutes(int newMinute){
        Minutes = newMinute;
        return Minutes;
    public int setSeconds(int newSecond){
        Seconds = newSecond;
        return Seconds;
    public String toString(){
        int newHours = Hours;
        String type = "";
        String minuteZero = "";
        String secondZero = "";
        if(Hours>=0 && Hours<=11){
            type = " AM";
            if(Hours==0){
                newHours +=12;  
        if(Hours>=12 && Hours<=23){
            type = " PM";
            if(Hours>=13 && Hours<=23){
                newHours = newHours - 12;
        if(Minutes>=0 && Minutes<=9){
            minuteZero = "0";
        if(Seconds>=0 && Seconds<=9){
            secondZero = "0";
        return newHours + ":" + minuteZero + Minutes + ":" + secondZero + Seconds + type;
    public void setTime(int setHours, int setMinutes, int setSeconds){
        if(setHours>=0 && setHours<=23 && setMinutes>=0 && setMinutes<=59 && setSeconds>=0 && setSeconds<=59){
        setHours(setHours);
        setMinutes(setMinutes);
        setSeconds(setSeconds);
    public int secondsUntil(Time newTime){
        int totalSeconds;
        totalSeconds = ((this.Hours*3600)+(this.Minutes*60)+(this.Seconds))-((newTime.Hours*3600)+(newTime.Minutes*60)+(newTime.Seconds));
        return totalSeconds;
    }

    My Time class is in a folder called Time on my flash drive, and my Flight class is in a folder called Flight on my flash drive. And what do you mean how am i compiling them?

  • Error in creating a process using runtime class - please help

    Hi,
    I am experimenting with the following piece of code. I tried to run it in one windows machine and it works fine. But i tried to run it in a different windows machine i get error in creating a process. The error is attached below the code. I don't understand why i couldn't create a process with the 'exec' command in the second machine. Can anyone please help?
    CODE:
    import java.io.*;
    class test{
    public static void main(String[] args){
    try{
    Runtime r = Runtime.getRuntime();
         Process p = null;
         p= r.exec("dir");
         BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
         System.out.println(br.readLine());
    catch(Exception e){e.printStackTrace();}
    ERROR (when run in the dos prompt):
    java.io.IOException: CreateProcess: dir error=2
    at java.lang.Win32Process.create(Native Method)
    at java.lang.Win32Process.<init>(Win32Process.java:63)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Runtime.java:550)
    at java.lang.Runtime.exec(Runtime.java:416)
    at java.lang.Runtime.exec(Runtime.java:358)
    at java.lang.Runtime.exec(Runtime.java:322)
    at test.main(test.java:16)
    thanks,
    Divya

    As much as I understand from the readings in the forums, Runtime.exec can only run commands that are in files, not native commands.
    Hmm how do I explain that again?
    Here:
    Assuming a command is an executable program
    Under the Windows operating system, many new programmers stumble upon Runtime.exec() when trying to use it for nonexecutable commands like dir and copy. Subsequently, they run into Runtime.exec()'s third pitfall. Listing 4.4 demonstrates exactly that:
    Listing 4.4 BadExecWinDir.java
    import java.util.*;
    import java.io.*;
    public class BadExecWinDir
    public static void main(String args[])
    try
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec("dir");
    InputStream stdin = proc.getInputStream();
    InputStreamReader isr = new InputStreamReader(stdin);
    BufferedReader br = new BufferedReader(isr);
    String line = null;
    System.out.println("<OUTPUT>");
    while ( (line = br.readLine()) != null)
    System.out.println(line);
    System.out.println("</OUTPUT>");
    int exitVal = proc.waitFor();
    System.out.println("Process exitValue: " + exitVal);
    } catch (Throwable t)
    t.printStackTrace();
    A run of BadExecWinDir produces:
    E:\classes\com\javaworld\jpitfalls\article2>java BadExecWinDir
    java.io.IOException: CreateProcess: dir error=2
    at java.lang.Win32Process.create(Native Method)
    at java.lang.Win32Process.<init>(Unknown Source)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at BadExecWinDir.main(BadExecWinDir.java:12)
    As stated earlier, the error value of 2 means "file not found," which, in this case, means that the executable named dir.exe could not be found. That's because the directory command is part of the Windows command interpreter and not a separate executable. To run the Windows command interpreter, execute either command.com or cmd.exe, depending on the Windows operating system you use. Listing 4.5 runs a copy of the Windows command interpreter and then executes the user-supplied command (e.g., dir).
    Taken from:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • [Help] Using a class at the other class

    hi guys, i'm still new to java. So that i tried to learn by myself.
    i got 2 class: 'Person.java' and 'Ex1.java'
    basically, Person just a class for making an object of Person. and the main function is made at Ex1.java.
    my problem is: i made 2 Person objects (p1 and p2). then i tried to initialise them in 2 ways (using default constructor and user-defined constructor). Why when i print 'em (p1.print() and p2.print()), it printed p1 attributes only. I tried many ways to do this, but can't find the way out. pls help me...
    * Person.java *
    public class Person {
         // attributes
         private static String name;
         private static int age;
         // constructor
         public Person() {
              name = "";
              age = -1;
         public Person(String n, int a) {
              name = n;
              age = a;
         // mutator
         public static void setName( String n ) { name = n; }
         public static void setAge( int a) { age = a; }
         // other methods
         public static void print() {
              System.out.println( name + " (" + age + " years old)" );
    * Ex1.java *
    public class Ex1{
         private static Person p1;
         private static Person p2;
         public static void main(String args[]) {
              p1 = new Person();
              p2 = new Person("Jessica", 25);
              p1.setName("Antonio");
              p1.setAge(20);
              p1.print();
              p2.print();
    }

    Change
    public class Person {
         // attributes
         private static String name;
         private static int age;
    to
    public class Person {
         // attributes
         private String name;
         private int age;
    You're using incorrectly static for object attributes:)

  • Need help using 'visited' class with Colorbox

    Hi guys,
    I'm creating a site for a client that uses the Colorbox script for the store. When you click on a thumbnail of a product in the store, the browser uses Colorbox to display the external PHP page with the product information.
    This all works fine but what I would like to do is...
    When you click on a product thumbnail and it brings up the page (using Colorbox), when you close the Colorbox window and return to the thumbnails, I would like the padded background of the image to be a different color and not grey like the rest of them - so you can see which products you have looked at and which products you haven't.
    I've tried using...
    #productContainer img:visited {background-color:#0973ba;}
    ...but it didn't work.
    Click here for the link to the test site if that helps.
    Does anyone have any suggestions as to how I can achieve what I need to do?
    Thank you very much and I look forward to hearing from you.
    SM

    Did you try adding the pseudoclasses here?
    #content a {
        color: #0973BA; 
        text-decoration: none;

  • Keynote sharing with more than one person using iworks can someone help

    Hi I hope someone can help.
    I am trying to share a keynote presentation which I have already shared with a second person.
    Every time I try I get the pop up asking me if I want to replace existing presentation, which I don't.
    Can I share again? If so how, as I feel really dumb ant the moment!!!!

    Here is how I initiate a text chat.
    (0) Click on one of my buddy names in my Buddy List to highlight it.
    (1) ⌘ click on the next buddy I want to add to highlight him, too.
    (2) Repeat the ⌘ clicks for all the other buddies I want in the chat.
    (3) Click the "A" at the bottom of my buddy list to initiate the multiple-party chat.
    Try that, and see if it works for you. If you can make it work for two, it should work for more.

  • Need help using multiple classes in different folders.

    Hey everyone.
    Im trying to make a trading card game, in Java. Each card is going to be a class derived from a main card class (called card). The problem is that each card is going to be in a different folder based on the set and card number. (ex. card 001 from set 02 would be in "game/02/001/")
    I found this is a real good way to organize the game since there will be new cards all the time and players wont have all of them. Is it posible to call classes from different folders, and if it is how do I do it?
    -Thanks to anyone who answers

    The problem is that each card is going to be in a different folder based on the set and card number.Why don't you simply add two attributes to your Card class:
    cardNumber
    setNumber
    Or better, have a Set class with attribute:
    number
    and a Card class with two attributes:
    number
    set

  • Does anyone have an issue with earbuds connection with iphone 4s. sounds like speaker is on when using them. can someone help me?

    everytime i connect the earbuds to talk on phone it sounds like a loud speaker  on earbuds. it has a lot of echo. does anyone know how to fix this?

    Is yours 4s? Have you recently updated to 6.1 or 6.1.2?
    Looks like apple is kiding with us. Ive had this problem since Ios 6.1 and now after 3 days I ulgraded to 6.1.2 this ****** issue has returned. Again the other part will listen me if I scream HELLOOo in the first second and then everything works fine or if I wait 1 minute but none can wait that.
    Im really angry with this company always they mess up after each update

  • Help!! Can someone help me with this message I keep getting before startup, please ?? Here it is: "/Library/Startupitems/Intego Backup Manager Pro" has not been started because it does not  have the proper security settings. Help!?!?

    Hello:
    I keep getting this message upon startup. Can't figure out how to address it. Here it is.
    "/Library/Startupitems/Intego Backup Manager Pro" has not been started because it does not have the proper security settings.
    Any suggestions?

    There's an invisible one name "Icon" according to the error message.
    Enable Finder to Show Invisible Files and Folders
    Open the Terminal application in your Utilities folder.  At the prompt enter or paste the following command line then press RETURN.
    defaults write com.apple.finder AppleShowAllFiles TRUE
    killall Finder
    To turn off the display of invisible files and folders enter or paste the following command line and press RETURN.
    defaults write com.apple.finder AppleShowAllFiles FALSE
    killall Finder
    Alternatively you can use one of the numerous third-party utilities such as TinkerTool or ShowHideInvisibleFiles - VersionTracker or MacUpdate.
    First, make invisible files visible. Find the invisible file in that folder and remove it. Please be sure you are looking in the /Library/StartupItems/ folder. There is another one in the /Home/Library/ folder. Be sure you look in the right one.

  • Re: Skype calls can someone help me

    Hi 
    i have just brought a skype number and i want people to call the number and for me to answer it on skype
    when i ring the number nothing happens
    i dont know how to use it can someone help??
    Thanks

    Hi, Angelafran, and welcome to the Community,
    Please check this FAQ article first, so we can rule out problems with some of these items listed:  https://support.skype.com/en/faq/FA10615/why-am-i-not-receiving-calls-to-my-skype-number
    Here is a link to the rest of the library of articles related to Skype Numbers:
    https://support.skype.com/en/category/ONLINE_NUMBER_SKYPEIN/
    If you try to call your Skype Number from Skype, the number would ring as busy as you are actually calling yourself.  After checking that your software preference settings are correct, you can also contact Skype Customer Service to have the number checked.
    Regards,
    Elaine
    Was your question answered? Please click on the Accept as a Solution link so everyone can quickly find what works! Like a post or want to say, "Thank You" - ?? Click on the Kudos button!
    Trustworthy information: Brian Krebs: 3 Basic Rules for Online Safety and Consumer Reports: Guide to Internet Security Online Safety Tip: Change your passwords often!

  • Scanner class

    i m very new to Java..i have Netbeans 5 to compile and run my Java programs.....when i try to run the following program
    import java.util.Scanner;
    class EchoLine {
    public static void main(String args[]) {
    Scanner myScanner = new Scanner(System.in);
    System.out.println(myScanner.nextLine());
    i get some errors saying...
    D:\Java\Projects\JavaApplication12\src\javaapplication12\Main.java:11: cannot resolve symbol
    symbol : class Scanner
    location: package util
    import java.util.Scanner;
    D:\Java\Projects\JavaApplication12\src\javaapplication12\Main.java:19: cannot resolve symbol
    symbol : class Scanner
    location: class javaapplication12.EchoLine
    Scanner myScanner = new Scanner(System.in);
    D:\Java\Projects\JavaApplication12\src\javaapplication12\Main.java:19: cannot resolve symbol
    symbol : class Scanner
    location: class javaapplication12.EchoLine
    Scanner myScanner = new Scanner(System.in);
    3 errors
    BUILD FAILED (total time: 0 seconds)
    i also get same kind of error while compiling it in JCreator.
    Can anybody help me in this matter to expalin this knid of behavoiur??
    Thanking in advance!!

    after downloading JDK 5 update 7 from
    http://java.sun.com/j2se/1.5.0/download.jsp
    i still cannot use Scanner class.....
    Java doesn't like you sorry. It's hopeless. We try and talk to Java and make her understand that she shouldn't be so flighty but you know... it just isn't going to work out. She hopes you can remain friends but she's just not interested in a more intimate relationship at this time.

  • IN MATERIAL MASTER RECORD WHAT IS THE USE OF CLASS TYPE(CLASSIFICATION VIEW

    Hi Guys,
    Can you please explain what are the different critiria to use different class type and what exactly meaning of the each class type with respect to Material classification.
    Any material available on this to study. Please give link.
    Thanks,
    Dhanu

    Hi,
    Purpose
    The classification system allows you to use characteristics to describe all types of objects, and to group similar objects in classes u2013 to classify objects, in other words, so that you can find them more easily later.
    You then use the classes to help you to find objects more easily, using the characteristics defined in them as search criteria. This ensures that you can find objects with similar or identical characteristics as quickly as possible.
    Integration
    The classification system allows you to classify all types of object. First, you must define certain settings in Customizing for the classification system. For more information, see Customizing for the Classification System.
    SAP has predefined a number of object types (for example, materials, and equipment). The settings for these object types have already been defined in Customizing, so you can start to set up your classification system for these object types without defining further settings.
    Features
    Before you can use classification functions, you need to set up your classification system.
    The there are three steps to setting up a classification system:
    Defining the Properties of Objects
    You use characteristics to describe the properties of objects. You create characteristics centrally in the SAP R/3 System.
    See the SAP Library, Characteristics (CA-CL-CHR).
    Creating Classes
    You need classes to classify objects. These classes must be set up. During set up you must assign characteristics to the classes.
    Assigning Objects
    Once you have created the classes you require for classification, you can assign objects to these classes. You use the characteristics of the class to describe the objects you classify.
    This completes the data you require to use your classification system. You can then use your classification system to find objects that match the criteria you require.
    Once you have set up the classification system you can use it to find certain objects. To do this:
    Find a class in which objects are classified
    Find the object(s) you require in the class
    When you use classification to find objects, you use the characteristics as search criteria, and the system compares the values you enter with the values of the classified objects.
    Uts
    Award if helpfull

  • Scanner class refuses to work

    Hi, I am having a really big pain in the butt issue with java, (ive tried using eclipse, jgrasp and bluej, all giving me same error)
    I am trying to read from a .dat file (which can easily be opened with wordpad or notepad to reveal contents)
    I am using scanner class
    Scanner key = new Scanner (new File ("file.dat"));
    no matter what i do, i keep getting the same error message FileNotFound Exception, i have gotten java to print out the directory it is searching for, i have put the file into that directory and i am still getting nothing....ive have been at this for two days now, and it is driving me nuts, nothing is making sense and i have asked everyone i know, they say that is the code you need to use to get it to read.
    P.S i have also tried
    File abc = new File ("file.dat");
    Scanner key = new Scanner (abc); same result
    I even got a little hopeful and tried just plain old
    Scanner key = new Scanner ("file.dat); and i get nada, same error, im wondering if anyone has seen this before.

    public static void populate(){
    Scanner keyb= new Scanner(new File("city.dat"));
    for(int j=0;j<=18;j++){
         int x = keyb.nextInt();
         String abr=keyb.next();
         int h = convert(abr);
         String name=keyb.next();
         int pop=keyb.nextInt();
         int alt = keyb.nextInt();
         city[x]=new cities(name,pop,alt);
         }Error Message: Exception in thread "main" java.lang.Error: Unresolved compilation problems:
         Unhandled exception type FileNotFoundException
         Unhandled exception type FileNotFoundException
         at Main.populate(Main.java:45) Line 45 is Scanner keyb= new Scanner(new File("city.dat"));
         at Main.main(Main.java:34) Line 34 is a call to the populate method.

Maybe you are looking for