I am new to Learning java so i am stuck and i don't understand how to fix this error i am stuck here for last 2 days i am making a a validation sign up form kindly explain me what i have to do to fix this error and need more suggestion or any other way to develop a form like this is university assignment.
Form development with scanner using nextint, nextLine etc and sorry for the bad english i tried my best to explain the problem i mention error below at the end of the code kindly check it .
import java.util.Scanner;
public class Vali{
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter User Name :");
String uname = s.nextLine();
System.out.println("Enter Password :");
String pass = s.nextLine();
System.out.println("Enter Number :");
if (s.hasNextInt()) {
int numberr = s.nextInt() ;
} else {
System.out.println("Please Enter The Number");
}
if (!uname.equals("") && !pass.equals("") && !numberr.equals("") ) {
System.out.println("logged in");
} else if(!uname.equals("") && !numbe.equals("")) {
System.out.println("fill the feild");
} else {
System.out.println("invalid");
}
}
}
I am getting this error kindly guide me
Vali.java:23: error: cannot find symbol
if (!uname.equals("") && !pass.equals("") && !numberr.equals("") ){
^
symbol: variable numberr
location: class Vali
Change as below :
1 - declare number out of the if
2 - use == to compare int instead equal method in the if condition
public class Vali{
public static void main(String[] args){
int numberr = 0;
Scanner s = new Scanner(System.in);
System.out.println("Enter User Name :");
String uname = s.nextLine();
System.out.println("Enter Password :");
String pass = s.nextLine();
System.out.println("Enter Number :");
if (s.hasNextInt()) {
numberr = s.nextInt() ;
} else {
System.out.println("Please Enter The Number");
}
if (!uname.equals("") && !pass.equals("") && !(numberr == {SOME_NUMBER}) ){
System.out.println("logged in");
}
else if(!uname.equals("") && !numbe.equals("")) {
System.out.println("fill the feild");
}
else{
System.out.println("invalid");
}
}
}
The variable numberr was created in another if statement before you used it, therefore it can't be found if it wasn't set. Also numberr can never equal "" since it's an Integer and not a String. To make your code work write it like this:
int numberr = 0;
if (s.hasNextInt()) {
numberr = s.nextInt() ;
} else {
System.out.println("Please Enter The Number");
}
if (!uname.equals("") && !pass.equals("") && numberr != 0 ){
System.out.println("logged in");
}
An even better way to do this, is not to check if numberr has the standard value 0, since the user might want to set it to 0. So you could introduce a boolean value to determine if numberr was set. The code would then look like this:
boolean b = false;
int numberr = 0;
if (s.hasNextInt()) {
numberr = s.nextInt() ;
b = true;
} else {
System.out.println("Please Enter The Number");
}
if (!uname.equals("") && !pass.equals("") && b ){
System.out.println("logged in");
}
I don't know what you are trying to achieve exactly, but if you want to force the user to put a number in, you might want to consider using loops as well like this, then you won't have to check if numberr is set, since the user is forced to set it:
while(!s.hasNextInt()) {
System.out.println("Please Enter The Number");
}
int numberr = s.nextInt() ;
if (!uname.equals("") && !pass.equals("")){
System.out.println("logged in");
}
Related
As I have shown the codes below, option 1 initiates setting up a player name but it has to be between 3 and 25 characters long and also should not have any blank space. What logic and methods should be used behind this reason after the (String name = " ") statement?
import java.util.*;
public class Game
{
private Player player;
public Game()
{
this.player = null;
}
public void showMenu()
{
while(true)
{
System.out.println("=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=");
System.out.println("Welcome to Lucky Vending Machine Game");
System.out.println("=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=");
System.out.println("Please select 1 to Register a Player");
System.out.println("Please select 2 to Play a Round");
System.out.println("Please select 3 to View Round Information");
System.out.println("Please select 4 to Get Help");
System.out.println("Please select 5 to Exit");
System.out.println("Choose an option: ");
Scanner menuScanner = new Scanner(System.in);
int option = menuScanner.nextInt();
if (option < 1 || option > 5)
{
System.out.println("Error: Please, choose a number from 1 to 5");
continue;
}
else if(option == 1)
{
System.out.println("Please enter the player name");
Scanner playerName = new Scanner(System.in);
String name = " ";
player = new Player(name);
}
}
}
}
public boolean isValidName(String playerName) {
int length = playerName.length();
return ((length >= 3 && length <= 25) && !playerName.contains(" "));
}
You can use the below piece of code, here I am including only else part
else if(option == 1)
{
System.out.println("Please enter the player name");
Scanner scanner = new Scanner(System.in);
String name = " ";
name = scanner.next(); // return type for next() is string
if(name.length()>=3 && name.length()<=25 && !name.contains(" ")){
player = new Player(name);
}else{
System.out.println('Name length should be between 3 and 25 characters");
}
}
First, no need for another Scanner. The first scanner can be used for the playerName scanning.
Second, it's somehow a basic grammar.
else if(option == 1)
{
System.out.println("Please enter the player name");
String name = menuScanner.next();
if (name.length >= 3 && name.length <= 25 && !Pattern.compile("\\s").matcher(name).find())
{
// valid name
player = new Player(name);
}
else
{
// invalid name, do some warning output and ask user to reenter again.
}
}
Note that "blank space" may not only contains white space, but maybe a \t too.
You can use this,
Scanner sc = new Scanner(System.in);
String PlayerName = "";
do {
System.out.println("Enter a player's name");
PlayerName = sc.nextLine();
if((PlayerName.length()<3 && PlayerName.length()>25)|| PlayerName.contains(" "))
System.out.println("Invalid number !!!");
}while((PlayerName.length()<3 && PlayerName.length()>25) || PlayerName.contains(" "));
If you have more validations, you can use the .matches() method by passing the regular expression in it.
I'm new to Java, and I'm working on a method in my program that checks the users input to be within bounds, not a null value (zero), not a letter, and a positive number. So originally I incorporated two while loops within this method to check for the validity of these inputs, but I would like to simplify it in one loop. I'm getting an error when I input a letter (ex. a) after a few inputs, and I believe it is due to the two different while loops making it more complicated. Can someone help me with this please?
public static void valid(String s, int max)
{
while(sc.hasNextInt() == false) {
System.out.println("That is not correct. Try again:");
sc.nextLine();
}
int value;
while((value= sc.nextInt()) > max || (value= sc.nextInt()) <= 0){
System.out.println("That is not correct. Try again: ");
sc.nextLine();
}
sc.nextLine();
return;
}
You have:
int value;
while((value= sc.nextInt()) > max || (value= sc.nextInt()) <= 0){
System.out.println("That is not correct. Try again: ");
sc.nextLine();
}
Which is doing sc.nextInt() twice, so value does not necessarily have the same value in these two cases and it is also asking you for a number twice.
A fix would be something like this:
int value;
while((value = sc.nextInt()) > max || value <= 0) {
System.out.println("That is not correct. Try again: ");
sc.nextLine();
}
which would make it better but you still have issues. If value is bigger than max, then the loop will iterate again calling nextInt() but this time you have not checked for hasNextInt(). This is why you'd better have everything in one loop. Something like this:
public static void valid(String s, int max) {
while(true) {
if(!sc.hasNextInt()) { //this is the same as sc.hasNextInt() == false
System.out.println("That is not correct. Try again:");
sc.nextLine();
continue; //restart the loop again
} else {
int value = sc.nextInt();
if(value > max || value <= 0) {
System.out.println("That is not correct. Try again:");
sc.nextLine();
continue; //restart the loop from the top - important!
} else {
extendedValidation(value, s);
return;
}
}
}
}
Try something more like (pseudo code):
while valid input not yet received:
if input is an integer:
get integer
if in range:
set valid input received
skip rest of line
extended validation
With a little thought, you should be able use one "print error message" statement. But using two could be arguably better; it can tell the user what they did wrong.
What is the purpose of the String s parameter? Should you be checking that instead of a Scanner input?
Also, don't be surprised by mixing nextInt() and nextLine(). -- Source
I prefer using do-while loops for input before validation.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int max = 1000;
int val = -1;
String in;
do {
// Read a string
System.out.print("Enter a number: ");
in = input.nextLine();
// check for a number
try {
val = Integer.parseInt(in);
} catch (NumberFormatException ex) {
// ex.printStackTrace();
System.out.println("That is not correct. Try again.");
continue;
}
// check your bounds
if (val <= 0 || val > max) {
System.out.println("That is not correct. Try again.");
continue;
} else {
break; // exit loop when valid input
}
} while (true);
System.out.println("You entered " + val);
// extendedValidation(value, in);
}
I would say that this is a lot closer to what you're looking for, in simple terms...
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
final int MIN = 0;
final int MAX = 10;
Scanner sc = new Scanner(System.in);
int value = -1;
boolean valid;
do {
valid = sc.hasNextInt();
if (valid) {
value = sc.nextInt();
valid = value > MIN && value < MAX;
}
if (!valid) {
System.out.println("Invalid!");
sc.nextLine();
}
} while (!valid);
System.out.println("Valid Value: " + value);
}
}
You should be able to abstract this code to suit your requirements.
im trying to do two checks with a while loop:
1) To show "error" if the user inputs something other than an int
2) Once the user entered an int, if it is one digit, show "two digits only" and keep the loop on until a two digit int has been entered (so an IF should be used as well)
Currently I only have the first part done:
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number");
while (!scan.hasNextInt()) {
System.out.println("error");
scan.next();
}
However, if possible, I would like to have both checks in one while loop.
And that's where I'm stuck...
Since you already have two answers. This seems a cleaner way to do it.
Scanner scan = new Scanner(System.in);
String number = null;
do {
//this if statement will only run after the first run.
//no real need for this if statement though.
if (number != null) {
System.out.println("Must be 2 digits");
}
System.out.print("Enter a 2 digit number: ");
number = scan.nextLine();
//to allow for "00", "01".
} while (!number.matches("[0-9]{2}"));
System.out.println("You entered " + number);
As said above you should always take the input in as string and then try
and parse it for an int
package stackManca;
import java.util.Scanner;
public class KarmaKing {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = null;
int inputNumber = 0;
while (scan.hasNextLine()) {
input = scan.next();
try {
inputNumber = Integer.parseInt(input);
} catch (Exception e) {
System.out.println("Please enter a number");
continue;
}
if (input.length() != 2) {
System.out.println("Please Enter a 2 digit number");
} else {
System.out.println("You entered: " + input);
}
}
}
}
First take the input as a String. If it is convertible to Int then you do your checks, else say 2 digit numbers are acceptable. If it is not convertible to a number throw an error. All this can be done in one while loop. And you would like to have a "Do you want to continue? " kind of a prompt and check if the answer is "yes" / "No." Break from the while loop accordingly.
To have it as one loop, it's a bit messier than two loops
int i = 0;
while(true)
{
if(!scan.hasNextInt())
{
System.out.println("error");
scan.next();
continue;
}
i = scan.nextInt();
if(i < 10 || >= 100)
{
System.out.println("two digits only");
continue;
}
break;
}
//do stuff with your two digit number, i
vs with two loops
int i = 0;
boolean firstRun = true;
while(i < 10 || i >= 100)
{
if(firstRun)
firstRun = false;
else
System.out.println("two digits only");
while(!scan.hasNextInt())
{
System.out.println("error");
scan.next();
}
i = scan.nextInt();
}
//do stuff with your two digit number, i
This while loop that is suppose to prompt for a price and a y/n and end if price = 0. However, when I run the code, it asks for the price, takes it, goes to a blank line, and I have to enter the number again before asking me the next question. For the second question, I only have to enter the input once.
And when I print the price array, the value is the number I inputted the second time.
int keepGoing = 1;
while (keepGoing > 0) {
System.out.print("How much is the item? (If no more items, enter '0') ");
if (in.nextDouble() > 0) {
prices.add(in.nextDouble());
System.out.print("Is the item a pet? (Y or N) ");
String input = in.next();
if (new String("Y").equals(input) || new String("y").equals(input)) {
isPet.add(true);
}
else { isPet.add(false); }
}
else { keepGoing = 0; }
}
Help please?
That's because each time you write in.nextDouble(), the user will be need to type something into the scanner. Instead, you should store the input in a tempory variable:
Double input = in.nextDouble(); // Keep the input in this variable
if (input > 0) { // You can use it on each of these lines
prices.add(input); // so that the user doesn't have to type it twice.
System.out.print("Is the item a pet? (Y or N) ");
String input = in.next();
if (new String("Y").equals(input) || new String("y").equals(input)) {
isPet.add(true);
}
else { isPet.add(false); }
}
else { keepGoing = 0; }
A little side note: keepGoing should probably be a boolean instead of an int
Also, you can use new String("Y").equalsIgnoreCase(input) so that you don't need the ||
It asks you twice because you call the in.nextDouble() method twice, one in the if statement and another time in the following line.
Take a look at the comments on your code below:
int keepGoing = 1;
while (keepGoing > 0) {
System.out.print("How much is the item? (If no more items, enter '0') ");
if (in.nextDouble() > 0) { // <-- You are asking for the input here
prices.add(in.nextDouble()); // <-- and asking for the input here again.
System.out.print("Is the item a pet? (Y or N) ");
String input = in.next();
if (new String("Y").equals(input) || new String("y").equals(input)) {
isPet.add(true);
}
else { isPet.add(false); }
}
else { keepGoing = 0; }
}
Just change your code to be like this:
int keepGoing = 1;
double d = 0;
while (keepGoing > 0) {
System.out.print("How much is the item? (If no more items, enter '0') ");
d = in.nextDouble();
if (d > 0) {
prices.add(d);
System.out.print("Is the item a pet? (Y or N) ");
String input = in.next();
if (new String("Y").equals(input) || new String("y").equals(input)) {
isPet.add(true);
}
else { isPet.add(false); }
}
else { keepGoing = 0; }
}
I am learning java in the internet in sites like "oracle academy" and using Google to search how to do somethings, i wanted to make a simple java program that takes an number(day) a number or word(month) and another number(year), so if you input something like
"3" "1" and "1993"
it outputs
"January 1st, 1993"
and if you input something like
"2" "July" and "1992"
it outputs
"7/2/1992"
I kind of already know how to make it using "case" and while loops to tell you if you input something incorrectly, but on the "day" part i tried using a while loop to keep asking you to input something if the input wasn't a number between 1 and 31 but i can't make it return the number from the while loop using the return command, is there any way to return the number without using the return command or not?
the code:
public static void main(String[] args) {
String x;
Scanner scan = new Scanner(System.in);
//day
System.out.println("Insert Day");
while (1 < 2){
x = scan.nextLine();
if (x.matches(".*\\d.*")){
q = Integer.parseInt(x);
if ((0 < q) && (q < 32)){
return q;
}
else {
System.out.println("please use a valid number");
}
}
else {
System.out.println("please use a number");
}
}
System.out.println(q);
You can use return if you refactor this into a separate function:
public static int getDay() {
Scanner scan = new Scanner(System.in);
System.out.println("Insert Day");
while (true){
line = scan.nextLine();
if (line.matches(".*\\d.*")){
int day = Integer.parseInt(line);
if (0 < day && day < 32){
return day;
} else {
System.out.println("please use a valid number");
}
} else {
System.out.println("please use a number");
}
}
}
public static void main(String[] args) {
int day = getDay();
System.out.println(day);
}
Or you could use a break:
Scanner scan = new Scanner(System.in);
System.out.println("Insert Day");
int day = -1;
while (true){
line = scan.nextLine();
if (line.matches(".*\\d.*")){
day = Integer.parseInt(line);
if (0 < day && day < 32){
break;
} else {
System.out.println("please use a valid number");
}
} else {
System.out.println("please use a number");
}
}
Or you could use your while condition:
int day = -1;
Scanner scan = new Scanner(System.in);
System.out.println("Insert Day");
while (day < 1 || day > 31){
line = scan.nextLine();
if (line.matches(".*\\d.*")){
day = Integer.parseInt(line);
if (day < 1 || day > 31){
System.out.println("please use a valid number");
}
} else {
System.out.println("please use a number");
}
}
Also, you can simplify your code by using the NumberFormatException parseInt throws, instead of trying to validate it yourself with a regular expression:
int day = -1;
Scanner scan = new Scanner(System.in);
System.out.println("Insert Day");
while (day < 1 || day > 31){
line = scan.nextLine();
try {
day = Integer.parseInt(line);
if (day < 1 || day > 31){
System.out.println("please use a valid number");
}
} catch (NumberFormatException e) {
System.out.println("please use a number");
}
}
The return statement returns a value from the entire method you're in. But you're in main, which can't return a value (it's void).
If you want to end the while loop when you have a good value, then use the break statement to break out of the while loop. Control then passes to the next statement following the end of the loop.