I am literally know and get the hang of the java right now and I'm writing the program that helps to records patient'd ID in the Hospital, i'll show the whole code first,then, I will tell where you will, here is the code
package hospitalsrecord;
import java.util.*;
import java.io.*;
public class HospitalsRecord {
public static Scanner read = new Scanner(System.in);
public static ArrayList nameList = new ArrayList();
public static ArrayList patientAge = new ArrayList();
public static ArrayList Disease = new ArrayList();
public static ArrayList dateHospitalized = new ArrayList();
public static ArrayList roomNumber = new ArrayList();
//adding patient function
public static void AddNewPatient () {
//Ask patient's name
System.out.println("Please enter patient's name:");
String patientName = read.next();
//Ask Patient's age
System.out.println("Please enter patient's age:");
int age = read.nextInt();
//Ask patient's illness
System.out.println("Please enter patient's Disease name (also include accidents eg. Leg broke by Car Accident):");
String illness = read.next();
//Ask patient Hospitalized date
System.out.println("Please enter patient's Hospitalized date(Total days not included):");
String HPTLdate = read.next();
//Ask patient's room number
System.out.println("Please enter patient's hospitalize room number(3 degits):");
int HRN = read.nextInt();
//Confirmation
System.out.println("Doctor, would you like to confirm the following(y/n)?");
System.out.println("Name:" + patientName);
System.out.println("Age:" + age);
System.out.println("Disease:" + illness);
System.out.println("Date Hospitalized (HPTLD):" + HPTLdate);
System.out.println("Room Number:" + HRN);
String Confirm = read.next();
if (Confirm.equals("y")) {
nameList.add(patientName);
patientAge.add(age);
Disease.add(illness);
dateHospitalized.add(HPTLdate);
roomNumber.add(HRN);
} else {
AddNewPatient();
}
}
//Searching patient that listed
public static void searchPatient (){
}
//remove the patient function
public static void removePatient() {
}
//text printing function when strat the program
public static void selectorPage(){
System.out.println("Hello Doctor, welcome to Hospital Recorder v1.0.0");
System.out.println("If you want to add new patient into this recorder type: 'add' in the next blank line line");
System.out.println("If you want to search the patient list type: 'search' in the next blank line");
System.out.println("And, if you want to remove the patient that was out of hospitalizing type: 'remove' in the next blank line");
option = read.next();
}
//text printing simmilar to selecterPage function but perform after function
public static void selecterPageAfterAction() {
System.out.println("Your action has been performed, doctor");
System.out.println("Would you like to perform another action?(y/n)");
choiceSelection = read.next();
if (choiceSelection.equals("y")){
System.out.println("If you want to add new patient into this recorder type: 'add' in the next blank line line");
System.out.println("If you want to search the patient list type: 'search' in the next blank line");
System.out.println("And, if you want to remove the patient that was out of hospitalizing type: 'remove' in the next blank line");
option = read.next();
}
}
//Selection var
public static String option;
public static String choiceSelection;
//Main program
public static void main(String[] args) {
selectorPage();
switch (option) {
case("add"): {
AddNewPatient();
break;
}
case("search"):{
searchPatient();
break;
}
case("remove"):{
removePatient();
break;
}
case("end"):{
break;
}
default: {
System.out.println("Please enter the indentified option");
break;
}
}
if (option.equalsIgnoreCase("end")){
}
}
}
I hope you guys can read every line because it was so so so so complex, but for someone who can read all of it, i'll know that you'll say I still need more time for hard working, no worry i'll spend sometime to get most knowledge from you guys first, but still working hard for program to complete while waiting for answers! anyway the point that I want you guys to focus at this point:
if (option.equalsIgnoreCase("end")){
}
It maybe too blank because I've just newly add it while i'm working on it. So, what I want to know is at the if statement I type option.equalsIgnoreCase("end"), Am I explain the computer to do the following?
1.Compare the the String variable options with the String"end"?
2.Tell the computer to do the action inside if statement's when the String option wasn't the word end?
And please tell me how this method work, i don't clearly understand it. I understand like this "It compare two strings if it wasn't the same then it's result is true" I know my explanation is wrong so could you please help me? thanks again for helping if you can.
option.equalsIgnoreCase("end") - equalsIgnoreCase will ignore whether string is in lower case or uppercase.
So it will enter into if block only when option variable has either end or END.
Your first assumption is correct, you are asking to compare String whether it is equal to end. But Second one is wrong, from above code it will enter and execute statements present inside if only when option is end/END.
If you want to go inside If block when the option is not end then add a not like this if(!option.equalsIgnoreCase("end")).
I Hope this clears your doubt!
The class String has two methods to compare one String to another.
See the example below:
public static void main(String[] args) {
String str1 = "beer";
String str2 = "Beer";
System.out.println(str1.equals(str2));
System.out.println(str1.equalsIgnoreCase(str2));
}
The first method equals() compares str1and str2and takes the case into consideration. Hence, the first comparison results in false, meaning Beer is not equal to beer.
The second method equalsIgnoreCase()does the same, except that it is not case-sensitive. Result of this comparison is true, meaning "ignoring the case, Beer is the same string as beer".
Hope this helps.
Related
I am currently creating a program where the user enters a specific set of questions. And the program must go back to the menu after completely answering all questions. How should I do it?
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("""
\n \nAre you ready to take the quiz?
Enter "Y" to proceed or "N" to exit the program:""");
String TakeQuiz = input.nextLine();
if (TakeQuiz.equalsIgnoreCase("Y"))
do {
//blocks of code
}
}
}
System.out.println("Do you want to take the quiz again?");
String RetakeQuiz = input.nextLine();
while (RetakeQuiz.equalsIgnoreCase("Y")) ;
else {
System.out.println("We hope to see you again soon!");
System.exit(0);
}
}
}
There are many ways to achieve what you want, I would not clutter the main method and break the code to another function and loop there.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
for(;;)
takeQuiz();
}
public static void takeQuiz(){
Scanner input = new Scanner(System.in);
System.out.print("\n \nAre you ready to take the quiz?" +
"Enter \"Y\" to proceed or \"N\" to exit the program:");
String takeQuiz = input.nextLine();
if (takeQuiz.equalsIgnoreCase("Y")) {
System.out.println("Running code...");
System.out.println("Question 1");
System.out.println("Question 2");
System.out.println("Question 3");
}
// retake
if (takeQuiz.equalsIgnoreCase("R")){
takeQuiz();
}
if (takeQuiz.equalsIgnoreCase("N")){
System.out.println("We hope to see you again soon!");
System.exit(0);
}
}
}
Notice the escape character for quotes \" and the + for multiline Strings
Java 15 and beyond allows triple quotes as Java Text Blocks
so your String message should be valid
The basic structure is something like this:
boolean continueWithQuiz = true;
while (continueWithQuiz) {
// Put the code here for handling the quiz
...
// Should we keep going?
System.out.println("Do you want to take the quiz again?");
String retakeQuiz = input.nextLine();
continueWithQuiz = retakeQuiz == "Y";
}
One more comment. Please follow Java naming standards. Class names begin with an upper case letter. Constants should be ALL_CAPS. Everything else is in lower case.
//my code is on java code on employ details using console
//my input is no.of employess
//i am taking input a employ details
//function on searching for a given employ for a given id
// code meaning
// #String employee[][]=new String[numberOfEmployees][12]; will store //employ details
//#String input will take the employee details in the string formatt.
//#String choice will take choice as yes to search the another employee
/ABOVE CODE IS ON DEVELOPING SIMPLE JAVA CODE ON EMPLOY MANAGEMENT SYSTEM/
import java.util.Scanner;
public class EmployeeManagement {
public static void main(String args[]){
Scanner read=new Scanner(System.in);
System.out.println("Enter the no.of employees");
int numberOfEmployees=read.nextInt();//GIVEN INPUT FOR NO.OF EMPLOYESS
int employeeId;
String employee[][]=new String[numberOfEmployees][12];
for(int inner=0;inner<numberOfEmployees;inner++){/*taken input on employ details*/
for(int outer=0;outer<11;outer++){
employee[inner][outer]=read.nextLine();
}
System.out.println();
}
for(int inner=0;inner<numberOfEmployees;inner++){
employee[inner][11] = (int)(Integer.parseInt(employee[inner][5])+Integer.parseInt(employee[inner][6])
+Integer.parseInt(employee[inner][7])+Integer.parseInt(employee[inner][8])
-Integer.parseInt(employee[inner][9])-Integer.parseInt(employee[inner][10]));
}
String choice;
do{
System.out.println("do you want to search enter employee id");
String input=read.nextLine();
System.out.println("do you want to continue press yes or YES");
read.nextLine();
choice =read.nextLine();
}while(choice=="yes" || choice=="YES");
for(int inner=0;inner<numberOfEmployees;inner++){
if(employee[inner][0]=="input"){
for(int outer=0;outer<12;outer++)
System.out.print(employee[inner][outer]);
}
System.out.println();
}
}
}
If you format the code in the question properly it will be easier to see what's going wrong. But to start with:
Don't compare Strings like this:
choice=="yes"
Then you just check if the first String object is the same object as the second one, and in this case they never are.
Instead, go like this:
choice.equals("yes")
Or better yet, since you never risk a NullPointerException:
"yes".equals(choice)
I want to validate the user input before the program continued. For example:
A variable String name. The program displays 'Enter name' and if the user types in a number instead of a String, a message should pop up and also make the user assign a String to name.
This is what I have so far:
System.out.println("Enter name");
String name = input.nextLine();
I tried try/catch but that did not work. I tried using
if(input.hasNextInt()){System.out.println("Type in a string!");}
but that carries on through the program and still assigns a number to 'name'. It does not give the user a second chance to assign a string to 'name'
Here is something to get you started using regular expression. It only checks for a String with characters between A-Z and a-z. See what happens when you try and enter "FirstName LastName" and see if you can figure out how to fix it.
Scanner input = new Scanner(System.in);
String name;
while(true){
System.out.println("Enter name");
name = input.nextLine();
if (name.matches("[A-Za-z]+")){
break;
}else{
System.out.println("Please enter only letters");
}
}
System.out.println("Name selected: "+name);
The plus sign at the end of the brackets checks to see if you have at least one character. So if you enter a blank name, it will go to the else.
The number checking can be achived fairly simple with the String matches() method. This method tells whether or not the string matches the given regular expression.
String name = "Shrek";
if (name.matches(".*\\d+.*")) {
// Do whatever you want to do if the name contains a number
}
Try this solution that validate the input with pop up, when user inputs something invalid.
public class Test {
static String name;
public static void main(String[] args) {
final JFrame parent = new JFrame();
parent.pack();
parent.setVisible(false);
name = JOptionPane.showInputDialog(parent,
"Enter name", null);
while (true) {
if (name.matches("[A-Za-z]+")) {
break;
} else {
name = JOptionPane.showInputDialog(parent,
"Please enter only letters", null);
if (name.matches("[A-Za-z]+"))
break;
}
}
System.out.println("Name selected: " + name);
}
}
public void addItem() {
System.out.println("Please type the item to add to the To-Do List");
System.out.println();
String newItem = inputread.next();
toDoList.add(newItem);
System.out.println("Your item has been added! Type any key and press Enter to continue");
String discardMe = inputread.next();
menu();
}
This is my code, I'm just learning Java and trying to made a little "To-Do List" type program. As it stands, I can only add one word at a time. If, for example, I type "Pick Up Milk", the arrayList only stores "Pick".
I tried using inputread.nextLine() above, but then I get an "InputMismatchException". Any advice? I'm sure it's something simple.
Edited to include the whole class, per request:
public class ToDo {
Scanner inputread = new Scanner(System.in);
ArrayList<String> toDoList = new ArrayList<String>();
public void menu() {
clearConsole();
System.out.println("Welcome to the To-Do program.");
System.out.println();
System.out.println();
System.out.println("Please select an option from the following menu, using the number.:");
System.out.println("1- View To-Do List");
System.out.println("2- Add Item To List");
System.out.println("3- Remove Item From List");
int userinput = inputread.nextInt();
switch (userinput) {
case 1:
clearConsole();
displayList();
System.out.println();
System.out.println("This is your list. Type any key and press Enter to continue");
String discardMe = inputread.next();
menu();
break;
case 2:
clearConsole();
addItem();
break;
case 3:
clearConsole();
deleteItem();
break;
}
}
public void clearConsole() {
for (int i = 0; i < 25; i++) {
System.out.println();
}
}
public void addItem() {
System.out.println("Please type the item to add to the To-Do List");
System.out.println();
String newItem = inputread.nextLine();
toDoList.add(newItem);
System.out.println("Your item has been added! Type any key and press Enter to continue");
String discardMe = inputread.next();
menu();
}
public void displayList() {
if (toDoList.isEmpty()) {
System.out.println("For [REDACTED]'s sake, add an activity.");
} else {
for (String listItem: toDoList) {
System.out.println(listItem);
}
}
}
public void deleteItem() {
System.out.println("Please choose the number of the line you want to delete:");
displayList();
int userinput = inputread.nextInt();
int listPos = userinput - 1;
toDoList.remove(listPos);
System.out.println("That item has been deleted. Type any key and press Enter to continue.");
String discardMe = inputread.next();
menu();
}
}
I would suggest using a BufferedReader instead of the Scanner class. The problem with a Scanner is that it looks for tokens between white spaces and new lines, so when you add something like Go to the store, each token between the white spaces will get picked up, and you will end up with go to the store, rather than 1 large token. You can get input using the BufferedReader by declaring it using:
public static BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
Then, in your addItem() method, in a while(true) loop, you read the input from the reader, then check if it is empty or not. IF it is empty, then you break the loop and exit the function, otherwise add an item to your list.
System.out.println("Please type the item to add to the To-Do List"); // Output
while (true) { // Continue adding items until user just hits enter
String newItem = buf.readLine(); // read user input
if (newItem == null || newItem.isEmpty()) { // check if the user entered anything, or just hit enter
break; // If they didn't enter anything, then break the loop and drop out of the function
}
toDoList.add(newItem); // if they did enter something, add it to your to-do list
}
For example, to test this I used a main method:
public static BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException {
List<String> toDoList = new ArrayList<String>();
System.out.println("Please type the item to add to the To-Do List");
while (true) {
String newItem = buf.readLine();
if (newItem == null || newItem.isEmpty()) {
break;
}
toDoList.add(newItem);
}
System.out.println("Your item has been added! Type any key and press Enter to continue");
for (String s : toDoList) {
System.out.println(s);
}
}
Then, when prompted for input I entered:
Please type the item to add to the To-Do List
Go to the grocery store and get milk
Stop by the gym and pay membership fees
Pick up flowers for the wife
And for output I got:
Your item has been added! Type any key and press Enter to continue
Go to the grocery store and get milk
Stop by the gym and pay membership fees
Pick up flowers for the wife
You have several problems in this code.
Let's first address your input issues.
In the menu, you read a number. When you use scanner.next(), scanner.nextInt() etc., it reads the following item up to - but not including - any white space or newline. So the white space or newline remain in the buffer waiting to be read.
Now, when you go to the addItem() and use nextLine(), it reads just that whitespace or newline. If it was just a newline (a Return you pressed), then you get an empty string, and you probably don't want to add that to the list. If you use next() it will skip that newline but... it will read just one word.
So you need to have a nextLine() after your nextInt() in the menu. After you read your integer, you'll clear the buffer up to and including the newline.
Then, inside the addItem() method, you'll be able to use nextLine() again, because it will now start on a fresh new line - and it will read the next line in its entirety.
Also, the discardMe part has to be with nextLine(), not with next(), otherwise it will not clear the end-of-line for the next operation.
Your other problem is something you didn't ask about. What you currently do is basically go into the menu, then go into an operation, then go into the menu, then an operation. You keep calling more and more functions, and you never return, or rather, you return from all when you display the list.
In time, this may cause a stack overflow.
The proper way to do this is not to call menu() from inside the operational methods, but rather, to have a loop in the menu() method, which shows the menu, calls the appropriate operational method, and when it returns (clears its space on the stack), loops back to the menu and so on. This keeps your stack nice and flat.
And of course, you should have a "Quit" option on your menu.
an example for Stultuskes idea:
public void addItem() {
System.out.println("Please type the item to add to the To-Do List");
System.out.println();
try (Scanner in = new Scanner(System.in)) {
while (in.hasNext()) {
String newItem = in.next();
toDoList.add(newItem);
System.out
.println("Your item has been added! Type any key and press Enter to continue");
}
}
System.out.println(toDoList);
}
public void addItem() {
System.out.println("Please type the item to add to the To-Do List");
//The skip gets over the leftover newline character
inputread.skip("\n");
String newItem = inputread.nextLine();
toDoList.add(newItem);
System.out.println("Your item has been added! Type any key and press Enter to continue");
String discardMe = inputread.next();
menu();
}
Putting in the skip fixed it for me. I want to thank you guys for your answers.
I have to use a loop in my code so that when someone enters yes, they can re-enter their names as many times as they want, but I have no idea how to do this. Any help is appreciated, here is my code:
public static void main(String [] args)
{
// Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);
//Get the user's name.
System.out.print("What is your name?");
String name = keyboard.nextLine();
System.out.println("Hello there," + name);
System.out.println("Would you like to enter another name? Please enter Yes Or No.");
String reply = keyboard.nextLine();
if (reply == "yes")
{
}
}
}
This reply == "yes" is not how you compare Strings in Java. This compares there memory locations, not there contents (and it's unlikely there memory locations are going to be equal).
Instead you need to use reply.equals("yes") or if you don't care about doing a case comparison, you can use reply.equalsIgnoreCase("yes") instead
do {
// The remainder of your code...
} while (reply.equalsIgnoreCase("yes"));
Updated
You may also wish to have a read through The while and do-while statements and The for Statement, which covers the basics of looping in Java
Use a do-while loop:
public static void main(String[] args) {
// Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);
do {
//Get the user's name.
System.out.print("What is your name?");
String name = keyboard.nextLine();
System.out.println("Hello there," + name);
System.out.println("Would you like to enter another name? Please enter Yes Or No.");
} while (keyboard.nextLine().equalsIgnoreCase("yes"));
System.out.println("Bye!");
keyboard.close();
}
}
use this
import java.util.*;
public class prob13 {
public static void main(String [] args)
{
// Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);
//Get the user's name.
while(true){
System.out.print("What is your name?");
String name = keyboard.nextLine();
System.out.println("Hello there," + name);
System.out.println("Would you like to enter another name? Please enter Yes Or No.");
String reply = keyboard.nextLine();
if(reply.equals("no"))
break;
}
}
}
The reason for this is to loop through as long as the answer is not no.
or you could use this if you want the answer to always be yes
import java.util.*;
public class prob13 {
public static void main(String [] args)
{
// Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);
String reply="yes";
//Get the user's name.
while(reply.equals("yes")){
System.out.print("What is your name?");
String name = keyboard.nextLine();
System.out.println("Hello there," + name);
System.out.println("Would you like to enter another name? Please enter Yes Or No.");
reply = keyboard.nextLine();
}
}
}
I think this will work (untested):
public static Scanner keyboard = new Scanner(System.in); // global
public static void main(String [] args)
{
getName();
}
public static void getName()
{
System.out.print("What is your name?");
String name = keyboard.nextLine();
System.out.println("Hello there," + name);
rerun();
}
public static void rerun()
{
System.out.println("Would you like to enter another name? Please enter \"yes\" or \"no\".");
String reply = keyboard.nextLine();
if (reply.equals("yes")) getName();
else System.exit();
}
}
First we call the getName() method and run through that once. Then we make a call to the rerun() method. This method will test if we want to re-run the program. If the user types in "yes", then we repeat the whole process. If we type in anything besides "yes", the program quits.
Besides the fact that your code is unfinished, the only real problem with your code is that you try to compare strings with the == operator. See MadProgrammer's answer as to why that is wrong.
The simplest (and probably clearest) way is to wrap what you want to repeat in a do-while statement:
public static void main(String [] args)
{
// Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);
String reply;
do {
//Get the user's name.
System.out.print("What is your name?");
String name = keyboard.nextLine();
System.out.println("Hello there," + name);
System.out.println("Would you like to enter another name? Please enter Yes Or No.");
reply = keyboard.nextLine();
} while ("yes".equals(reply));
}
}
The reply variable must be declared before the block, because it is accessed in the loop condition (a variable is only visible in the block it is declared in, so if reply were declared in the loop, it would not be available to the loop condition).
I changed the loop condition because the == operator compares Strings by reference, i.e. it will check whether both sides point to the same String object. The equals method, in contrast, checks that the content of the Strings is equal (i.e. they contain the same characters in the same order).