9 Replies - 7636 Views - Last Post: 12 September 2012 - 08:22 PM Rate Topic: -----

#1 jmProg  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 33
  • Joined: 04-July 12

How to limit user input

Posted 11 September 2012 - 06:34 AM

Hello. I have a problem with my program. Almost everything is OK with what was required to us, my only problem is how to prompt user that he exceeds from entering an input value that is required.

Example: When the user inputs 3, then in the next line, he must input only 3 numbers, too. If he exceeds or lacks, a message must prompt him.

here's my code:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class example {
    public static void main(String[] args) throws FileNotFoundException {
        File textFile = new File("newfile.txt");
        try (Scanner scanner = new Scanner(textFile)) {
           
            while (scanner.hasNext()) {
                int firstNumber = scanner.nextInt();
                int array[] = new int[firstNumber];
                
                    int compute = 1;

                    for (int i = 0; i < array.length; i++) {
                        array[i] = scanner.nextInt();
           
                        if (array[i] > 0) {
                            compute *= array[i];
                        } 
                    } System.out.println("The maximum product is " + compute + "."); 
                }      
           } 
      } 
}



BTW, i'm using netbeans, and we are required to use textFile, that is to get user input in textFile. Please help. Thank you very much.

Is This A Good Question/Topic? 0
  • +

Replies To: How to limit user input

#2 Miikalsen  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 85
  • Joined: 29-December 11

Re: How to limit user input

Posted 11 September 2012 - 06:47 AM

Just create a If variable. Where if the input is longer then the first input. Print Error. Then return to the top of the program or something. Look at some control flow. :)
Was This Post Helpful? 0
  • +
  • -

#3 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 7999
  • View blog
  • Posts: 13,700
  • Joined: 19-March 11

Re: How to limit user input

Posted 11 September 2012 - 06:48 AM

Quote

Hello. I have a problem with my program. Almost everything is OK with what was required to us, my only problem is how to prompt user that he exceeds from entering an input value that is required.

Example: When the user inputs 3, then in the next line, he must input only 3 numbers, too. If he exceeds or lacks, a message must prompt him.


I have no idea what that has to do with the code you've posted. They seem almost entirely unrelated.
However:

-To prompt a user, send a String to whatever output you're using. To get their input, you'd have to read from that input. From the command line, you'd use a Scanner on System.in. In a GUI, you'd use some sort of text entry, there are too many choices to run them all down.

-All input comes in as a String, you have to convert it to a numeric form if you want to treat it as a number, which in this case you do. You'd do that with the Integer.parseInt() method. There's a convenience method in Scanner that you can use, but you might as well do it the long way first time around. That way you'll understand what's going on when you use the shortcuts - if you decide to use the shortcuts, there are some annoying things about them.

-Once you have the String converted to an int, you need to get the next input. I don't know what "exactly three numbers" means to you*, but once you define "exactly N numbers", you can easily check to see that the user's input matches that.


*Just to point you at the problem, here's some legitimate things that could be "exactly three numbers", depending on how you mean that:

123
1,2,3
1.0,2.7,3,8
3.14 1.14 34
0x1A 0755 -0xFFEE
pi, e, i
Was This Post Helpful? 0
  • +
  • -

#4 jmProg  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 33
  • Joined: 04-July 12

Re: How to limit user input

Posted 11 September 2012 - 07:03 AM

View PostMiikalsen, on 11 September 2012 - 06:47 AM, said:

Just create a If variable. Where if the input is longer then the first input. Print Error. Then return to the top of the program or something. Look at some control flow. :)


I tried using IF statement but it didn't work.. :| I want it to check first all the inputs or count all the input and if it exceeded, then it must show error message..

View Postjon.kiparsky, on 11 September 2012 - 06:48 AM, said:

Quote

Hello. I have a problem with my program. Almost everything is OK with what was required to us, my only problem is how to prompt user that he exceeds from entering an input value that is required.

Example: When the user inputs 3, then in the next line, he must input only 3 numbers, too. If he exceeds or lacks, a message must prompt him.


I have no idea what that has to do with the code you've posted. They seem almost entirely unrelated.
However:

-To prompt a user, send a String to whatever output you're using. To get their input, you'd have to read from that input. From the command line, you'd use a Scanner on System.in. In a GUI, you'd use some sort of text entry, there are too many choices to run them all down.

-All input comes in as a String, you have to convert it to a numeric form if you want to treat it as a number, which in this case you do. You'd do that with the Integer.parseInt() method. There's a convenience method in Scanner that you can use, but you might as well do it the long way first time around. That way you'll understand what's going on when you use the shortcuts - if you decide to use the shortcuts, there are some annoying things about them.

-Once you have the String converted to an int, you need to get the next input. I don't know what "exactly three numbers" means to you*, but once you define "exactly N numbers", you can easily check to see that the user's input matches that.


*Just to point you at the problem, here's some legitimate things that could be "exactly three numbers", depending on how you mean that:

123
1,2,3
1.0,2.7,3,8
3.14 1.14 34
0x1A 0755 -0xFFEE
pi, e, i


Sorry for not stating the problem.. Here it is:

Create a program that would determine the value of the maximum product (the maximum product that can be computed from the inputs).

Sample input:
3 //the user need to input the range of numbers to be computed
2 4 3 //then, the range determines how many inputs will be entered in this line
5
2 5 1 2 1

Sample output:
Maximum product is 24.
Maximum product is 20.

If the user input is:

4
2 3 4 5 6

it must show that the user exceeded, the program is asking only for 4 numbers to be computed.
and if..

4
2 3 4

it also lacks of input, so an error message must be shown also.
Therefore, the numbers must not be multiplied or proceed to the computation..
Was This Post Helpful? 0
  • +
  • -

#5 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 7999
  • View blog
  • Posts: 13,700
  • Joined: 19-March 11

Re: How to limit user input

Posted 11 September 2012 - 07:30 AM

Okay, that's not hard. I'm going to sketch it out, and you're going to try to make it work, okay?

You're going to use the "split" method of the String class. Look it up if you're not familiar with it: it breaks up a String into an array of Strings, using a separator which you provide. So

"a,b,c,d".split(",");

would return the array
{"a", "b", "c","d"}

In this case your separator is the space character (" "). (Later on, you'll learn about regex, which will allow you to split on any whitespace, or any "non-word character" or other fancy tricks - don't worry about that now, though)

Splitting on " " gives you an array of Strings. Check the length of that - is it the required length? If not, the user has failed to enter the correct number of ints. (we're going to be strict, and assume that they're required to enter N integers and nothing else)

If the length is right, you need to verify that each individual item in that array is an integer. They might have entered something like
5
1 2 apple tornado 5


and we don't want to accept that!

This part might be a little tricky, but read up on Integer.parseInt and exception handling and see if you can dope out how I'm thinking you'd want to do it.
There's another way to do it, using regex, but that's probably more complicated to learn for this assignment. You can try that if you want, it might be interesting.

In the meantime, get up to the point where you have an array of Strings and you know that there are exactly the right number of Strings in the array, and if you're still having trouble with the last bit you can check in again.
Was This Post Helpful? 1
  • +
  • -

#6 WannaJava?  Icon User is offline

  • New D.I.C Head

Reputation: -4
  • View blog
  • Posts: 27
  • Joined: 11-September 12

Re: How to limit user input

Posted 11 September 2012 - 01:47 PM

Depends if you are trying to handle spaces...

if you are just checking for 3 characters

string input = input.nextLine();

if(input.length() != 3)
{
    System.out.println("invalid amount of characters");
}


or if you are going to cut the whitespaces
input.replaceAll("//s", "");
if(input.length() != 3)
{
    System.out.println("invalid amount of characters");
}

This post has been edited by jon.kiparsky: 11 September 2012 - 02:46 PM

Was This Post Helpful? -1
  • +
  • -

#7 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 7999
  • View blog
  • Posts: 13,700
  • Joined: 19-March 11

Re: How to limit user input

Posted 11 September 2012 - 02:45 PM

@WannaJava - First of all, please use more English and less code in responding to homework problems. The point of homework is to solve a problem, not to look up an answer on the internet, and when you give people the code they stop trying to solve the problem.


Second, please read the problem carefully before trying to answer it. Your solution doesn't really make sense in the context of the actual problem. He's not trying to check that there are exactly three characters, and he's not trying to delete whitespace.

Your answer does suggest a plausible solution, but it's a bad one. That is, if we wanted to assume that the user's input is going to be small numbers we could remove whitespace and then parse the result as an int - but then we fail if the user input is too big.

EDIT: Also, please use the code tags.

This post has been edited by jon.kiparsky: 11 September 2012 - 02:46 PM

Was This Post Helpful? 1
  • +
  • -

#8 jmProg  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 33
  • Joined: 04-July 12

Re: How to limit user input

Posted 12 September 2012 - 05:55 PM

Thanks for all your help! :) I came up with an if statement. But all your ideas helped. Many THANKS!!

now here it is, it worked:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class MaximumProduct {
    public static void main(String[] args) throws FileNotFoundException {
        File textFile = new File("newfile.txt");
        try (Scanner scanner = new Scanner(textFile)) {
           
            while (scanner.hasNext()) {
                int firstNumber = scanner.nextInt();
                int array[] = new int[firstNumber];
                
                    int compute = 1;
                    int j = 0;
                    for (int i = 0; i < array.length; i++) {
                        array[i] = scanner.nextInt();
                        j = array[i];
                        
                        if (array[i] > 0) {
                            compute *= array[i];
                        } 
                    } if (j > array.length) {
                        System.out.println("Your input exceeded.");
                        continue;
                    }
                    System.out.println("The maximum product is " + compute + "."); 
                }      
           } 
      } 
}



but.. when i run it...

example:
INPUT:

4
1 2 3 4 5

OUTPUT:

Your input exceeded.
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at javaprogram1.MaximumProduct.main(MaximumProduct.java:26)
Java Result: 1

Eventhough it worked, i was confused that an error occur after the message.. what does those mean? THANKS :D
Was This Post Helpful? 0
  • +
  • -

#9 Cuzzie  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 72
  • View blog
  • Posts: 341
  • Joined: 16-July 10

Re: How to limit user input

Posted 12 September 2012 - 07:14 PM


                    for (int i = 0; i < array.length; i++) {
                        array[i] = scanner.nextInt();
                        j = array[i];
                        
                        if (array[i] > 0) {
                            compute *= array[i];
                        } 
                    } if (j > array.length) {
                        System.out.println("Your input exceeded.");
                        continue;
                    }



Your code here, every time the loop runs, the value of array[i] is assigned to variable "j". Once the for loop ends, the current value of "j" is then checked with the length of the array. It doesn't make any sense to assign the value of "array[i]" to "j". Here, let me give you an example.

Let's say the length of your array is 3, and by the end of your for loop the value of "j" is 100. Your code then proceeds to check if 100 is bigger than 3, then shows you the "Your input exceeded." message.

You should be assigning "i" to "j" instead, and then check if the value of "j" exceeds the array length.

array[i] = scanner.nextInt();
j = i;



But even if you do this, your input will never exceed the array length. At the beginning of your while loop, "firstNumber" is assigned a value, and then the array is created with a size of this number. In the for loop, for (int i = 0; i < array.length; i++) checks if the value of "i" is less than length of array before executing the code, so it means the number of inputs will never be bigger than "firstNumber".
Was This Post Helpful? 1
  • +
  • -

#10 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 7999
  • View blog
  • Posts: 13,700
  • Joined: 19-March 11

Re: How to limit user input

Posted 12 September 2012 - 08:22 PM

If you run the program in your head, or on paper, you'll start to see what's going on. Take a small input and go through, doing each of the things you're telling the machine to do and nothing else.

This sort of exercies is critical to becoming a good programmer, and the more you do it the easier it is to do. If you make this effort explicitly now, with relatively simple programs, you'll find that reading more compicated code later on is quite easy.

Quote

You should be assigning "i" to "j" instead, and then check if the value of "j" exceeds the array length.


I'm not sure I understand your thinking here, Cuzzie - you seem to be making the same mistake that jmProg made. The problem is not whether any particular value in the array is greater than the length of the array. The question is whether you're reading in exactly N numbers, where N is the number the user provided in step 1.

One way to do this is as follows (very rough sketch form)

Notice, I've left out the calculations - you can fold those in easily enough, I think.
Get a number N, which is the number of ints to read from the user.
Declare an array of length n.
Get integers from the user, and put them into the slots of the array, one at a a time.
If you get to the end of the array, and there are more inputs remaining, break out of the procedure and report and error
If you get to the end of the input, and there is still more array remaining, break out of the procedure and report and error

If you get to the end of the array, and there is no more input, report a success.

Notice that we never look at the numbers the user is submitting: as long as they're numbers, we're cool. They can be greater than array.length, we don't mind.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1