Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 10 of 10

Thread: Experiencing problems w/ Scanner & main, open to any assistance!

  1. #1
    Junior Member BlackStones's Avatar
    Join Date
    Feb 2014
    Posts
    15
    My Mood
    Fine
    Thanks
    1
    Thanked 1 Time in 1 Post

    Default Experiencing problems w/ Scanner & main, open to any assistance!

    At the moment, I am creating this program to ask the user for input. The user will give a number (to be added to sum and then divided by n to find the mean) or the letter "e" (to terminate the program). The program should take multiple numbers until an "e" is given.

    This is the underlying concept but I'm not really there yet. I'm having some trouble getting my main and Scanner to cooperate so any help would be appreciated, thank you.

    //package homework1;
     
    import java.util.Scanner;
     
    public class hmwk1 
    {
        public static void main(String[] args) 
    	{
    		partA();
    	}
     
    	public static void partA()
        {  
            int n = 0;
            double mean = 0;
            double sum = 0;
            String input;
     
     
            System.out.println("Enter a number or enter 'e' to quit:");
            Scanner kb = new Scanner(System.in);
            input = kb.next();
     
            while(!(input.equals("e")))
            {
            	if(!(input.equals("e")))
            	{
                    double d = Double.parseDouble(input);
     
                    if(d >= 10 && d <= 100)
                    {
                        sum += d;
                        n++;  
                    }
                    else
                    {
                        System.out.println("Not in range");
                    }  
            	}
     
                /*System.out.println("Enter a number or enter 'e' to quit:");
                String input2 = kb.next();
                if(!input2.equals("e"))
                {
                    double d = Double.parseDouble(input);
                }*/
            }
                mean = sum / n;
                System.out.println(mean);
     
                System.exit(0);
        }
     
    }


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    4,356
    My Mood
    Mellow
    Thanks
    143
    Thanked 598 Times in 585 Posts

    Default Re: Experiencing problems w/ Scanner & main, open to any assistance!

    Are you getting errors? Please post those. Also, not sure what you mean about cooperation of main and Scanner. The main() calls a method and steps aside. (Give your methods better names that describe what they do, usually verbs.)

  3. #3
    Member Ganeprog's Avatar
    Join Date
    Jan 2014
    Location
    Chennai,India
    Posts
    80
    My Mood
    Love
    Thanks
    3
    Thanked 6 Times in 6 Posts

    Default Re: Experiencing problems w/ Scanner & main, open to any assistance!

    Hi,

    As per your program, Your problem is

    If i entered "e" means you are trying to parse into double that time you are getting NaN.
    if i entered number means program hanged in infinite loop.

    So you can do one thing,

    1)Put the while as a continuous running.
    2)get the input inside the while loop.
    3)If press "e" means but break and come out of while loop then perform your calculation.

    while(true)
    {
    input = kb.next();
          if(**your codition**)
         {
     
          }
          else
               break;
    }

    Still you facing difficulties, post here

    Thanks,

  4. #4
    Junior Member BlackStones's Avatar
    Join Date
    Feb 2014
    Posts
    15
    My Mood
    Fine
    Thanks
    1
    Thanked 1 Time in 1 Post

    Default Re: Experiencing problems w/ Scanner & main, open to any assistance!

    Hello all,

    After making modifications suggested by Ganeprog, I am still struggling to compile the program. In essence, the program does generate the output question but when a user inputs a number my program blows up. Here is my error message, I'm using CompileOnline at the moment because I am away from my PC.

    Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:907)
    at java.util.Scanner.next(Scanner.java:1416)
    at hmwk1.partA(hmwk1.java:25)
    at hmwk1.main(hmwk1.java:9)



    And here is my updated Java code;

    //package homework1;
     
    import java.util.Scanner;
     
    public class hmwk1 
    {
        public static void main(String[] args) 
        {
    		partA();
    	}
     
    	public static void partA()
        {  
            int n = 0;
            double mean = 0;
            double sum = 0;
            String input;
     
     
            System.out.println("Enter a number or enter 'e' to quit:");
            Scanner kb = new Scanner(System.in);
     
            while(true)
            {
                input = kb.next();
     
            	if(!(input.equals("e")))
            	{
                    double d = Double.parseDouble(input);
     
                    if(d >= 10 && d <= 100)
                    {
                        sum += d;
                        n++;  
                    }
                    else
                    {
                        System.out.println("Not in range");
                        break;    
                    }
            	}
     
     
            }
                mean = sum / n;
                System.out.println(mean);
     
                System.exit(0);
        }
     
    }

    The objective of this program is to
    • ask the user for a number or an 'e' to exit. Each time the user enters a number and presses "return", the program will prompt the user to enter another number or press 'e'.
    • When user presses 'e' and and hits return, the program will calculate the mean (m) of the numbers entered
    • Range [10,100]
    • If a number is entered that is not in that range, print an error message and then continue on with the program until they enter "e"


    @ GregBrannon I do not have the option to name the methods.

    Thanks for ANY assistance, really.

  5. #5
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    4,356
    My Mood
    Mellow
    Thanks
    143
    Thanked 598 Times in 585 Posts

    Default Re: Experiencing problems w/ Scanner & main, open to any assistance!

    Perhaps your code formatting is confusing you, but what you describe and what your code says don't match.

    This is what your code says:

    get input
    for other than "e"
    turn input into double value
    and if double value is between 10 and 100, inclusive,
    add value to sum and increment count
    otherwise print error message and exit input loop

    There's no code that exits on an "e" input. In fact, an "e" input is just ignored.

  6. #6
    Member
    Join Date
    Apr 2012
    Posts
    161
    Thanks
    0
    Thanked 27 Times in 27 Posts

    Default Re: Experiencing problems w/ Scanner & main, open to any assistance!

    I would suggest using nextLine() as it will clear the buffer. A lot of problems arise when using next() and then not clearing the buffer afterwards.

  7. #7
    Member Ganeprog's Avatar
    Join Date
    Jan 2014
    Location
    Chennai,India
    Posts
    80
    My Mood
    Love
    Thanks
    3
    Thanked 6 Times in 6 Posts

    Default Re: Experiencing problems w/ Scanner & main, open to any assistance!

    Hi BlackStones,

    You put the break statement wrongly. Please put the break statement outer if condition not inside if. For your reference see the below code
      while(true)
            {
            	input = kb.next();
            	if(!(input.equals("e")))
            	{
     
                    double d = Double.parseDouble(input);
     
                    if(d >= 10 && d <= 100)
                    {
                        sum += d;
                        n++;  
                    }
                    else
                    {
                        System.out.println("Not in range");
                    }  
            	}
            	else
            		break;
     
            }
     
                if(n>0){                         //If n and sum both zero means you wil get NaN so i put this condition.
                mean = sum / n;
                System.out.println(mean);
                }

    here No need to use System.exit(0)

    Try this and post here what happened.
    Thanks,
    Last edited by Ganeprog; February 8th, 2014 at 12:34 AM. Reason: code altered

  8. #8
    Junior Member BlackStones's Avatar
    Join Date
    Feb 2014
    Posts
    15
    My Mood
    Fine
    Thanks
    1
    Thanked 1 Time in 1 Post

    Default Re: Experiencing problems w/ Scanner & main, open to any assistance!

    Thanks for all of your feedback thus far. I am now coding the final section of the program and my objective is to create the last method "partD" to print the following output to a file named "report.txt";

    Number of Entries: 5
    Numbers entered: 1,2,3,5,6
    Mean: 3.4
    Maximum Number Found: 6
    Minimum Number Found: 1

    I was thinking I should add a double array to input the values after I parsed them. Then I would be able to use a function to determine the minimum and maximum values.

    The PartD method is the only relevant method to my question. It is the last method in the program. I am seeking logical guidance, I'm unfamiliar with the approach I should take to gather the input and print it and also analyzing it for high and low value.

    Here is my code;

    package homework1;
     
    import java.io.FileNotFoundException;
    import java.io.PrintWriter;
    import java.io.Writer;
    import java.util.Scanner;
     
    public class hmwk1 
    {
        private static Scanner kb;
    	private static Scanner kb2;
    	private static Scanner kb3;
     
    	private static PrintWriter outputStream;
     
    	public static void main(String[] args) 
        {
    		partD();
    	}
     
    	public static void partA()
        {  
            int n = 0;
            double mean = 0;
            double sum = 0;
            String input;
     
     
            System.out.println("Enter a number or enter 'e' to quit:");
            kb = new Scanner(System.in);
     
     
            while(! (input = kb.next()).equalsIgnoreCase("e") )
            {
     
                    double d = Double.parseDouble(input);
     
                    if(d >= 10 && d <= 100)
                    {
                        sum += d;
                        n++;  
                    }
                    else
                    {
                        System.out.println("Not in range");
                        break;
                    }  
            }
     
     
                mean = sum / n;
                System.out.println(mean);
     
                System.exit(0);
        }
     
    	public static void partB()
        {  
            int n = 0;
            double mean = 0;
            double sum = 0;
            String input;
     
            String fileName = "out5555.txt";
            try {
    			outputStream = new PrintWriter(fileName);
     
    		} catch (FileNotFoundException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
     
            System.out.println("Enter a number or enter 'e' to quit:");
     
            kb2 = new Scanner(System.in);
     
            while(! (input = kb2.next()).equalsIgnoreCase("e") )
            {
            		outputStream.println(input);
     
                    double d = Double.parseDouble(input);
     
     
                    if(d >= 10 && d <= 100)
                    {
                        sum += d;
                        n++;  
                    }
                    else
                    {
                        System.out.println("Not in range");
                        break;
                    }  
            }
     
                mean = sum / n;
                System.out.println(mean);
     
                outputStream.close();
                System.exit(0);
        }
     
    	public static void partC()
        {  
            int n = 0;
            double mean = 0;
            double sum = 0;
            String input;
     
            String fileName = "out1212.txt";
            try {
    			outputStream = new PrintWriter(fileName);
     
    		} catch (FileNotFoundException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
     
            System.out.println("Enter a number or enter 'e' to quit:");
     
            kb3 = new Scanner(System.in);
     
            outputStream.println("Numbers entered:");
     
            while(! (input = kb3.next()).equalsIgnoreCase("e") )
            {
            		outputStream.println(input);
     
                    double d = Double.parseDouble(input);
     
                    if(d >= 10 && d <= 100)
                    {
                        sum += d;
                        n++;  
                    }
                    else
                    {
                        System.out.println("Not in range");
                        break;
                    }  
            }
     
     
     
     
                mean = sum / n;
                System.out.println(mean);
     
                outputStream.println("Average:" + mean);
                outputStream.close();
     
                System.exit(0);
        }
    	public static void partD()
        {  
            int n = 0;
            double mean = 0;
            double sum = 0;
            String input;
     
            String fileName = "report.txt";
            try {
    			outputStream = new PrintWriter(fileName);
     
    		} catch (FileNotFoundException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
     
            System.out.println("Enter a number or enter 'e' to quit:");
     
            kb3 = new Scanner(System.in);
     
            outputStream.print("Numbers entered: ");
     
            while(! (input = kb3.next()).equalsIgnoreCase("e") )
            {
            		outputStream.print(input + ", ");
     
                    double d = Double.parseDouble(input);
     
                    if(d >= 10 && d <= 100)
                    {
                        sum += d;
                        n++;  
                    }
                    else
                    {
                        System.out.println("Not in range");
                        break;
                    }  
            }
     
     
     
     
                mean = sum / n;
                System.out.println(mean);
                outputStream.println("  Number of Entries:" + n);
                outputStream.println("Mean:" + mean);
                outputStream.println("Maximum Number Found:");
                outputStream.println("Minimum Number Found:");
     
                outputStream.close();
     
                System.exit(0);
        }
     
     
    }

  9. #9
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    4,356
    My Mood
    Mellow
    Thanks
    143
    Thanked 598 Times in 585 Posts

    Default Re: Experiencing problems w/ Scanner & main, open to any assistance!

    Why does this line appear in the program multiple times?:

    System.out.println("Enter a number or enter 'e' to quit:");

    I see it's partly because you've set up the program to do each part separately (odd), but anytime you're coding the same thing over and over again, you should think "Method!" Programmers like to think they are efficient, but they're basically lazy, and writing the same code over and over again is offensive. Also, multiple Scanner objects are unnecessary. One for the whole program should do. Focusing on each part separately could have been done in a way that the common methods were written once and shared among the parts.

    As for your PartD, what you showed requires storing all values entered by the user into a collection of some kind. Since the program doesn't know how many values the user will enter, an ArrayList is more appropriate than a simple Array. Do you know/can you use an ArrayList? If not, then a sufficiently large Array will be required and the user input will have to be limited in size to the size of the Array. After storing the numbers entered, PartD is simple math and logic.

  10. The Following User Says Thank You to GregBrannon For This Useful Post:

    BlackStones (February 9th, 2014)

  11. #10
    Junior Member BlackStones's Avatar
    Join Date
    Feb 2014
    Posts
    15
    My Mood
    Fine
    Thanks
    1
    Thanked 1 Time in 1 Post

    Default Re: Experiencing problems w/ Scanner & main, open to any assistance!

    @GregBrannon

    "Programmers like to think they are efficient, but they're basically lazy, and writing the same code over and over again is offensive."

    Lol.

    Also, multiple Scanner objects are unnecessary (one for entire program) - I resolved this problem, thanks for clarifying.

    Focusing on each part separately could have been done in a way that the common methods were written once and shared among the parts. - I'm not experienced enough yet, I think this program was created to be an introductory exercise.

    But in conclusion,
    I ended up using an ArrayList and I found a very helpful video on Youtube. My problem is resolved, thanks to all who contributed.

Similar Threads

  1. how to open one Jframe from main method call
    By ankushpruthi in forum What's Wrong With My Code?
    Replies: 12
    Last Post: October 1st, 2013, 05:23 PM