Java - Adding constraints - java

I have made this class for fun, and now I want to add some constraints and if statements. But don't know how.
Problem 1) I don't know how to do an if statement on System.out.print outputs. Say, if the user enter more than 50 characters then they'll be stopped.
I know how to do this in MySQL but not in Java as I'm very inexperienced ATM. :|
Problem 2) I also want to restrict myself from entering digits if it's nextLine, or text if it's nextInt.
Can anyone help me on these two problems?
import java.util.Scanner;
class AppForm {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name... ");
System.out.println("Your name is " + sc.nextLine());
System.out.print("Enter your age... ");
System.out.println("Your age is " + sc.nextInt());
}
}
Thanks.

You should start by breaking apart the input and output code by storing the result of nextLine() in a variable:
System.out.print("Enter your name... ");
String line = sc.nextLine();
System.out.println("Your name is " + line);
You can then perform any check you need on the line string variable. The typical paradigm in the case of an interactive program is to print out an error message and ask the user to repeat the entry in case of invalid input:
System.out.print("Enter your name... ");
String line = sc.nextLine();
while (line.length() > 50) {
System.out.println("Error: you entered more than 50 characters");
// Ask the user for their name again...
System.out.print("Enter your name... ");
line = sc.nextLine();
}
System.out.println("Your name is " + line);
Unfortunately there is no way to prevent the user from typing invalid characters - you can only check the content of the line after the user has finished typing and your program receives the typed line.

I would recommend at taking a look at while loops.
Some possibilities:
String name;
do {
System.out.print("Enter your name... ");
String line = sc.nextLine();
while (StringUtils.isEmpty(name) || name.length() > 50)
Or:
String name;
while (StringUtils.isEmpty(name)) {
System.out.print("Enter your name... ");
name = sc.nextLine();
if (name.length >= 50) {
System.out.println("Max name length is 50");
}
}
But there are plenty of flow control options.

Related

How do I get the name input to read whitespaces

So im having trouble getting the first read input to read all inputs on the line. But for some reason it doesnt take into consideration of whitespaces. in fact, it considers the whitespace from the print information as part of the whitespace. only name has this problem. ID does not have this problem. I would just like to know how to fix this one problem since it is giving me the most trouble.
public class Project2 {
public static Scanner sc = new Scanner (System.in);
public static void main(String[] args) {
PersonList PersonList = new PersonList();
System.out.print("Welcome to my personal Management Program\n\n");
System.out.print("\nChoose one of the following options: \n\n");
//print out options for user
for (;;) {
int input = 0;
System.out.print("1- Enter the information of a faculty\n");
System.out.print("2- Enter the information of a student\n");
System.out.print("3- Print tuition person for a student\n");
System.out.print("4- Print faculty information\n");
System.out.print("5- Enter the information of a staff member\n");
System.out.print("6- Print the information of a staff member\n");
System.out.print("7-Exit the program\n\n");
System.out.print("\tEnter a selection: ");
input = sc.nextInt();
if (input == 1) {
faculty f = new faculty();
System.out.print("Enter the faculty info:\n");
System.out.print("\tName of Faculty: ");
f.name = sc.nextLine();
System.out.print("\tID: ");
f.ID = sc.nextLine();
String rank, department;
for(;;) {
System.out.print("\n\tRank: ");
rank = sc.nextLine();
if (rank.equalsIgnoreCase("professor") || rank.equalsIgnoreCase("adjunct")) {
f.rank = rank;
break;
}
else {
System.out.print("\"" + rank +"\" is invalid");
}
}
for(;;) {
System.out.print("\tDepartment: ");
department = sc.nextLine();
if (department.equalsIgnoreCase("mathematics") || department.equalsIgnoreCase("engineering") || department.equalsIgnoreCase("sciences")) {
f.Department = department;
break;
}
else {
System.out.print("\"" + department +"\" is invalid");
}
}
System.out.println("Faculty added!");
PersonList.addPerson(f);
}
When you read the selection input = sc.nextInt() it returns the next integer it finds, stopping right after that. It returns the choice typed but it does not read the newline. If you typed 1 (space one space) it would skip over the leading space then read the 1 and stop; it would not read the following space or the newline.
So when you get to the faculty name f.name = sc.nextLine() it reads whatever was remaining from the input = line, which is probably just a newline, and returns that for the name.
Now when you get to f.ID = sc.nextLine() the input buffer is clear so it reads ID as you expect it to.
A simple solution is to just finish reading the line by adding a nextLine() after reading the selection:
System.out.print("\tEnter a selection: ");
input = sc.nextInt();
sc.nextLine(); // Read the remainder of the line and throw it away
Read the javadoc for java.util.Scanner and for nextInt() and nextInt(radix)

Java program that asks for user's name and prints it - issue with error message

I have a program that asks for the user's name and prints it back out. It can do that part fine, but it currently has the issue of not printing the proper error message when the user leaves the prompt empty and presses "Enter".
The code:
//Get User Input
Scanner sc = new Scanner(System.in);
System.out.println("What is your name?");
while (sc.hasNext()) {
//User Input Variable
String name = sc.nextLine();
if (name == null || name.trim().isEmpty()) {
//Error for empty input, keep asking for valid input
System.out.print("Please, what is your name?\n");
sc.next();
} else {
//Print name
System.out.println("Hello " + name + "!");
break;
}//End of conditional
}//End of while loop
The current output:
What is your name?
<blank space for input>
<Empty Space where error message should be>
The ideal output:
What is your name?
<blank space>
Please, what is your name?
What's wrong?
The only thing that you need to change is your condition in the while statement.
Please use sc.hasNextLine() insted of sc.hasNext(). Then you will get desired output. Here is the working soltion:
// Get User Input
Scanner sc = new Scanner(System.in);
System.out.println("What is your name?");
while (sc.hasNextLine()) { // here is the difference in the code
// User Input Variable
String name = sc.nextLine();
if (name == null || name.trim().isEmpty()) {
// Error for empty input, keep asking for valid input
System.out.print("Please, what is your name?\n");
sc.hasNextLine(); // here is the difference in the code
} else {
// Print name
System.out.println("Hello " + name + "!");
break;
} // End of conditional
} // End of while loop
Scanner sc = new Scanner(System.in);
System.out.print("ENTER YOUR USERNAME : ");
String name = sc.nextLine();
while(name.equals("") || name.trim().isEmpty()) {
System.out.print("PLEASE ENTER YOUR USERNAME AGAIN : ");
name = sc.nextLine();
}
System.out.println("WELCOME " + name);

How do I prevent an error message from repeating in Java?

I'm trying to write a program to calculate factorial but I can't figure out why the Error message displays twice if I enter a letter instead of an integer.
I feel like the issue has to do with Line 29 c = sc.next().charAt(0);, but am not sure how to fix it. Any help is appreciated.
My program:
public class Factorials {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char c = 'Y';
int num = 0;
do
{
System.out.print("Enter a number to calculate its factorial: ");
while (!sc.hasNextInt()) {
System.out.println("Invalid Entry - Enter only Integers! Try Again: ");
sc.nextLine();
}
int result = 1;
num = sc.nextInt();
for(int i = 1; i <= num; i++) {
result = result * i;
}
System.out.println("The factorial of " + num + " is: " + result);
System.out.println("Do you wish to continue? Y/N: ");
c = sc.next().charAt(0);
}while(c == 'y' || c == 'Y');
sc.close();
}
}
Simple fix: Change the sc.nextLine(); in your code to a sc.next() and you should be good to go. This error occurs because .nextLine() considers the enter/return key as a separate character, while .next() doesn't. (The enter key when you press it after entering either 'y' or 'n': if you try it, the error message doesn't print twice if you enter a letter the first time you run the program).
Side note: You probably want it to be a .print(/*invalid input sentence*/) instead of a .println() to go along with how you take in your other number values.
Otherwise, you're good!
Finds and returns the next complete token from this scanner.
A complete token is preceded and followed by input that matches
the delimiter pattern
As jdk doc shows, the 'sc.next' method will return when it reaches space, enter or return. So when you enter 'y' with enter, the enter character is still in buffer. You can assign sc.nextLine to a variable, like
String str = sc.nextLine();
System.out.println(str);
You can see the enter character and your input character.
Both #TheSj and #Lahiru Danushka answer could solve this problem.
add sc.nextLine(); after c = sc.next().charAt(0);

Getting length of names in Java with nextLine()

I am very new to Java. I'm in my first Java class and we are just working on the basics. I am supposed to write a program that prompts the user to enter their first, middle, and last name with spaces. Then display the length of the first name, the length of the middle name, the initials, and the full name in all upper case. Here is the class example
Example Output:
Enter a first name middle name and surname
Peggy Sue Palmer
Length of your name: 16 characters
Length of your middle name: 3 characters
Your initials are PSP
PEGGY SUE PALMER
I have worked on some code so far and I am able to get some of the output correctly but when I go to enter Peggy Sue Palmer I have to input the name one at a time with a space at the end and then press enter to input the next name. Also it displays the length of the middle initial as 4 instead of 3. I know that I can have the input all on one line by just having one input String name = input.nextLine(), which allows the input format I am looking for but if I do that I have no clue how to get the length of the middle name or the initials. Sorry this is a dumb question but this is my first Java class and we are just learning the basics.
package tracy2prog1;
import java.util.Scanner;
public class Tracy2prog1 {
public static void main(String[] args) {
//create new scanner class
Scanner input = new Scanner(System.in);
//prompt user to enter first middle and last name
System.out.println("Please enter your first middle and last name with spaces between them");
String firstname = input.nextLine();
String middlename = input.nextLine();
String lastname = input.nextLine();
System.out.println(firstname.length() + middlename.length() + lastname.length());
System.out.println("The length of your middle name is " + middlename.length() + " characters");
System.out.println("Your initials are " + firstname.charAt(0) + middlename.charAt(0) +lastname.charAt(0));
System.out.println(firstname.toUpperCase() + middlename.toUpperCase() + lastname.toUpperCase());
}
}
Here is the updated code that works, only issue is its not counting the spaces in the output of the full name to 16, I am getting 14.
package tracy2prog2;
import java.util.Scanner;
public class Tracy2prog2 {
public static void main(String[] args) {
//create new scanner class
Scanner input = new Scanner(System.in);
//prompt user to enter first middle and last name
System.out.println("Please enter your first middle and last name with spaces between them");
String firstname = input.next();
String middlename = input.next();
String lastname = input.next();
System.out.print("Your name is ");
System.out.println(firstname.length() + middlename.length() + lastname.length() + " characters");
System.out.println("The length of your middle name is " + middlename.length() + " characters");
System.out.println("Your initials are " + firstname.charAt(0) + middlename.charAt(0) +lastname.charAt(0));
System.out.println(firstname.toUpperCase() + " " + middlename.toUpperCase() + " " + lastname.toUpperCase());
}
}
I have to input the name one at a time with a space at the end and then press enter to input the next name.
Let's look at how you get the name:
String firstname = input.nextLine();
String middlename = input.nextLine();
String lastname = input.nextLine();
You are reading three separate lines here which is why you have to press enter between each part of the name. Instead you should read the entire name at once:
String name = input.nextLine();
Now you need to parse the name into separate pieces. I'll leave this for you to figure out how to do. You should look at the documentation of the String class to find any functions which might be helpful to finish solving the problem.
Take a look at how you can do it (one of many examples) - Maybe this will help you in the future, as you probably don't know arrays yet (I didn't know you were in your first class, I went to the problem before reading all - don't do that by the way, sorry!)
import java.util.Scanner;
public class Tracy2prog1 {
public static void main(String[] args) {
//create new scanner class
Scanner input = new Scanner(System.in);
//prompt user to enter first middle and last name
System.out.println("Please enter your first middle and last name with spaces between them");
//Here you will have your names without " ", then its length is 2 characters shorter
String[] names = input.nextLine().split(" ");
//As your names are in an array now, you can get then directly
System.out.println(names[0].length() + names[1].length() + names[2].length());
System.out.println("The length of your middle name is " + names[1].length() + " characters");
System.out.println("Your initials are " + names[0].charAt(0) + names[1].charAt(0) +names[2].charAt(0));
System.out.println(names[0].toUpperCase() + " " + names[1].toUpperCase() + " " + names[2].toUpperCase());
//Peggy Sue Palmer
//Considering you did this: String[] names = input.nextLine().split(" ");
//your array is ["Peggy", "Sue", "Palmer"]
//then array[0] is "Peggy"
//then "Peggy".length == 5
//plus: names[0].charAt(0) means "Peggy".charAt(0) which is "P"
System.out.println("The length of your first name is " + names[0].length() + " characters");
System.out.println("The initial of your first name is " + names[0].charAt(0));
}
}

Loop not executing more than once

I'm supposed to make a program that continuously accepts desk order data and displays all the relevant information for oak desks that are over 36 inches long and have at least one drawer.
import java.util.*;
public class MangMaxB
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
char ans;
int orderNum=0, length=0, width=0, numDrawer=0, price=1000;
String name;
System.out.print("Do you wish to enter Oak " +
"desk order data? (y/n)");
ans = input.nextLine().charAt(0);
while (ans != 'n')
{
System.out.print("Enter customer name: ");
name=input.nextLine();
System.out.print("Enter order number: ");
orderNum=input.nextInt();
System.out.print("Enter length and width of Oak desk" +
" separated by a space: ");
length = input.nextInt();
width = input.nextInt();
System.out.print("Enter number of drawer/s: ");
numDrawer=input.nextInt();
if ((length>36)&&(numDrawer>=1))
{
if ((length*width)>750)
{
price+= 250;
}
price+= (numDrawer*100);
price+= 300;
System.out.println("\nOak desk order information:\n"
+ "Order number: " + orderNum + "\n"
+ "Customer name: " + name + "\n"
+ "Length: " + length + ", width: "
+ width + ", surface: " + (length*width)
+ "\n" + "Number of drawer/s: " + numDrawer
+ "\nPrice of the desk is P " + price);
}
else
{
System.out.println("\nOak desk order isn't over 36 " +
"inches long and doesn't have a drawer");
}
System.out.print("Any more items? (y/n) ");
ans = input.nextLine().charAt(0);
}
}
}
I was able to enter data and display it but on the second attempt since it is a loop, it didn't work.
It says "Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at controlStruc.MangMaxB.main"
how do I fix this?
nextInt() doesn't read the end of the line - just the next integer. You need to call nextLine() after nextInt() if you want to read the remainder of that line.
At present, you're not doing so, so the last nextLine() method just reads the rest of the empty line after the integer, and returns immediately with an empty string, causing the exception.
In this case, putting a nextLine() call here should do the trick:
System.out.print("Enter number of drawer/s: ");
numDrawer=input.nextInt();
input.nextLine(); //Added nextLine() call
Please use like the below,
System.out.print("Any more items? (y/n) ");
input = new Scanner(System.in);
ans = input.nextLine().charAt(0);
beacuse input.nextLine() returns empty string, so when try to get 0th char it returns StringIndexOutOfBoundsException
You need to get a String before calling input.nextLine()
Are you just pressing enter?
ans = input.nextLine().charAt(0);
is throwing this error when it's an empty string. Your exception is clearly telling you this. You need to check if the "nextLine" is an empty string or not.
Clearly according to documentaion:
nextLine()-Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
nextInt()-Scans the next token of the input as an int.
And henceforth ans = input.nextLine() in your code is returning you with '' and char(0) leading for StringIndexOutOfBoundsException.

Categories

Resources