Creating a Basic Java phone book - java

I'm just learning Java and trying to make a simple phone book. For this part I'm trying to prompt the user to choose one of the 3 options below.
public class PhoneBook {
public static void main (String[] args){
options();
/*This method prompts the user to enter phone number
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter Phone Number");
s = in.nextLine();
System.out.println("You entered phone number ");
System.out.println(s);*/
}
public static void options (){
//This method gives the user choices on what to do
char choice;
char enterNumber = 'n';
char showNumber = 's';
char closeBook = 'c';
String read;
String freeLine = "error";
Scanner keyboard = new Scanner(System.in);
while (true){
System.out.println("Please select from the following");
System.out.println("n to Enter the number");
System.out.println("s to Show the number ");
System.out.println("c to Close the Phone book");
read = keyboard.nextLine();
choice = read.charAt(0);
switch (choice) {
case 'n': enterNumber;
system.out.println();
case 's':showNumber;
system.out.println();
case 'c': closeBook;
break;
default: System.out.println("Invalid Entry");
}
}
}
}
When I compile it i get errors on lines 37, 39, and 41 saying "Error: not a statement". I feel like something is missing. If anyone can help it would be greatly appreciated.

I am assuming that with the following lines you want to achieve to print the letter n for enterNumber in the console?
case 'n': enterNumber;
system.out.println();
This is not correct Java syntax. You will have to pass the variable value to the System.out.println method call:
case 'n': System.out.println(enterNumber);
Also note that Java is case sensitive, so you have to spell System with a capital letter.
On a side note, you will want to break; after each of your case statements, otherwise the code of the following cases will be executed as well:
switch (choice) {
case 'n': System.out.println(enterNumber);
break;
case 's': System.out.println(showNumber);
break;
case 'c': System.out.println(closeBook);
break;
default: System.out.println("Invalid Entry");
}

you do not have to write variable after 'cast' statement.
Refer below code.
import java.util.Scanner;
public class PhoneBook {
public static void main (String[] args){
options();
/*This method prompts the user to enter phone number
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter Phone Number");
s = in.nextLine();
System.out.println("You entered phone number ");
System.out.println(s);*/
}
public static void options (){
//This method gives the user choices on what to do
char choice;
char enterNumber = 'n';
char showNumber = 's';
char closeBook = 'c';
String read;
String freeLine = "error";
Scanner keyboard = new Scanner(System.in);
while (true){
System.out.println("Please select from the following");
System.out.println("n to Enter the number");
System.out.println("s to Show the number ");
System.out.println("c to Close the Phone book");
read = keyboard.nextLine();
choice = read.charAt(0);
switch (choice) {
case 'n':
System.out.println();
case 's':
System.out.println();
case 'c':
break;
default: System.out.println("Invalid Entry");
}
}
}
}

I have made a special answer for you. I don't add additional explanation. It's a large answer. I tell more than you ask, but I've done my best to make a readable code, so that you can analyse step-by-step to understand what you need at least when trying to make a Phone Book (console test drive application). If you need more explanation, write under comments.
First make a PhoneEntry class:
import java.util.Objects;
public class PhoneEntry implements Comparable<PhoneEntry> {
// https://jex.im/regulex/#!embed=false&flags=&re=%5E%5Ba-zA-Z%5D%7B2%2C%7D((-%7C%5Cs)%5Ba-zA-Z%5D%7B2%2C%7D)*%24
private static final String NAME_PATTERN = "^[a-zA-Z]{2,}((\\-|\\s)[a-zA-Z]{2,})*$";
// https://jex.im/regulex/#!embed=false&flags=&re=%5E%5C%2B%3F%5Cd%2B((%5Cs%7C%5C-)%3F%5Cd%2B)%2B%24
private static final String NUMBER_PATTERN = "^\\+?\\d+((\\s|\\-)?\\d+)+$"; //^\+?\d+((\s|\-)?\d+)+$
private final String name;
private final String number;
public PhoneEntry(String name, String number) {
if (!name.matches(NAME_PATTERN) || !number.matches(NUMBER_PATTERN)) {
throw new IllegalArgumentException();
}
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
public String getNumber() {
return number;
}
public boolean nameContainsIgnoreCase(String keyword) {
return (keyword != null)
? name.toLowerCase().contains(keyword.toLowerCase())
: true;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!(obj instanceof PhoneEntry)) {
return false;
}
PhoneEntry phoneEntry = (PhoneEntry) obj;
return name.equalsIgnoreCase(phoneEntry.name)
&& number.equalsIgnoreCase(phoneEntry.number);
}
#Override
public int hashCode() {
int hash = 5;
hash = 17 * hash + Objects.hashCode(this.name.toLowerCase());
hash = 17 * hash + Objects.hashCode(this.number.toLowerCase());
return hash;
}
#Override
public int compareTo(PhoneEntry phoneEntry) {
return name.compareToIgnoreCase(phoneEntry.name);
}
}
Then the test drive
public class TestDrive {
private static final String choices = "nspc";
enum Choice {
CREATE, READ, PRINT, CLOSE;
static Choice getChoice(char c) {
switch (c) {
case 'n':
return Choice.CREATE;
case 's':
return Choice.READ;
case 'p':
return Choice.PRINT;
case 'c':
return Choice.CLOSE;
}
return null;
}
}
// Main
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
final Set<PhoneEntry> entries = new TreeSet<>();
Choice choice;
while ((choice = getChoice(kbd)) != Choice.CLOSE) {
switch (choice) {
case CREATE:
PhoneEntry entry = getPhoneEntry(kbd);
if (entry != null) {
entries.add(entry);
}
break;
case READ:
print(readEntries(entries, kbd));
break;
case PRINT:
print(entries);
break;
}
}
}
private static Choice getChoice(Scanner kbd) {
System.out.println("\nPlease select from the following");
System.out.println("\tn to Enter the number");
System.out.println("\ts to Show numbers by keyword ");
System.out.println("\tp to Show all numbers ");
System.out.println("\tc to Close the Phone book");
System.out.print("> ");
String input = kbd.nextLine();
Choice choice = null;
if (!input.isEmpty()
&& choices.contains(input.toLowerCase())
&& ((choice = Choice.getChoice(input.toLowerCase().charAt(0))) != null)) {
return choice;
}
System.out.println("ERR: INVALID ENTRY. TRY AGAIN");
return getChoice(kbd);
}
private static PhoneEntry getPhoneEntry(Scanner kbd) {
System.out.print("Type contact name: ");
String name = kbd.nextLine();
System.out.print("Type phone number: ");
String number = kbd.nextLine();
try {
return new PhoneEntry(name, number);
} catch (IllegalArgumentException ex) {
System.out.println("\nERR: WRONG ENTRY");
}
return null;
}
private static void print(Set<PhoneEntry> entries) {
System.out.println("\nPHONE NUMBERS\n");
entries.stream().forEach(entry -> {
System.out.printf("Name: %s%nPhone: %s%n%n",
entry.getName(), entry.getNumber());
});
}
private static Set<PhoneEntry> readEntries(Set<PhoneEntry> entries, Scanner kbd) {
System.out.print("Type keyword: ");
return entries.stream().filter(entry
-> entry.nameContainsIgnoreCase(kbd.nextLine()))
.collect(Collectors.toCollection(TreeSet::new));
}
}

Instead of enterNumber;, you have to write enterNumber();.
The parentheses mean: Call the method.

Related

Java -how can I store an array in switch case

I need to build code that first gets a 2d array and then prints it.
for this, I built a menu with a switch case.
when the user clicks 0, the user types the size of the array (the size is always n*n), and then the user types the values. then I need to create a function that uses this info to build a char array.(the values is hex base 0-F)
when the user clicks 1, the code needs to print the same 2d array.
I have a difficult time understanding how I can move the array from case 0.
import java.util.Scanner;
public class Assignment3 {
static Scanner reader = new Scanner (System.in);
public static void main(String[] args) {
int checker=1;
int user_selction;
do {
user_selction=Menu();
switch(user_selction) {
case 0:
Menu_0(user_selction);
break;
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
checker=GoodBye(checker);
break;
default:
break;
}
}while(checker==1);
}
public static int Menu ()
{
int menu_num;
System.out.println("~ Photo Analyzed ~");
System.out.println("0. Load Photo");
System.out.println("1. Print Photo");
System.out.println("2. Circle Check");
System.out.println("3. Random Check");
System.out.println("4. Exit");
System.out.println("Please select an option>");
menu_num=reader.nextInt();
if(menu_num>4||menu_num<0)
{
System.out.println("Invalid input");
}
return menu_num;
}
public static int GoodBye(int GB)
{
GB=0;
System.out.println("Goodbye!");
return GB;
}
public static int Menu_0 (int a)
{
int Ps;
System.out.println("Please insert the photo size>");
Ps=reader.nextInt();
if(Ps<0||Ps>12)
{
System.out.println("Invalid Photo Input!");
return a;
}
System.out.println("Please insert the photo value>");
String strPhoto;
do {
strPhoto = reader.nextLine();
} while(strPhoto.length() == 0);
if(strPhoto.length()!=Ps*Ps)
{
System.out.println("Invalid Photo Input!");
return a;
}
for(int i=0;i<Ps*Ps;i++)
{
if(strPhoto.charAt(i)<'0'||strPhoto.charAt(i)>'F')
{
System.out.println("Invalid Photo Input!");
return a;
}
}
return a;
}
This is an example
import java.util.Scanner;
public class Assignment3 {
static Scanner reader = new Scanner (System.in);
public static void main(String[] args) {
int checker=1;
int user_selction;
char [][]array = null;
do {
user_selction=Menu();
switch(user_selction) {
case 0:
array = Menu_0();
break;
case 1:
print_array(array);
break;
case 2:
break;
case 3:
break;
case 4:
checker=GoodBye(checker);
break;
default:
break;
}
}while(checker==1);
}
public static int Menu ()
{
int menu_num;
System.out.println("~ Photo Analyzed ~");
System.out.println("0. Load Photo");
System.out.println("1. Print Photo");
System.out.println("2. Circle Check");
System.out.println("3. Random Check");
System.out.println("4. Exit");
System.out.println("Please select an option>");
menu_num=reader.nextInt();
if(menu_num>4||menu_num<0)
{
System.out.println("Invalid input");
}
return menu_num;
}
public static int GoodBye(int GB)
{
GB=0;
System.out.println("Goodbye!");
return GB;
}
public static char[][] Menu_0 ()
{
int Ps;
System.out.println("Please insert the photo size>");
Ps=reader.nextInt();
if(Ps<0||Ps>12)
{
System.out.println("Invalid Photo Input!");
return null;
}
System.out.println("Please insert the photo value>");
char [][]array = new char[Ps][Ps];
for(int i=0;i<Ps;i++)
{
for (int j = 0 ; j < Ps ; j++)
{
char c = reader.next().charAt(0);
if(c<'0'||c>'F')
{
System.out.println("Invalid Photo Input!");
return null;
} else {
array[i][j] = c;
}
}
}
return array;
}
public static void print_array(char [][]array){
for (int i = 0 ; i < array[0].length ; i++)
{
for (int j = 0 ; j < array[0].length ; j++)
{
System.out.print(array[i][j] + " ");
}
System.out.println();
}
}
}
Use Scanner like this:
Scanner sc = new Scanner(System.in);
System.out.println("Select 1 to input array size or 2 to do sth");
int option = sc.nextInt();
switch(option) {
case 1 :
Scanner sc = new Scanner(System.in);
System.out.println("Enter array size: ");
int size = sc.nextInt()
int[] array = new array[size*size];
break;
case 2 :
something;
break;
default:
System.out.println("No such option ");
break;
}

How to automatically return to main menu without user input?

The "main menu" is the place where System.out.print("enter letter P T L S A or Q");. When the user has entered his/her surname, the console should automatically return to the first System.out.print statement i.e the menu. How do I set it up to be like that?
class myOwnTryAginLoopThatWorks{
public static void main (String [] args){
Scanner console = new Scanner(System.in);
boolean valid;
char choice = '\0';
String persnr;
do{
valid = true;
System.out.print("enter letter P T L S A or Q"); //menu
String input = console.nextLine();
if (!isValid(input)){
valid = false;
System.out.print("You did not enter the correct menu option, ");
if (input.length() != 1) {
System.out.println("and your input length is too long (must be 1 character long), ");
valid = false;
}
}
choice = input.charAt(0);
}while(!valid);
switch (choice) {
case 'P':
do {
valid = true;
System.out.print("Enter persnr in the format of (YYYYMMDD): ");
try {
persnr = console.nextLine();
if (!persnr.matches("[1-9]{1}[0-9]{7}")) {
throw new IllegalArgumentException("You printed wrong format, try again");
}
System.out.println("Processsing...");
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
valid = false;
}
} while (!valid);
break;
}
System.out.print("enter first name ");
String firstName = console.nextLine();
System.out.print("enter surrname ");
String surName = console.nextLine();
}
public static boolean isValid (String n){
switch(n){
case "P":
case "T":
case "L":
case "S":
case "A":
case "Q":
return true;
default:
return false;
}
}
}
You MUST ask the question better. As I understand it, you need your menu is shown again asking to enter another data.
private static boolean exit = false;
public static void main(String[] args) {
while (exit == false){
readValues();
}
}
private static boolean isValid(String n) {
switch (n) {
case "P":
case "T":
case "L":
case "S":
case "A":
case "Q":
return true;
default:
return false;
}
}
private static void readValues() {
Scanner console = new Scanner(System.in);
boolean valid;
char choice = '\0';
String persnr;
do {
valid = true;
System.out.print("enter letter P T L S A or Q"); //menu
String input = console.nextLine();
if (!isValid(input)) {
valid = false;
System.out.print("You did not enter the correct menu option, ");
if (input.length() != 1) {
System.out.println("and your input length is too long (must be 1 character long), ");
valid = false;
}
}
choice = input.charAt(0);
} while (!valid);
switch (choice) {
case 'P':
do {
valid = true;
System.out.print("Enter DATE in the format of (YYYYMMDD): ");
try {
persnr = console.nextLine();
if (!persnr.matches("[1-9]{1}[0-9]{7}")) {
throw new IllegalArgumentException("You printed wrong format, try again");
}
System.out.println("Processsing...");
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
valid = false;
}
} while (!valid);
break;
}
System.out.print("enter first name ");
String firstName = console.nextLine();
System.out.print("enter surrname ");
String surName = console.nextLine();
String query = " insert into Person (PNr, FName, ENamn)"
+ " values (persnr, firstName, surName)";
}

Professor gets a java.io.FileNotFoundException but I don't?

I had a project for my Java class where the user enters patients for a hospital then the program reads a file and the user can choose to amend their added patients to the file, print it out to the screen, or both. The program works perfectly in NetBeans for me but in the professor's comments, he says his compiler got a FileNotFoundException(Edit: It is actually a runtime error), even though I included the file in the package. When I emailed him, he only repeated that he received a FileNotFoundException.
Here is the code:
package realworldproblem3;
import java.util.*;
import java.io.*;
public class xyzHospital {
static int numOfPat;
static Scanner input = new Scanner(System.in);
static String inp;
static ArrayList<Patient> p = new ArrayList<>();
public static void main(String[] args) throws IOException {
boolean done = false;
importPatients();
System.out.print("Add new patients to the report:\n");
while (done == false){
addPatient();
System.out.print("Are you done adding patients? (Y or N)\n");
inp = input.nextLine();
switch (inp.toLowerCase()){
case "y": done = true;
break;
case "n": done = false;
break;
default: System.out.print("You did not enter a valid character. The program will print results then exit.\n\n");
done = true;
break;
}
}
printAll();
}
static public void addPatient(){
numOfPat++;
Patient pat = new Patient();
p.add(pat);
pat.addInfo(numOfPat);
}
static public void printAll() throws IOException{
System.out.print("Do you want to output the report to the screen ('S'), to a file ('F'), or both('B')?\n");
inp = input.next();
PrintWriter writer = new PrintWriter("XYZHospitalExampleData-1.txt");
switch (inp.toLowerCase()){
case "s":
System.out.print("\t\t\t\t\tXYZ Community Hospital\t\t\n=============================================================================================================\n");
System.out.printf("%-14s%30s%38s%n", " Name", "Address", "Payment Information");
System.out.printf("%-8s%-8s%15s%10s%10s%8s%15s%15s%15s %n", "Last", "First", "Address Line 1", "City", "State", "Zip", "Payment Date", "Payment Amt.","Amount Owed");
System.out.print("=============================================================================================================\n");
for(int i = 0; i<numOfPat;i++){
p.get(i).print();
}
break;
case "f":
writer.print(""); //writes over file so there is no duplicate patients
writer.close();
for(int i = 0; i<numOfPat;i++){
p.get(i).printToFile();
}
break;
case "b":
System.out.print("\t\t\t\t\tXYZ Community Hospital\t\t\n=============================================================================================================\n");
System.out.printf("%-14s%30s%38s%n", " Name", "Address", "Payment Information");
System.out.printf("%-8s%-8s%15s%10s%10s%8s%15s%15s%15s %n", "Last", "First", "Address Line 1", "City", "State", "Zip", "Payment Date", "Payment Amt.","Amount Owed");
System.out.print("=============================================================================================================\n");
writer.print("");
writer.close();
for(int i = 0; i<numOfPat;i++){
p.get(i).printToFile();
p.get(i).print();
}
break;
}
}
//each patient from the file is added as a patient object
static public void importPatients() throws IOException{
try(Scanner read = new Scanner(new BufferedReader(new FileReader("XYZHospitalExampleData-1.txt")))) {
while(read.hasNextLine()){ //one more line means that there is another patient to add
numOfPat++;
read.nextLine();
}
read.close();
try(Scanner r = new Scanner(new BufferedReader(new FileReader("XYZHospitalExampleData-1.txt")))) {
for (int j=0; j < numOfPat; j++){
String line = r.nextLine();
Patient pat = new Patient();
p.add(pat);
String[] str = line.split("\\^"); //the delimiter ^ is used to separate information in the file
for (int i = 0; i < str.length; i++){
if(str[i].isEmpty()||str[i].matches("0")||str[i] == null){ //if str[i] is empty, that means that it will be skipped over
i++;
}
switch (i){
case 0: p.get(j).ID = Integer.parseInt(str[i]);
break;
case 1: p.get(j).nameLast = str[i];
break;
case 2: p.get(j).nameFirst = str[i];
break;
case 3: p.get(j).address = str[i];
break;
case 4: p.get(j).opAddr = str[i];
break;
case 5: p.get(j).city = str[i];
break;
case 6: p.get(j).state = str[i];
break;
case 7: p.get(j).zip = Integer.parseInt(str[i]);
break;
case 8: p.get(j).optZip = Integer.parseInt(str[i]);
break;
case 9: p.get(j).payDate = str[i];
break;
case 10: p.get(j).payment = Double.parseDouble(str[i]);
break;
case 11: p.get(j).owed = Double.parseDouble(str[i]);
break;
default: System.out.print("Error.\n");
break;
}
}
}
r.close();
}
}
}
}
Here is the patient class:
package realworldproblem3;
import java.util.*;
import java.io.*;
public class Patient {
Scanner input = new Scanner(System.in);
String nameFirst, nameLast, address, opAddr,city, state, payDate;
int zip, optZip, ID;
double owed, payment;
public void print() {
System.out.printf("%-8s%-9s%-20s%-10s%-8s%-7s%-15s%-11.2f%-10.2f%n", nameLast, nameFirst, address, city, state, zip, payDate, owed, payment);
}
public void printToFile()throws IOException{
try (PrintWriter writer = new PrintWriter(new FileWriter("XYZHospitalExampleData-1.txt", true))) {
writer.write(ID + "^" + nameLast+ "^" + nameFirst + "^" + address + "^" + opAddr + "^" + city + "^" + state + "^" + zip + "^" + optZip + "^"+ payDate + "^" + payment + "^" + owed +"\n");
writer.close();
}
}
private void setName(){
System.out.print("Enter patient's first name.\n"); //user is asked for all information
nameFirst = input.nextLine(); //first three inputs use nextLine so it consumes the end of line character, so the address will be put in the string correctly.
System.out.print("Enter patient's last name.\n"); //if next() is used, the address is cut off at the first whitespace and the other elements of the address
nameLast = input.nextLine(); //are stored in the upcoming inputs.
if (nameFirst.isEmpty()||nameLast.isEmpty()){
System.out.print("You must enter the first and last name.\n");
setName();
}
}
public String getName(){
return nameFirst + " " + nameLast;
}
private void setAddr(){
System.out.print("Enter patient's address.\n");
address = input.nextLine();
if (address.isEmpty()){
System.out.print("You must enter the patients address.\n");
setAddr();
}
}
public String getAddr(){
return address;
}
private void setCity(){
System.out.print("Enter patient's home city.\n");
city = input.nextLine();
if(city.isEmpty()){
System.out.print("You must enter the patients city.\n");
setCity();
}
}
public String getCity(){
return city;
}
private void setState(){
System.out.print("Enter patient's state.\n");
state = input.nextLine();
if(state.isEmpty()){
System.out.print("You must enter the patients state.\n");
setState();
}
}
public String getState(){
return state;
}
private void setDate(){
System.out.print("Enter the payment date.\n");
payDate = input.next();
if(payDate.isEmpty()){
System.out.print("You must enter a payment date.\n");
setDate();
}
}
public String getDate(){
return payDate;
}
private void setZip(){
System.out.print("Enter patient's zipcode.\n");
try{
zip = input.nextInt();
}
catch(Exception e){
System.out.print("You must enter a valid 5-digit zipcode.\n");
input.next();
setZip(); //if it says that the setZip call will make the function loop infinitely, it is just a warning, it will not loop infinitely.
}
int length = String.valueOf(zip).length();
if(length != 5 && zip > 0){
System.out.print("You must enter a valid 5-digit zipcode.\n");
setZip();
}
}
public int getZip(){
return zip;
}
private void setOwed(){
System.out.print("Enter patient's due balance.\n");
try{
owed = input.nextDouble();
}
catch(Exception e){
System.out.print("Amount has to be a non-negative number.\n");
input.next();
setOwed();
}
int length = String.valueOf(owed).length();
if (owed <0 || length == 0){
System.out.print("Amount has to be a non-negative number.\n");
setOwed();
}
}
public double getOwed(){
return owed;
}
private void setPayment(){
System.out.print("Enter patient's payment amount.\n");
try{
payment = input.nextDouble();
}
catch(Exception e){
System.out.print("Payment amount has to be a positive number less than the amount owed.\n");
input.next();
setPayment();
}
int length = String.valueOf(payment).length();
if(payment < 0 || length ==0 || payment > owed){
System.out.print("Payment amount has to be a positive number less than the amount owed.\n");
setPayment();
}
}
public double getPayment(){
return payment;
}
private void setID(int Id){
ID = Id;
}
public int getID(){
return ID;
}
public void addInfo(int ID){
setID(ID);
setName();
setAddr();
setCity();
setState();
setZip();
setOwed();
setPayment();
setDate();
}
}
And here is the file XYZHospitalExampleData-1.txt:
12345^Jones^John^1234 Test Drive^PO box 123^Test City^IN^11234^1234^12/05/2015^250.0^25000.0
12346^Jones^Sara^1234 Test Drive^PO box 123^Test City^IN^11234^1234^12/20/2017^50.0^50000.0
12347^Doe^John^1235 XYZ Drive^null^Test City^IN^11234^0^01/05/2016^350.0^56799.0
12348^Doe^Sara^1235 XYZ Drive^null^Test City^IN^11234^0^11/09/2017^100.0^5020.52
12349^Lawson^Lonnie^12 South Drive^null^Test City^IN^11236^0^03/15/2013^253.51^25065.52
12349^Anderson^Sara^156 North Avenue^null^Test City^IN^11246^0^05/05/2013^21.33^251.56
12350^Smith^Andy^2455 East Street^null^Test City^IN^11246^0^12/05/2017^365.21^2543.33
It starts with their ID and ends with the amount that they owe. Any help to understand why my professor's compiler is giving him an error would be appreciated, and what I can do to be sure that it will be able to find the file so I do not have this problem again.
In the beginning of your main method you call importPatients which reads data from the XYZHospitalExampleData-1.txt file. If this file is not present, you'll get an exception (in the runtime, not a compiler error).
Most probably something went wrong when your package was unpackaged. Maybe the file was not copied to the expected location, something like that. One of the ways to address this would be to catch the FileNotFoundException and to display a message describing what went wrong and what is expected.

Validate the input using a while loop

I doing a little practice on Computer Science because when I leave the military I want to start taking classes on the basics of java. I'm a little stuck on this question i was wondering if i can get some assistance.
a program that allows the user to enter a character. The only valid values are 'A', 'M', and 'S'. Validate the input using a while loop so that if the user enters any value other than one of those 3 characters, an error message is displayed and the user is prompted for another value. Once the user has finally entered valid data, print the character they entered back to the screen.
You can look into this basic example
import java.util.Scanner;
public class Read {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
boolean isCheck = true;
while (isCheck) {
String str = sc.next();
switch (str) {
case "A":
System.out.println("A");
isCheck = false;
break;
case "M":
System.out.println("M");
isCheck = false;
break;
case "S":
System.out.println("S");
isCheck = false;
break;
default:
System.out.println("Not Valid : Enter next");
isCheck = true;
}
}
}
}
Reading you input within the loop will enforce repetitive reading of input.
public class Read {
public static void main(String[] args) {
boolean isCheck = true;
while(isCheck){
Scanner sc = new Scanner(System.in);
String str = sc.next();
switch (str) {
case "A":
System.out.println("A");
isCheck = false;
break;
case "M":
System.out.println("M");
isCheck = false;
break;
case "S":
System.out.println("S");
isCheck = false;
break;
default:
System.out.println("Not Valid : Enter next.");
isCheck = true;
}
}
}
}

Code efficiency. Effective way of using loops

I am building a framework for a web application and would like to perform certain simple tasks like input retrieval and displaying them. Below is have the code, I feel the code can be improved and isn't efficient. Note:All three methods have the same implementation.
The Switch needs to be implemented twice one within the IF loop and the other for general case.
public class selector8
{
public static void main (String [] args){
selector8 obj1 = new selector8();
Scanner inputString = new Scanner (System.in);
Scanner inputYN = new Scanner (System.in);
String input, A,B,C;
System.out.println("Choose. A || B || C || X to exit");
input = inputString.nextLine();
char contLoop1 = 'y';
do{
if(input.equalsIgnoreCase("y")) {
input = "";
System.out.println("Choose. A || B || C || X to exit");
input = inputString.nextLine();
switch (input){
case("a"):
obj1.startMethod1(input);
break;
case("b"):
obj1.startMethod2(input);
break;
case("c"):
obj1.startMethod3(input);
break;
case("x"):
System.out.println("Goodbye");
break;
case ("n"):
System.out.println("See ya");
break;
default:
System.out.println("Invalid argument. Try again");
break;
}
} else
switch (input){
case("a"):
obj1.startMethod1(input);
break;
case("b"):
obj1.startMethod2(input);
break;
case("c"):
obj1.startMethod3(input);
break;
case("x"):
System.out.println("Goodbye");
break;
case ("n"):
System.out.println("See ya");
break;
default:
System.out.println("Invalid argument. Try again");
break;
}
System.out.println("Do want to try again " +"Y/N" );
input = inputYN.nextLine();
contLoop1 = input.charAt(0);
}while(contLoop1 != 'n');
}
public void startMethod1(String A){
String input;
Scanner inputString = new Scanner (System.in);
System.out.println("Enter a or b");
input = inputString.nextLine();
switch (input){
case("a"):
System.out.println("output parsed");
break;
case("b"):
System.out.println("output parsed");
break;
default:
System.out.println("Invalid argument");
}
}
public void startMethod2(String B){
String input;
Scanner inputString = new Scanner (System.in);
System.out.println("Enter a or b");
input = inputString.nextLine();
switch (input){
case("a"):
System.out.println("output parsed");
break;
case("b"):
System.out.println("output parsed");
break;
default:
System.out.println("Invalid argument");
break;
}
}
public void startMethod3(String C){
String input;
Scanner inputString = new Scanner (System.in);
System.out.println("Enter a or b");
input = inputString.nextLine();
switch (input){
case("a"):
System.out.println("output parsed");
break;
case("b"):
System.out.println("output parsed");
break;
default:
System.out.println("Invalid argument");
}
}
}
On a side note could you also tell me why can static classes be called without an object?
public class StaticImplementation{
public static void main (String [] args){
StaticImplementation obj1 = new StaticImplementation();
obj1.stat(); //is invalid
stat(); //is valid
}
static void stat(){
System.out.println("Static class");
}
Thanks a bunch. Have a good day!
using Java you'd probably take a more "Object Oriented" approach and leave those switches to C programming :)
do something like:
interface Action {
void start();
}
class Jumper implements Action {
public void start() {
System.out.println("Jump!");
}
}
class Sitter implements Action {
public void start() {
System.out.println("Sit!");
}
}
class Runner implements Action {
public void start() {
System.out.println("Run!");
}
}
class Test {
public static void main(String[] args) {
// init phase
Map<String, Action> map = new HashMap<String, Action>();
map.put("a", new Jumper());
map.put("b", new Runner());
// usage
map.get("a").start();
}
}
you can have two Maps one for Y and the other for the rest, you can also have a key composed from the two strings Pair
Oh yes, it can. You don't need two scanners, and I would extract your switch into a method (let's call it startMethods) like so -
private static void startMethods(selector8 obj1,
String input) {
switch (input) {
case ("a"):
obj1.startMethod1(input);
break;
case ("b"):
obj1.startMethod2(input);
break;
case ("c"):
obj1.startMethod3(input);
break;
case ("x"):
System.out.println("Goodbye");
break;
case ("n"):
System.out.println("See ya");
break;
default:
System.out.println("Invalid argument. Try again");
break;
}
}
public static void main(String[] args) {
selector8 obj1 = new selector8();
Scanner inputString = new Scanner(System.in);
String input, A, B, C;
System.out.println("Choose. A || B || C || X to exit");
input = inputString.nextLine();
char contLoop1 = 'y';
do {
if (input.equalsIgnoreCase("y")) {
input = "";
System.out.println("Choose. A || B || C || X to exit");
input = inputString.nextLine();
startMethods(obj1, input);
} else
startMethods(obj1, input);
System.out.println("Do want to try again "
+ "Y/N");
input = inputString.nextLine();
contLoop1 = input.charAt(0);
} while (contLoop1 != 'n');
}
Try this:
public class Selector8 {
public static void main(String[] args) {
Selector8 obj1 = new Selector8();
Scanner inputString = new Scanner(System.in);
Scanner inputYN = new Scanner(System.in);
String input, A, B, C;
System.out.println("Choose. A || B || C || X to exit");
input = inputString.nextLine();
char contLoop1 = 'y';
while (contLoop1 != 'n') {
if (input.equalsIgnoreCase("y")) {
System.out.println("Choose. A || B || C || X to exit");
input = inputString.nextLine();
}
switch (input) {
case ("a"):
case ("b"):
case ("c"):
obj1.startMethod();
break;
default:
System.out.println(validate(input));
break;
}
System.out.println("Do want to try again " + "Y/N");
input = inputYN.nextLine();
contLoop1 = input.charAt(0);
}
}
public static String validate(String input) {
if (input.equalsIgnoreCase("x"))
return "Goodbye";
if (input.equalsIgnoreCase("n"))
return "See ya";
return "Invalid argument. Try again";
}
public void startMethod() {
Scanner inputString = new Scanner(System.in);
System.out.println("Enter a or b");
String input = inputString.nextLine();
switch (input) {
case ("a"):
case ("b"):
System.out.println("output parsed");
break;
default:
System.out.println("Invalid argument");
}
}
}

Categories

Resources