Java -how can I store an array in switch case - java

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;
}

Related

My array is only remembering last last element entered and histogram is not printing right

import java.util.Scanner;
public class RainRecording {
private int choice;
private Scanner input;
private String site;
private int days;
private int daysCounter;
private int[] rainRecorded;
private int[] rainEntered;
private float lattitude;
private float longitude;
private String message1;
private String message2;
private String message3;
private String message4;
private String message5;
private String message6;
// declare name of variable
public RainRecording() {
// declare value of variable
this.message1 = "Site";
this.message2 = "lattitude";
this.message3 = "longitude";
this.message4 = "Window";
this.message5 = "days";
this.message6 = ":";
this.daysCounter = 0;
this.input = new Scanner(System.in);
mainMenu();
}
private void mainMenu() {
System.out.println("");
System.out.println("*** Rain Gauge Menu ***");
System.out.println(" 1: Create rain gauge");
System.out.println(" 2: Display rain gauge details");
System.out.println(" 3: Add daily rainfall measurement");
System.out.println(" 4: Display rainfall histogram");
System.out.println(" 5: Get maximum rainfall");
System.out.println(" 6: Check rainfall is below threshold");
System.out.println(" 7: Display anaylsis");
System.out.println(" 8: Exit");
System.out.print("Please enter your selection: ");
Chosen();
}
private void Chosen() {
this.choice = Integer.parseInt(input.nextLine());
switch (choice) {
case 1:
createGauge();
break;
case 2:
gaugeDetails();
break;
case 3:
int i = 0;
while( i < this.days || this.daysCounter == this.days) {
if (this.daysCounter == this.days) {
System.out.printf("Error - system full\n");
mainMenu();
}
if (this.days < 1) {
mainMenu();
} else {
this.rainRecorded = new int[this.days];
System.out.printf("Please enter rainfall for the current day: ");
rainRecorded[this.daysCounter] = Integer.parseInt(input.nextLine());
this.daysCounter++;
this.rainEntered = new int[this.daysCounter];
mainMenu();
}
i++;
}
break;
case 4:
System.out.printf("\n");
displayHistogram();
break;
case 5:
break;
case 6:
break;
case 7:
break;
case 8:
break;
default:
System.out.println("Invalid input, try again");
mainMenu();
}
while (choice != 8)
;
}
private void createGauge() {
System.out.printf("\nPlease enter the name of the site :");
this.site = input.nextLine();
System.out.printf("Please enter the number of days to record :");
this.days = Integer.parseInt(input.nextLine());
System.out.printf("Please enter the lattitute :");
this.lattitude = Float.parseFloat(input.nextLine());
System.out.printf("Please enter the longitude :");
this.longitude = Float.parseFloat(input.nextLine());
mainMenu();
}
private void gaugeDetails() {
if (this.days > 0) {
System.out.printf("%-9s %-3s %s \n", this.message1, this.message6, this.site);
System.out.printf("%s %-3s % 09.4f\n", this.message2, this.message6, this.lattitude);
System.out.printf("%s %-3s %9.4f\n", this.message3, this.message6, this.longitude);
System.out.printf("%-9s %-3s %-2d%s \n", this.message4, this.message6, this.days, this.message5);
mainMenu();
} else {
mainMenu();
}
}
private void displayHistogram() {
for (int i = 0; i < this.rainEntered.length; i++) {
for (int j = 0; j < this.rainRecorded[i] - 1; j++) {
System.out.print("*");
}
System.out.println(i);
}
System.out.print("");
mainMenu();
}
public static void main(String[] args) {
#SuppressWarnings("unused")
RainRecording objName;
objName = new RainRecording();
}
}
I guys i being struck on this for a couple of days in my switch statement in case 3 is where i create my elements to enter into my array , but in seems to only remember the last array entered when i print my histogram out in case 4 displayHistogram(); and this is where my histogram is printing wrong as well.
So to issues my array isn't recording property and histogram is printing wrong.
For example users chooses 3 days to enter and values are 10,20,30, and when i print histogram its prints this.
0
1
*****************************2
What i want this below , one * for ever ten mills of rain with index printed first.
0 *
1 **
2 **
You need to move the initialisation of this.rainRecorded to createGauge method and update the displayHistogram to print as required. You can try the following:
import java.util.Scanner;
public class RainRecording {
private int choice;
private Scanner input;
private String site;
private int days;
private int daysCounter;
private int[] rainRecorded;
private int[] rainEntered;
private float lattitude;
private float longitude;
private String message1;
private String message2;
private String message3;
private String message4;
private String message5;
private String message6;
// declare name of variable
public RainRecording() {
// declare value of variable
this.message1 = "Site";
this.message2 = "lattitude";
this.message3 = "longitude";
this.message4 = "Window";
this.message5 = "days";
this.message6 = ":";
this.daysCounter = 0;
this.input = new Scanner(System.in);
mainMenu();
}
private void mainMenu() {
System.out.println("");
System.out.println("*** Rain Gauge Menu ***");
System.out.println(" 1: Create rain gauge");
System.out.println(" 2: Display rain gauge details");
System.out.println(" 3: Add daily rainfall measurement");
System.out.println(" 4: Display rainfall histogram");
System.out.println(" 5: Get maximum rainfall");
System.out.println(" 6: Check rainfall is below threshold");
System.out.println(" 7: Display anaylsis");
System.out.println(" 8: Exit");
System.out.print("Please enter your selection: ");
Chosen();
}
private void Chosen() {
this.choice = Integer.parseInt(input.nextLine());
switch (choice) {
case 1:
createGauge();
break;
case 2:
gaugeDetails();
break;
case 3:
int i = 0;
while( i < this.days || this.daysCounter == this.days) {
if (this.daysCounter == this.days) {
System.out.printf("Error - system full\n");
mainMenu();
}
if (this.days < 1) {
mainMenu();
} else {
System.out.printf("Please enter rainfall for the current day: ");
rainRecorded[this.daysCounter] = Integer.parseInt(input.nextLine());
this.daysCounter++;
this.rainEntered = new int[this.daysCounter];
mainMenu();
}
i++;
}
break;
case 4:
System.out.printf("\n");
displayHistogram();
break;
case 5:
break;
case 6:
break;
case 7:
break;
case 8:
break;
default:
System.out.println("Invalid input, try again");
mainMenu();
}
while (choice != 8)
;
}
private void createGauge() {
System.out.printf("\nPlease enter the name of the site :");
this.site = input.nextLine();
System.out.printf("Please enter the number of days to record :");
this.days = Integer.parseInt(input.nextLine());
this.rainRecorded = new int[this.days]; // move the array initialization here
System.out.printf("Please enter the lattitute :");
this.lattitude = Float.parseFloat(input.nextLine());
System.out.printf("Please enter the longitude :");
this.longitude = Float.parseFloat(input.nextLine());
mainMenu();
}
private void gaugeDetails() {
if (this.days > 0) {
System.out.printf("%-9s %-3s %s \n", this.message1, this.message6, this.site);
System.out.printf("%s %-3s % 09.4f\n", this.message2, this.message6, this.lattitude);
System.out.printf("%s %-3s %9.4f\n", this.message3, this.message6, this.longitude);
System.out.printf("%-9s %-3s %-2d%s \n", this.message4, this.message6, this.days, this.message5);
mainMenu();
} else {
mainMenu();
}
}
private void displayHistogram() {
for (int i = 0; i < this.rainEntered.length; i++) {
System.out.print(i + " ");
for (int j = 0; j < this.rainRecorded[i] - 1; j += 10 ) {
System.out.print("*");
}
System.out.println();
}
mainMenu();
}
public static void main(String[] args) {
#SuppressWarnings("unused")
RainRecording objName;
objName = new RainRecording();
}
}
So, your codes a little bit over the place and I've had some issues trying to understand the basic intent, for example
private int[] rainRecorded;
private int[] rainEntered;
I'm not sure what the intention is for these two variables. So in my example, I've discarded rainEntered for the time been.
So, your first problem starts here...
while( i < this.days || this.daysCounter == this.days) {
if (this.daysCounter == this.days) {
System.out.printf("Error - system full\n");
mainMenu();
}
if (this.days < 1) {
mainMenu();
} else {
this.rainRecorded = new int[this.days];
System.out.printf("Please enter rainfall for the current day: ");
rainRecorded[this.daysCounter] = Integer.parseInt(input.nextLine());
this.daysCounter++;
this.rainEntered = new int[this.daysCounter];
mainMenu();
}
i++;
}
First, I'd remove the need to for the two exit conditions, as it is going to make it more difficult to reasons about
Next, the checks for the validity of the data should be done outside of the loop and I'd also avoid calling mainMenu from within it, this is going to quickly put you in a strange place.
But, my main problem is with
this.rainRecorded = new int[this.days];
System.out.printf("Please enter rainfall for the current day: ");
rainRecorded[this.daysCounter] = Integer.parseInt(input.nextLine());
this.daysCounter++;
this.rainEntered = new int[this.daysCounter];
You keep creating new instances of both this.rainRecorded and this.rainEntered, meaning that each time the loop runs, you've lost anything that was previous entered.
So, in my "simplified" version, I modified it down to something like...
if (this.days < 1) {
System.out.println("Invalid number of days");
return;
}
if (this.daysCounter == this.days) {
System.out.printf("Error - system full\n");
return;
}
while (this.daysCounter < this.days) {
System.out.printf("Please enter rainfall for the day " + (daysCounter + 1) + ": ");
rainRecorded[this.daysCounter] = Integer.parseInt(input.nextLine());
this.daysCounter++;
}
I then simplified the histogram workflow as well, but I'm still trying to get my head around what rainEntered is suppose to do...
private void displayHistogram() {
for (int amount : rainRecorded) {
for (int count = 0; count < amount; count++) {
System.out.print("*");
}
System.out.println(" " + amount);
}
}
One last thing I also did, was to remove all the calls to mainMenu and instead relied on a simple do-while loop to reprint the menu each time it returned from Chosen method
private void mainMenu() {
do {
System.out.println("");
System.out.println("*** Rain Gauge Menu ***");
System.out.println(" 1: Create rain gauge");
System.out.println(" 2: Display rain gauge details");
System.out.println(" 3: Add daily rainfall measurement");
System.out.println(" 4: Display rainfall histogram");
System.out.println(" 5: Get maximum rainfall");
System.out.println(" 6: Check rainfall is below threshold");
System.out.println(" 7: Display anaylsis");
System.out.println(" 8: Exit");
System.out.print("Please enter your selection: ");
Chosen();
} while (shouldContinue);
}
This simplifies the workflow, as it's easier to reason about where you are at any point in the execution of the program, instead of wondering why when, under some condition, when you chose something from the menu, you end up in some other part of the program instead.
Example
import java.util.Scanner;
public class RainRecording {
private int choice;
private Scanner input;
private String site;
private int days;
private int daysCounter;
private int[] rainRecorded;
//private int[] rainEntered;
private float lattitude;
private float longitude;
private String message1;
private String message2;
private String message3;
private String message4;
private String message5;
private String message6;
private boolean shouldContinue = true;
// declare name of variable
public RainRecording() {
// declare value of variable
this.message1 = "Site";
this.message2 = "lattitude";
this.message3 = "longitude";
this.message4 = "Window";
this.message5 = "days";
this.message6 = ":";
this.daysCounter = 0;
this.input = new Scanner(System.in);
mainMenu();
}
private void mainMenu() {
do {
System.out.println("");
System.out.println("*** Rain Gauge Menu ***");
System.out.println(" 1: Create rain gauge");
System.out.println(" 2: Display rain gauge details");
System.out.println(" 3: Add daily rainfall measurement");
System.out.println(" 4: Display rainfall histogram");
System.out.println(" 5: Get maximum rainfall");
System.out.println(" 6: Check rainfall is below threshold");
System.out.println(" 7: Display anaylsis");
System.out.println(" 8: Exit");
System.out.print("Please enter your selection: ");
Chosen();
} while (shouldContinue);
}
private void Chosen() {
this.choice = Integer.parseInt(input.nextLine());
switch (choice) {
case 1:
createGauge();
break;
case 2:
gaugeDetails();
break;
case 3:
if (this.days < 1) {
System.out.println("Invalid number of days");
return;
}
if (this.daysCounter == this.days) {
System.out.printf("Error - system full\n");
return;
}
while (this.daysCounter < this.days) {
System.out.printf("Please enter rainfall for the day " + (daysCounter + 1) + ": ");
rainRecorded[this.daysCounter] = Integer.parseInt(input.nextLine());
this.daysCounter++;
}
break;
case 4:
System.out.printf("\n");
displayHistogram();
break;
case 5:
break;
case 6:
break;
case 7:
break;
case 8: shouldContinue = false;
break;
default:
System.out.println("Invalid input, try again");
}
}
private void createGauge() {
System.out.printf("\nPlease enter the name of the site :");
this.site = input.nextLine();
System.out.printf("Please enter the number of days to record :");
this.days = Integer.parseInt(input.nextLine());
System.out.printf("Please enter the lattitute :");
this.lattitude = Float.parseFloat(input.nextLine());
System.out.printf("Please enter the longitude :");
this.longitude = Float.parseFloat(input.nextLine());
if (days > 0) {
this.rainRecorded = new int[this.days];
}
}
private void gaugeDetails() {
if (this.days > 0) {
System.out.printf("%-9s %-3s %s \n", this.message1, this.message6, this.site);
System.out.printf("%s %-3s % 09.4f\n", this.message2, this.message6, this.lattitude);
System.out.printf("%s %-3s %9.4f\n", this.message3, this.message6, this.longitude);
System.out.printf("%-9s %-3s %-2d%s \n", this.message4, this.message6, this.days, this.message5);
}
}
private void displayHistogram() {
for (int amount : rainRecorded) {
for (int count = 0; count < amount; count++) {
System.out.print("*");
}
System.out.println(" " + amount);
}
}
public static void main(String[] args) {
#SuppressWarnings("unused")
RainRecording objName;
objName = new RainRecording();
}
}
Now, if rainEntered is suppose to be some kind of compounding array, where it allows you to record multiple days of rain over different periods, you might consider using a multi-dimensional array instead, so you could n periods and each period could have n days of rain...

Java nested loop issue with switch statement

For case "1" it seems to just loop instead of jumping to drunkSong();. If the user selects case "2" it will work fine and ask the user to input the number to return the int "BeerNum".
Case "1" needs to accept a default value of 99 while Case "2" needs to accept user input.
I have attached the code, if you can point my mistake out or where I have gone wrong.
package PartOne;
import java.util.Scanner;
public class View {
public void begin() {
BeerSong.drunkSong();
}
private int setBeerNum() {
return beerNum;
}
private int beerNum;
public Integer Menu() {
Scanner in = new Scanner(System.in);
// print menu
for (int i = 1; i <= 3; i++)
System.out.println(i + ". Menu item #" + i);
System.out.println("0. Quit");
// handle user commands
boolean quit = false;
int menuItem;
do {
System.out.print("Choose menu item: ");
menuItem = in.nextInt();
switch (menuItem) {
case 1:
System.out.println("Default ");
begin();
while (true)
try {
//where I have made a mistake
beerNum = 99;
this.beerNum = setBeerNum();
break;
} catch (NumberFormatException BecauseIsaidSo) {
System.out.print("Try again: ");
}
//working
case 2:
System.out.println("Enter your number to play the song: ");
Scanner scan = new Scanner(System.in);
while (true)
try {
beerNum = Integer.parseInt(scan.nextLine());
this.beerNum = setBeerNum();
return beerNum;
} catch (NumberFormatException BecauseIsaidSo) {
System.out.print("Try again: ");
}
case 0:
quit = true;
break;
default:
System.out.println("Invalid choice.");
}
}
while (!quit) ;
System.out.println("Bye-bye!");
return null;
}
}
I think it is much better to encapsulate menu logic in the separate class and encapsulate all logic in it. Moreover, logic for each menu item should be encapsulated in separate method as well.
public final class Menu {
private Integer res;
private boolean quit;
public static Integer showMenuAndGetResult() {
Menu menu = new Menu();
menu.activate();
return menu.res;
}
private Menu() {
}
private void activate() {
try (Scanner in = new Scanner(System.in)) {
show();
while (!quit) {
System.out.print("Choose menu item: ");
int menuItem = in.nextInt();
if (menuItem == 1)
onMenuItem1(in);
else if (menuItem == 2)
onMenuItem2(in);
else if (menuItem == 0)
onMenuQuit();
else
System.out.println("Invalid choice.");
}
System.out.println("Bye-bye!");
}
}
private void show() {
for (int i = 1; i <= 3; i++)
System.out.println(i + ". Menu item #" + i);
System.out.println("0. Quit");
System.out.println();
}
private void onMenuItem1(Scanner scan) {
System.out.println("Default ");
// TODO menu 1 logic incapsulation
}
private void onMenuItem2(Scanner scan) {
System.out.println("Enter your number to play the song: ");
// TODO menu 2 logic incapsulation
}
private void onMenuQuit() {
res = null;
quit = true;
}
}
P.S. I personally try to avoid using switch. This is not my recomendation, just note. I think that if...else if is more readable and problemless.

How to use control statements on a methods? if possible

I don't know how to say
if money(); < 1000 and house(); is == small print your poor
or
if money(); >=1000 and < 5000 and house(); is == to normal to print your ok, your too rich
package ArrayTest;
import java.util.Scanner;
/**
* Created by quwi on 02/12/2017.
*/`enter code here`
public class Happyness {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
// house();
// money();
comparison();
}
private static void house() {
// getting user input and using the switch statement to see the size
// of their house
System.out.println("Please enter the size of your house ");
String cap = scanner.next();
switch (cap) {
case "small":
System.out.println("you have a small house it means your poor");
break;
case "normal":
System.out.println("your house normal, it mean your not poor nor rich");
break;
case "large":
System.out.println("your house is big it means your rich");
break;
default:
System.out.println("please choose between: small, normal or large");
break;
}
}
private static void money() {
System.out.println("please enter a number");
int wage = scanner.nextInt();
if (wage < 1000) {
System.out.println("your poor");
} else if (wage >= 1000 && wage < 5000) {
System.out.println("your not poor, your OK");
} else if (wage > 5000) {
System.out.println("your rich, Give me money");
} else {
System.out.println("please enter a number nothing else");
}
}
private static void comparison() {
System.out.println("please enter a number");
int decision = scanner.nextInt();
switch (decision) {
case 1:
money();
break;
case 2:
house();
break;
case 3:
money();
house();
break;
default:
System.out.println("Please choose 1, 2 or 3");
}
}
}
Use return value from both to compare.
private static String money() {
System.out.println("please enter a number");
int wage = scanner.nextInt();
if (wage < 1000) {
return "poor";
} else if (wage >= 1000 && wage < 5000) {
return "ok";
} else if (wage > 5000) {
return "rich";
} else {
//ask for input again or exit, whatever
}
}
Do same for the house(). Then, compare the return values from both in another method.

Creating a Basic Java phone book

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.

Adding words and checking in Arraylist Hangman

I'm having trouble with adding words and using do while in my code:
ArrayList<String> word = new ArrayList<>();
word.add("fish");
word.add("chicken");
word.add("icecream");
int lengthz = word.size();
Scanner sc = new Scanner(System.in);
System.out.println("Hangman");
System.out.println("1. 1 Player");
System.out.println("2. 2 Player");
System.out.println("3. Add word");
System.out.println("4. Quit");
System.out.print("Choice : ");
int opsi = sc.nextInt();
if (opsi == 3) {
boolean show = false;
boolean founded = false;
System.out.println("Input the words to be added : ");
boolean showall = true;
do {
String input = sc.next() + sc.nextLine();
for (int i = 0; i < lengthz; i++) {
if (!input.equals(word.get(i))) {
while (!founded) {
word.add(input);
System.out.println("Succeed!");
founded = true;
}
} else if (input.equals(word.get(i))) {
while (!show) {
System.out.println("Already Added");
show = true;
}
}
}
System.out.println("Want to add more words?");
String answer = sc.next() + sc.nextLine();
if (answer.equals("no")) {
System.out.println("Thanks for adding");
showall = false;
} else if (answer.equals("yes")) {
opsi = 3;
}
} while (showall);
for (int i = 0; i <= lengthz; i++) {
System.out.println(word.get(i));
}
}
My desired output will be like if the user wants to add more word with "yes" then it will repeat the program, and if the user types "no" then it will display all the words together with the addition, and then going back to show the menu 1-4 option. Please help me ... Thanks in advance !
Structure your code, e.g. as follows:
static final Scanner in = new Scanner(System.in);
static List<String> words = getStandardWords();
public static void main(String[] args) {
while (true) {
System.out.println("-- Hangman --");
System.out.println("1. 1 Player");
System.out.println("2. 2 Player");
System.out.println("3. Add word");
System.out.println("4. Quit");
System.out.print("Choice : ");
String choice = in.nextLine();
switch (choice) {
case "1":
//todo
break;
case "2":
//todo
break;
case "3":
addWord();
break;
case "4":
System.exit(0);
break;
default:
System.out.println("Invalid choice: " + choice);
break;
}
}
}
static List<String> getStandardWords() {
List<String> result = new ArrayList<>();
result.add("fish");
result.add("chicken");
result.add("icecream");
return result;
}
static void addWord() {
System.out.println("Input the word to be added: ");
String word = in.nextLine();
// add word
if (words.contains(word)) {
System.out.println("Already Added");
} else {
words.add(word);
System.out.println("Succeed!");
}
// add more words?
while (true) {
System.out.println("Want to add more words?");
String choice = in.nextLine();
switch (choice.toLowerCase(Locale.ROOT)) {
case "n":
case "no":
System.out.println("Thanks for adding");
// print all words
for (int i = 0; i < words.size(); i++) {
System.out.println(words.get(i));
}
return;
case "y":
case "yes":
addWord();
return;
default:
System.out.println("Invalid coice: " + choice);
break;
}
}
}
1) You need to initialize the
founded = false;
inside do - while loop
2) use last printing for loop as below :
for(int i=0; i<word.size();i++)
{
System.out.println(word.get(i));
}

Categories

Resources