Validating the kind of data in an ArrayList java - java

Hello everyone~ I'm a little new in this theme of programming. I'm here to expose a particular case, of my college project, hoping that can find a way to validate the java code.
Basically, I'm designing a system to sum the daily sales of a company and save them into a matrix. The code below corresponds to the first day only.
package fsystem;
import java.util.ArrayList;
import java.util.Scanner;
public class class_Sist {
public class_Sist() {
}
ArrayList <Integer> MondayPrices = new ArrayList();
int Week[][]= new int [2][7];
public void addPricesDay1(){
Scanner scn = new Scanner(System.in);
String answer;
Integer auxAddition=0;
boolean flagNext= false, flagAgain= false;
System.out.println("Next it is come to apply the amounts of sales made on the day "+Week[0][0]+". Please "
+ "indicate the price of each of the items that were sold.");
do {
System.out.println("Enter the price of the corresponding article.");
MondayPrices.add(scn.nextInt());
do {
System.out.println("It requires enter the price of another article?");
answer= scn.next();
if (("Yes".equals(answer))||("yes".equals(answer))) {
flagNext=false;
flagAgain=true;
}
if (("No".equals(answer))||("no".equals(answer))){
flagNext=false;
flagAgain=false;
System.out.println("Introduced sales prices have been stored successfully.");
}
if ((!"Yes".equals(answer))&&(!"yes".equals(answer))&&(!"No".equals(answer))&&(!"no".equals(answer))) {
System.out.println("Error. Please respond using by answer only yes or no.");
flagNext=true;
}
} while (flagNext==true);
} while (flagAgain==true);
for (int i=0; i<MondayPrices.size(); i++) {
auxAddition= auxAddition+MondayPrices.get(i);
}
System.out.println("The total amount in sales for monday is "+auxAddition);
Week[1][0]=auxAddition;
}
}
So, what I need is to validate that the data inputted by the user be only numeric, and never otherwise, but I don't know completely how ArrayList works, therefore, I would greatly appreciate if someone could explain me how I can do that.

Use Scanner hasNextInt() function.
Returns true if the next token in this scanner's input can be interpreted as an int value in the specified radix using the nextInt() method.The scanner does not advance past any input.
Use it with while to check whether the input is integer.
Scanner stdin = new Scanner(System.in);
while (!stdin.hasNextInt()) stdin.next();
MondayPrice.add(stdin.nextInt());
http://docs.oracle.com/javase/6/docs/api/java/util/Scanner.html#hasNextInt%28%29

You can validate the input before adding the integer in the ArrayList.
I hope this will help - How to use Scanner to accept only valid int as input

Related

When user presses "enter" key or space enter then error message pops up

I would like to print an error message when the user presses enter or space enter instead of a string. I have tried isEquals("") and isEmpty() but haven't found anything that works yet.
Here's my code:
import java.util.Scanner;
public class check{
public static void main(String args[]){
System.out.println("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
String input = keyboard.next();
if(input.equals("")){
System.out.println("Empty");
} else {
System.out.println("number inputed");
}
}
}
One way to do this, change keyboard.next() to keyboard.nextLine(), use trim() to remove unnecessary spaces, check with isEmpty().
String input = keyboard.nextLine().trim();
if (input.isEmpty()) {
// error message
} else {
// good to go
}
import java.util.Scanner;
public class check{
public static void main(String args[]){
System.out.println("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
if(input.trim().equals("")){
System.out.println("Empty");
} else {
System.out.println("number inputed");
}
}
}
Strangely, I don't get an error when running your code. However, I noticed that your code simply doesn't react to an empty input (just pressing enter). If you want to check for that, you can use keyboard.nextLine().
Judging by the rest of your code, it seems like you want the user to input only a number. An easy way to check if the user entered an integer if you're using Scanner is keyboard.hasNextInt().
Meaning you can do something like this:
if(keyboard.hasNextInt()) {
int yourNumber = keyboard.nextInt();
System.out.println("Your number is: " + your Number);
}
else {
System.out.println("Please enter a valid integer");
}
To check whether the string input is empty, you can use the String.isEmpty() method. Look below:
String input = keyboard.nextLine();
if(!input.isEmpty()) {
//the input is not empty!
}
else {
//the input is empty!
}
Note, however, that since you want to receive numbers as inputs you should not retrieve them as strings. Below is an example where the program retrieves a double from the user. Scanner provides many methods to validate the user's input. In this case, I'm using hasNextDouble() to check whether the input is a number.
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number:");
while(!scanner.hasNextDouble()) {
System.out.println("That's not a number!");
scanner.next();
}
double numberInput = scanner.nextDouble();
System.out.println("The entered number was " + numberInput);
I made a sample program similar to yours and used nextLine() instead of next(). When user enters space and clicks enter he will print "space" else "a number".

Is there another way to use hasNextInt() in Java without putting everything in the if-statement?

My objective is to make sure the user inputs an int. Else, exit the program. Then I do some coding that requires that int.
Code Snippet :
Scanner input = new Scanner(System.in);
if (input.hasNextInt()) {
//check if user enters an int
int userinput = input.nextInt();
// assign that int input to variable userinput
// over 100+ lines of code using nextInt var "userinput"
} else {
System.exit(1);
// user did not enter an int
}
Is there a better way to check for whether a user has entered an int and then use that int that doesn't require my entire program to be coded into that if-statement (because nextInt's scope is limited to that if-statement)?
It feels messy to me to put everything into one if-statement.
I wouldn't be allowed to use separate objects/classes since it's early in the semester for my class. This all goes in the main method, and I'm just using simple if-statements/scanner inputs.
Thanks
Definitely! Just negate the if statement and early exit:
Scanner input = new Scanner(System.in);
if (!input.hasNextInt()) {
System.exit(1);
}
// "else"
doMagicalThings(input.nextInt());
Oh, I guess also to note: replace the 100 lines of code with a method call and break it up a bit. That'd be good to do in addition to the above.
Here is a simple example of using hasNextInt () to validate a positive integer input
Scanner input = new Scanner(System.in);
int number;
do {
System.out.println("Input Number ");
while (!input.hasNextInt()) {
System.out.println(" not a number!");
input.next();
}
number = input.nextInt();
} while (number <= 0);
System.out.println("Númber válid " + number);

How do I use java.util.Scanner with integers

I just started learning java and I want to make a simple program where it requests the persons
name, outputs the name then asks for the thier favorite number. It will then compare their number
to the number 6 and will output something depending on if the number is larger or smaller than 6.
I am getting a "String to int convert" error in Netbeans which has to do with the scanner.
Hopefully I am asking this correctly but how can I make the scanner pick-up integers?
Thanks
package javaapplication2;
import java.util.Scanner;
import java.lang.String;
public class JavaApplication2 {
public static void main(String[] args) {
// Creating an instance of the scanner class.
// Gets name and numbers.
Scanner getName = new Scanner(System.in);
Scanner getNumber = new Scanner(System.in);
//Holds name and number
String userName;
int userNumber;
// Asks for the users name.
// Holds name in userName.
System.out.println("What is your name?");
userName = getName.nextLine();
//Reponds with the users name.
System.out.println("Hello" + userName + "!");
//Asks for favorite number.
// Holds number in userNumber.
System.out.println("What is your favorite number?");
userNumber = getNumber.nextLine();
// Checks if users number is larger than 6.
if (userNumber > 6) {
// Stuff goes here.
}
}
}
You should use only one Scanner for one input stream:
Scanner in = new Scanner(System.in);
And after that you should use it's methods to get integers:
String name = in.nextLine();
int number = in.nextInt();
To be sure, you should read the documentation for Scanner:
Scanner
Scanner::nextLine
Scanner::nextInt
This might help: Javadoc page for Scanner.

How to insist that a users input is an int?

Basic problem here.. I will start off by asking that you please not respond with any code, as that likely will only confuse me further (programming noob). I am looking for a clear explanation on how to solve this issue that I'm having.
I have a scanner that reads input from the user. The user is prompted to enter an int value between 1 to 150 (whole numbers only). I obtain the value as follows:
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
And continue on with my program, and everything works fine.
Unfortunately, the code isn't exactly bulletproof, since any input that is not an integer can break it (letters, symbols, etc).
How can I make the code more robust, where it would verify that only an int was entered?
These are the results I'm hoping for:
Lets say the input was:
23 -> valid
fx -> display an error message, ask the user for input again (a while loop would do..)
7w -> error, again
3.7 -> error
$$ -> error
etc
Scanner.hasNextInt() returns true if the next token is a number, returns false otherwise.
In this example, I call hasNextInt(). If it returns true, I go past the while and set the input; if it returns false, then I discard the input (scanner.next();) and repeat.
Scanner scan = new Scanner(System.in);
while(!scan.hasNextInt()) {
scan.next();
}
int input = scan.nextInt();
Here's a simple example with prompts and comments.
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer: "); // Initial prompt for input
// Repeat until next item is an integer
while (!scan.hasNextInt())
{
scan.next(); // Read and discard offending non-int input
System.out.print("Please enter an integer: "); // Re-prompt
}
// At this point in the code, the user has entered an integer
int input = scan.nextInt(); // Get the integer
// And now you can use the input variable.
Use scan.hasNextInt() to make sure the next input is an int.
I have written an example that ensures that the program will continue only if a number and not an invalid value is entered. Do not worry, I added the desired explanation.
The program asks the user to input a number. A loop ensures that the processing will not go on until a valid number is entered. Before that I have defined a variable "inputAccepted" that has false as default value. If he enters a number, the variable "inputAccepted" is set to true and the program leaves the loop. But if he enters something else than a number, an exception is thrown right in this moment, and the line that sets the variable "inputAccepted" to true will not be executed. Instead a message will be printed out that tells the user that his input is not valid. Since "inputAccepted" could not be set to true, the loop will do the same stuff again until the string can be converted to a number.
You can test the program here.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean inputAccepted = false;
while (!inputAccepted) {
try {
System.out.print("Please enter a number: ");
Integer.valueOf(input.nextLine());
inputAccepted = true;
} catch (NumberFormatException e) {
System.out.println("Not a valid number.");
}
}
System.out.println("Thank you!");
}
}
Just get "anything" and parse it:
Scanner scan = new Scanner(System.in);
Integer number = null;
while (number == null) {
try {
number = Integer.parseInt(scan.next());
} catch (NumberParseException e) {
System.out.println("bad input: " + input);
}
}
Without any code and just in English, I'd say there's two things you have to test or look out for. First that the input is an int, second that the int is within the correct range.
In terms of pseudocode, the first thing to do is make sure it's an int. Declaring an int named "input", I would put a try / catch block, where you try to scan in the user input as an int, with parseInt(). If the try part fails, you know it's not an int and can return an error message.
Then, now that you know that "input" is an int, you can test whether it is less than 1 or more than 150, and return an error message if so!
public class Sample {
/**
* author CLRZ
*/
public static void main(String[] args) {
int a; // variable
Scanner in = new Scanner(System.in); // scans your input
System.out.println("Enter your number's choice:");
int sem1 = in.nextInt(); // reads next integer
if (sem1 == 1) // conditioned if your choice number is equal to 1
System.out.println("Hello World1"); // output wil be Hello World
int b;
System.out.println("Enter your number's choice:");
int sem2 = in.nextInt();
if (sem2 == 2)
System.out.println("Hello World2");
int c;
System.out.println("Enter your number's choice:");
int sem3 = in.nextInt();
if (sem3 == 3)
System.out.println("Hello World3");
}
}

Java - Accept different keys from user to do different tasks, terminate when user clicks "X"

I'm still a newbie to Java so if this question sounds dumb, please enlighten me. Any suggestion is appreciated.
I'm thinking of some way to implement a program which allows user to input a key from the keyboard to do different tasks. The thing is, the program should be able to continue until the user clicks a specific key, let's say, "X".
This is part of the class PizzaDemo I'm working on and part of the getPizzas() method which performs the above task:
public class PizzaDemo {
private PizzaOrder list;
public PizzaDemo(){
list = new PizzaOrder();
}
public static void getPizzas(){
Scanner sc = new Scanner(System.in);
System.out.println("To add a new Ham & Cheese pizza, press H.");
System.out.println("To add a new Pepperoni pizza, press P.");
System.out.println("To add a new Tropical pizza, press T.");
System.out.println("To exit, press X");
String input = sc.next();
while(!input.equalsIgnoreCase("H") && !input.equalsIgnoreCase("P") && !input.equalsIgnoreCase("T") && !input.equalsIgnoreCase("X")){
System.out.println("Invalid key. Enter again: ");
input = sc.next();
}
if (input.equalsIgnoreCase("H")){
System.out.println("Enter the size of the pizza: ");
String size = sc.next();
System.out.println("Enter the number of ham toppings: ");
int n1 = sc.nextInt();
System.out.println("Enter the number of cheese toppings: ");
int n2 = sc.nextInt();
Topping[] top = {createTopping("ham", n1), createTopping("cheese", n2)};
Pizza p = createHamCheese(size, top);
PizzaDemo demo = new PizzaDemo();
demo.list.setPizza(p);
getPizzas();
}
// the rest of the code is omitted
}
}
The problem is, I can't seem to find any way to use the constructor in such a way that the previously added element can still be kept even though the recursion (in the if block) is called. Anyone has some suggestion for me? The constructor is used for initializing a new pizza order, and it's a part of the program so I cannot omit it.
Thanks in advance guys.
Don't use recursion for this. You could end up with a stack overflow, no pun intended. Use a loop.
public static void getPizzas(){
Scanner sc = new Scanner(System.in);
String input;
do{
//put code in here
} while(!input.equalsIgnoreCase("X");
}
You would have to provide an overloaded constructor that takes the List of Pizzas as an arg.

Categories