How to avoid an else if marathon in Java? - java

I am beginning Java programming, and I have written a program which tests how many moons each planet has. Here is a shortened version with only four of the planets.
import java.util.Scanner;
import java.util.Random;
public class one {
public static void main(String args[]){
//SET VARIABLES
String zero="Mercury", one="Venus", two="Earth", three="Mars";
//SET VARIABLES
for (int x=1; x<=1000; x++){
System.out.println("Moons");
Random r = new Random();
for (int y=1; y<=1; y++){
int rI = r.nextInt(4);
if (rI == 0){
question(zero,0);
}
else if (rI == 1){
question(one, 0);
}
else if (rI == 2){
question(two, 1);
}
else if (rI == 3){
question(three, 2);
}
}
}
}
public static void question(String n, int num){
Scanner input = new Scanner(System.in);
System.out.print("How many moons does " + n + " have? ");
int ans = input.nextInt();
if (ans == num){
System.out.println("Correct!");
}
else if (ans != num){
System.out.println("Incorrect!");
question(n, num);
}
}
}
How would I go about not having to write "else if" so many times? This becomes very tedious with more statements. Keep in mind I am a beginner, and this code is about the limit of my current abilities.

You could use arrays like so:
String[] planets = { "Mercury", "Venus", "Earth", "Mars" };
int moons[] = { 0, 0, 1, 2 };
and call:
if (rI >= 0 && rI < planets.length) {
question(planets[rI], moons[rI]);
}

A better way to write this code. It is more readable and it is very easy to make any updates.
import java.util.Scanner;
import java.util.Random;
public class one {
public static void main(String args[]){
//SET VARIABLES
String planets []=new String[4];
planets[0]="Mercury";
planets[1]="Venus";
planets[2]="Earth";
planets[3]="Mars";
int moons []=new int[4];
moons[0]=0;
moons[1]=0;
moons[2]=1;
moons[3]=2;
//SET VARIABLES
while(true){
System.out.println("Moons");
Random r = new Random();
int rI = r.nextInt(4);
question(planets[rI],moons[rI]);
}
}
public static void question(String n, int num){
Scanner input = new Scanner(System.in);
System.out.print("How many moons does " + n + " have? ");
int ans = input.nextInt();
if (ans == num){
System.out.println("Correct!");
}
else if (ans != num){
System.out.println("Incorrect!");
question(n, num);
}
}
}

You could go with switch or if-else as long as you logic does not evolve. Otherwise you need to start the object-oriented programming.
Create a class "Planet" and another class for each planet that inherits from Planet and add the planet specific information to each of it. Then you're good for the future when you may plan to add some more questions for the planets.

Take a look at the switch statement in Java. That is designed to help overcome a screwy if-elseif-elseif-elseif-else block:
switch(rI){
case 2: question(two, 1);
break;
case 3: question(three, 2);
break;
default: doSomethingClever(...);
}
There are some other cleanups you could employ, but getting that switch block in place addresses your initial comment. Good luck.

You can try using switch instead of the long if-else ladder.
For more information on switch read the java documentation
In your case it could be something like:
switch (rI) {
case 0:
question(zero, 0);
break;
case 1:
question(one, 0);
break;
case 2:
question(two, 1);
break;
case 3:
question(three, 2);
break;
default:
break;
}

You could use the switch keyword:
switch (rI) {
case 0:
question(zero, 0);
break;
case 1:
question(one, 0);
break;
case 2:
question(two, 1);
break;
case 3:
question(three, 2);
break;
default:
// do something
}
The code under default executes when no match is found.
You could also use arrays:
String[] planets = new String[]{"Mercury", "Venus", "Earth", "Mars"};
int[] nums = new int[]{0, 0, 1, 2};
...
// in the loop:
question(planets[rI], nums[rI]);
Of course, there are other ways to approach the problem, but I think for someone who is just learning these should do the trick. One thing you might want to look into, however, (once you get deeper into Java), is the concept of a Map, much like a dictionary in Python. You could maintain a map that maps a planet (string) to the number of moons it has (int).

I would prefer enums over arrays here. See this enums tutorial (especially the planets example ;) ). Add another field (just like mass and radius) for moon count.

I would start with forgetting that vector-thing and putting Planets and their Moons together in a POJO (Plain Old Java Object) and putting those objects into the Array:
class Planet {
int moons;
String name;
Planet(String name, int moons) {
this.name = name;
this.moons = moons;
}
public String getName() {
return this.name;
}
public getMoons() {
return this.moons;
}
public void question(){
Scanner input = new Scanner(System.in);
System.out.print("How many moons does " + this.name + " have? ");
int ans = input.nextInt();
if (ans == this.moons){
System.out.println("Correct!");
}
else {
System.out.println("Incorrect!");
}
}
}
public class one {
public static void main(String args[]){
//SET VARIABLES
List<Planet> planets = new ArrayList<Planets>();
Planet earth = new Planet("Earth", 1);
// put other planets
//SET VARIABLES
for (int x=1; x<=1000; x++) {
System.out.println("Moons");
Random r = new Random();
int rI = r.nextInt(planets.size());
Planet p = planets.get(rI);
p.question();
}
}
}

Related

I have to do this task (online shop) using "switch" statements. I got stuck

"Write a Java program to simulate an online store. The program should begin
by displaying a list of products and their prices. There should be a minimum of 4
products offered.
My code is below, it works without the strings but I need to have names for the cakes(display names and prices)
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner input= new Scanner(System.in)
int cakeNo = 0;
double cake1;
double cake2;
double cake3;
double cake4;
double cake5;
int quantity;
double totalSales = 0;
while(cakeNo !=0 )
System.out.println("Enter cake number 1-5");
cakeNo=input.nextInt();
System.out.println("Enter quantity");
quantity = input.nextInt();
switch (cakeNo){
case 1: cake1 = 3.70;
totalSales+=(3.70*quantity);
break;
case 2: cake2 = 4.20;
totalSales+=(4.20*quantity);
break;
case 3: cake3 = 4.50;
totalSales+=(4.50*quantity);
break;
case 4: cake4 = 5.00;
totalSales+=(5.00*quantity);
break;
case 5: cake5 = 5.50;
totalSales+=(5.50*quantity);
break;
}
System.out.println(totalSales);
}
}
Thank you so much for reading! Please help if you have an idea.
Well there are a few things wrong in your code that you should take care first.
First: The first 5 string are wrongly defined. It should be like this String cake1 = "Angel cake" and so on.
Second: The strings and doubles have the same names you cannot do that. You need to have something like String cake1Name = "Name" and double cake1Price = price this way you have two distinct properties for everycake.
Third: Right now the code doesn't even enters the while loop. Since cakeNo starts with 0 and the condition in your while loop is cakeNo != 0 right on before the first loop this condition will be tested and it will be false meaning that the loop code won't be executed and will jump to the end of the program.
After this fixes there is still a little problem. After you get the input from the user if said input is 0 meaning that he wants to leave the program will still ask him for a quantity. You need to add/change something that breaks the loop when this conditions is true. I don't want to give you code but I hope this answer can help you good luck :)
This is what I would do:
public class Main {
LinkedList<Product> cart = new LinkedList<Product> ();
Scanner scanner = new Scanner(System.in);
double tax = 7.5;
boolean done = false;
public Main() {
cart.add(new Product("Cake 1", 3.70));
cart.add(new Product("Cake 2", 4.20));
cart.add(new Product("Cake 3", 4.50));
cart.add(new Product("Cake 4", 5.00));
cart.add(new Product("Cake 5", 5.50));
}
public void displayCart() {
for (int i = 0; i < cart.size(); i++) {
switch (cart.get(i).quantitySelected){
case 0:
System.out.println(i + ": " + cart.get(i).name + " none selected");
break;
default:
System.out.println(i + ": " + cart.get(i).name + " selected: " + cart.get(i).quantitySelected);
break;
}
}
}
public void addToCart(int product, int amount) {
cart.get(product).select(amount);
}
public void getSelection() {
int productSelected;
System.out.println("enter a product value or FINNISHED to end: ");
try {
productSelected = scanner.nextInt();
} catch (InputMismatchException e) {
done = true;
return;
}
System.out.println("enter amount to select: ");
int amount = scanner.nextInt();
cart.get(productSelected).select(amount);
}
public double getSubtotal() {
double cost = 0.00;
for (Product product : cart) {
cost += product.cost * product.quantitySelected;
}
return cost;
}
public double getTotal() {
return getSubtotal() + getSubtotal()*tax;
}
public void finnishPurchase() {
System.out.println("---------------------");
System.out.println("subtotal: " + getSubtotal());
System.out.println("tax: " + tax);
System.out.println("total: " + getTotal());
}
public static void main(String[] args) {
Main store = new Main();
while (!store.done) {
store.displayCart();
store.getSelection();
}
store.finnishPurchase();
}
}
public class Product {
String name;
double cost;
int quantitySelected = 0;
public Product(String name, double cost) {
this.name = name;
this.cost = cost;
}
public void select(int quantity) {
quantitySelected = quantity;
}
}

Can I get help figuring out this?

When i run my code, I get an error in mimir (idk if you guys know about it but is a platform that teachers use to check the test cases of the code that you submit) saying that I a have a whitespace that shouldn't be there (check image).
1.) how can i fix that regarding my code.
and another issue which it drove me crazy is,
how can I make it so that when I enter a letter, In this case it was inputted 'f' (check the image) to display the "enter two integers:" just like the imagine. I tried different types of loops and changing the layout but i never got it to be correct.
p.d. Yes, this was a homework and was due yesterday. Even though i got a good grade on it, it still bugged me that I couldn't figure out these two things out.
import java.util.InputMismatchException;
import java.util.Scanner;
public class MathTeacher {
public static int addNumbers(int n1, int n2){
int add = n1+n2;
return add;
}
public static int subtractNumbers(int n1, int n2){
int subs = n1-n2;
return subs;
}
public static int multiplyNumbers(int n1, int n2){
int mulp = n1*n2;
return mulp;
}
public static int divideNumbers(int n1, int n2){
int div = n1/n2;
return div;
}
private static int getIntFromUser(Scanner scan) {
int x;
while (true) {
try {
x = scan.nextInt();
break;
} catch (InputMismatchException e) {
scan.next();
}
}
return x;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Welcome to *Mental Math Practice* where you can test your addition, subtraction, multiplication, and division.");
Scanner scanner = new Scanner(System.in);
System.out.println("Enter two integers: ");
String typeQuit= "";
do {
int choices;
int n1 = getIntFromUser(scanner);
int n2 = getIntFromUser(scanner);
System.out.println("Enter 1 to add the two numbers.");
System.out.println("Enter 2 to subtract the second number from the first number.");
System.out.println("Enter 3 to multiply the two numbers.");
System.out.println("Enter 4 to divide the first number by the second number.");
choices = scanner.nextInt();
switch (choices) {
case 1: {
int add = addNumbers(n1, n2);
System.out.println(add);
break;
}
case 2: {
int sub = subtractNumbers(n1, n2);
System.out.println(sub);
break;
}
case 3: {
int mulp = multiplyNumbers(n1, n2);
System.out.println(mulp);
break;
}
case 4: {
int div = divideNumbers(n1, n2);
System.out.println(div);
break;
}
}
System.out.println("Enter 'Quit' to end the program.");
typeQuit = scanner.next();
} while(!typeQuit.equals("Quit"));
}
}

Why am i not able to regenerate a new game board after user respond yes to if the want to restart?

https://cse.sc.edu/~shephejj/csce146/Homework/Homework01.html
import java.util.*;
public class MineSweep {
enum Spaces{Empty,Player,Cone,Mine}
public static final int Board_Size=10;
public final static double Percent_Mine = 0.1;
public static void main(String[]arg){
Spaces[][] Board= new Spaces[Board_Size][Board_Size];//Creates new multidimensional array.
int numOfMoves=0;
int positionX=0;
int positionY=0;
boolean isOver=false;
boolean isDead = false;
Random r= new Random();
//Random Places the cone on the GameBoard.
int coneX=r.nextInt(Board_Size);
int coneY=r.nextInt(Board_Size);
Scanner Scan = new Scanner(System.in);
Scanner scan2 = new Scanner(System.in);
for(int i=0;i<Board.length;i++){
for(int j =0; j<Board[1].length;j++){
Board[i][j]=Spaces.Empty;
}
}
Board[positionX][positionY]= Spaces.Player;
Board[coneX][coneY]=Spaces.Cone;
System.out.println("Welcoem to Mine Walker. Get the ice cream cone and avoid the Mines.");
int mines = (int)(Board_Size*Board_Size*Percent_Mine);
do
{
int x = r.nextInt(Board_Size-1)+1;
int y =r.nextInt(Board_Size-1)+1;
//Places mines in random spots
if (Board[x][y]== Spaces.Empty)
{
Board[x][y]=Spaces.Mine;
mines--;
}
}
while(mines>0);
if(isDead==true){
Board=generateBoard();
}else{
while(isOver==false)
{
for(int y=0;y<Board.length;y++)
{
for(int x=0;x<Board[y].length;x++)
{
switch(Board[x][y])
{
case Empty:
System.out.print("_");
break;
case Player:
System.out.print("X");
break;
case Mine:
System.out.print("!");
break;
case Cone:
System.out.print("^");
break;
default:
System.out.print("?");
break;
}
}
System.out.println(" ");
}
System.out.println("Enter either -1,0,1 to move in the X or 9 to quit");
int directionX = Scan.nextInt();
if(directionX==9)
{
System.out.println("Game Over");
System.exit(0);
}
System.out.println("Enter either -1,0,1 to move in th Y");
int directionY= Scan.nextInt();
if(directionX<-1 || directionX>1){
System.out.println("Invalid Input X");
directionX=0;
}
if(directionY <-1 || directionY>1)
{
System.out.println("Invalid input Y");
directionY = 0;
}
Board[positionX][positionY] = Spaces.Empty;
positionX+=directionX;
positionY+=directionY;
if(positionX < 0)
{
positionX = 0;
}
else if(positionX>Board_Size-1)
{
positionX = Board_Size-1;
}
if(positionY < 0)
{
positionY = 0;
}
else if(positionY> Board_Size-1)
{
positionY = Board_Size-1;
}
String retry;
if(Board[positionX][positionY]==Spaces.Mine)
{
isDead=true;
System.out.println("Boom! Dead!");
System.out.println("Would you like to play again? \"Yes\" or \"No\"");
retry = scan2.nextLine();
if (retry.equalsIgnoreCase("Yes"))
{
isOver = false;
generateBoard();
}
else if (retry.equalsIgnoreCase("No"))
{
System.out.println("Goodbye!");
System.exit(0);
}
}
if(Board[positionX][positionY]==Spaces.Cone)
{
System.out.println("You win!");
System.out.println("Would you like to play again? \"Yes\" or \"No\"");
}
Board[positionX][positionY] = Spaces.Player;
}
}
}
public static Spaces[][] generateBoard(){
int positionX=0;
int positionY=0;
Random r= new Random();
//Random Places the cone on the GameBoard.
int coneX=r.nextInt(Board_Size);
int coneY=r.nextInt(Board_Size);
Spaces[][] Board= new Spaces[Board_Size][Board_Size];
for(int i=0;i<Board.length;i++){
for(int j =0; j<Board[1].length;j++){
Board[i][j]=Spaces.Empty;
}
}
Board[positionX][positionY]= Spaces.Player;
Board[coneX][coneY]=Spaces.Cone;
System.out.println("Welcoem to Mine Walker. Get the ice cream cone and avoid the Mines.");
int mines = (int)(Board_Size*Board_Size*Percent_Mine);
do
{
int x = r.nextInt(Board_Size-1)+1;
int y =r.nextInt(Board_Size-1)+1;
//Places mines in random spots
if (Board[x][y]== Spaces.Empty)
{
Board[x][y]=Spaces.Mine;
mines--;
}
}
while(mines>0);
return Board;
}
}
In the code is above.Everything works, i'm just unable to create a new game board.I create a method called "generateboard()" and I call that method if "isDead= true" and user responds yes to if they want to retry.Please Help !
First of, you should really try to clean up your code a bit. It has some duplication and it is kinda hard to read. That said, I think your problem lies with this piece of code:
if (retry.equalsIgnoreCase("Yes"))
{
isOver = false;
generateBoard();
}
You are generating a new board, but you are not telling your program to use it. Change generateBoard() to Board = generateBoard();. Also you forget to reset your players position to 0,0.
Now I would like to give you some pointers on how you could clean up your program. The first part of your main method is basically a copy paste of your generate board method, this means that you could instead reuse that method to initialize the board.
After generating your board, the first if statement if (isDead == true) will never be true, because you just set isDead = false. Just do away with this if statement. This actually makes your isDead variable unused, because you don't use it otherwise.
You probably want to either return the starting position of the player from the generateBoard method, or take the starting position as arguments to the method in order to know where the position of the player is. In your example your player always starts at 0,0, but one could imagine that you would want to change that some time.
A couple of things to note:
In Java, variables usually start with a lower case letter (use "board" instead of "Board").
Enums in Java are usually all UPPER CASE (EMPTY instead of Empty etc.).
You don't need to use == false or ==true on boolean values, you could simply write: if (isDead).
You could also do with dividing your code into methods, but I'll leave that as an exercise for you. Also, you don't actually do anything when a player wins in the game.

Trying to access a sets of variable from string (JAVA)

Given this :
System.out.println("Make a choice : (1), (2), (3)");
//validation is a scanner already declare elsewhere
n = validation.nextLine();
switch (n) {
case "1":
play(1);
break;
case "2":
play(2);
break;
case "3":
play(3);
break;
default:
System.out.println("invalid");
/?? means I don't know
public static void play(1??){
System.out.print("Did you win? ( (y)es or (n)o ) ");
choice = validation.nextLine();
// if yes ?? ++win1
// if no ?? ++loose1
// I know how to do those loops, I don't know how to make the variable choice fit the current case (++win2 and ++loose2 ans the case 2: for example)
}
My problem, for every cases, there are a set of specific variables that has to be increment (example casevar1, win1, loose1, etc.), if the case 2 is selected, I want that the variables in the play() method now automatically refer to the proper variables (example casevar2, win2, loose2, etc.). So how do I pass that information to the play() method?
You could do somthing like this
public static void play(String s){
System.out.print("Did you win? ( (y)es or (n)o ) ");
choice = validation.nextLine();
if("1".equals(s)) {
if("y".equals(choice)) {
win1 ++;
} else if ("n".equals(choice)) {
loose1 ++;
}
}
if("2".equals(s)) {
if("y".equals(choice)) {
win2 ++;
} else if ("n".equals(choice)) {
loose2 ++;
}
}
}
Ok, with inspiration from you guys, I've answered my question. I did it this way :
in the main, something like that
case "1":
play(1, nbEasy, easyPos, easyNeg);
break;
case "2":
play(2, nbInter, interPos, interNeg);
break;
case "3":
//same thing with hard
and in the play() method, something like that :
public static void play(int niv, int nbGames, int nbPos, int nbNeg){
++nbGames;
System.out.print("Completed? ( (y)yes or (n)o ) ");
choice = validation.nextLine();
if (choice.equals("y")){
++nbPos;
}
else if (choice.equals("n"))
++nbNeg;
switch (niv){
case 1:
nbEasy=nbGames; easyPos=nbPos; easyNeg=nbNeg;
case 2:
nbInter=nbGames; interPos=nbPos; interNeg=nbNeg;
case 3:
//same thing with hard
}
}
It’s perfect for me, because I can add a lot of lines in the first section of the play () method, working with what has been passed with the switch in the main and at the end, I’m affecting the new values to the proper variables.
I would like to thank you all, I’m new to programming and new to this community, but for having tried a bunch of places, that place looks by far the best. You’re responsive, polite, cordial, and I will read all the rules to suit better this place, prepare more my questions and when I will be able, I will help others. This place is amazing, I love you guys.
I am not sure I fully understand your question. I think part of it is how to pass parameters to a method. Please follow the code and comments :
//I used 3 integers just for demonstration purpose
int casevar1, win1, loose1,casevar2, win2, loose2;
public static void main(String[]arghs){
System.out.println("Make a choice : (1), (2), (3)");
//validation is a scanner already declare elsewhere
n = validation.nextLine();
switch (n) {
case "1":
//assign values
casevar1 =7; win1 =9; loose1 =0;
play(casevar1, win1, loose1); //pass appropriate variables to play method
break;
case "2":
//assign values
casevar2 =17; win2 =8; loose2 = 4;
play(casevar2, win2, loose2); //pass appropriate variables to play method
break;
case "3":
//do like case "1" / case "2"
break;
default:
System.out.println("invalid");
}//end of switch
}
//an example of a play method recieving 3 integers.
public static void play(int casevar, int win, int loose){
System.out.print("Did you win? ( (y)es or (n)o ) ");
choice = validation.nextLine();
//follow Aku Nour's answer
}
EDITED: Added an example to answer your question.
Create an object warping the data, as #David Wallace suggested:
public class Test {
public static void main(String[]arghs){
public static void main(String[]arghs){
System.out.println("Make a choice : (1), (2), (3)");
//validation is a scanner already declare elsewhere
n = validation.nextLine();
switch (n) {
case "1":
//set an object initialized to casevar =7, win =9, loose = 0
play(new DataObject(7,9, 0));
break;
case "2":
play(new DataObject(17,8, 4));
break;
case "3":
//do like case "1" / case "2"
break;
default:
System.out.println("invalid");
}//end of switch
}
//an example of a play method recieving 3 integers.
public static void play(){
System.out.print("Did you win? ( (y)es or (n)o ) ");
choice = validation.nextLine();
//follow Aku Nour's answer
}
}
//play method receiving data object
public static void play(DataObject data){
System.out.print("Did you win? ( (y)es or (n)o ) ");
choice = validation.nextLine();
//
casevar++;
}
//as David Wallace proposed
//an object containing the 3 parameters you mentioned
class DataObject {
private int casevar; private int win; private int loose;
DataObject(int casevar, int win, int loose){
this.casevar = casevar;
this.win = win;
this.loose = loose;
}
public int getCasevar() {
return casevar;
}
public void setCasevar(int casevar) {
this.casevar = casevar;
}
public int getWin() {
return win;
}
public void setWin(int win) {
this.win = win;
}
public int getLoose() {
return loose;
}
public void setLoose(int loose) {
this.loose = loose;
}
}
}
If it doesn't answer or not clear enough don't hesitate to ask.

Java compressing some code

Very new to Java and I am looking to change the following to allow the same variable call to occur only once.
The second "b" variable is only called during rectangle and triangle. This does work just want to see if I can get that one extra line out of the main.
The "b" variable can not be moved out from the if statements as the program will not start as the user will only enter the a variable.
import java.util.*;
public class Main {
public static void main(String[]args) {
Scanner in = new Scanner(System.in);
System.out.print("? ");
String word = in.next();
Shape s = null;
while (!word.equals("quit")) {
double a = in.nextDouble();
if (word.equals("triangle")){
double b = in.nextDouble();
s = new Shapet (a, b);
}else if (word.equals("rectangle")){
double b = in.nextDouble();
s = new Shaper (a, b);
}else if (word.equals("square")){
s = new Shapes (a);
}else if (word.equals("circle")){
s = new Shapec (a);
}else if (word.equals("pentagon")){
s = new Shapep (a);
}
System.out.printf("Area of %s = %.2f\n", s, s.area());
System.out.print("? ");
word = in.next();
}
}
}
You could use switch which will not make the code shorter but more readable:
String word = in.next();
Shape s = null;
while (!word.equals("quit")) {
double a = in.nextDouble();
switch(word) {
case "triangle":
s = new Shapet (a, in.nextDouble());
break;
case "rectangle":
s = new Shaper (a, in.nextDouble());
break;
case "square":
s = new Shapes (a);
break;
case "circle":
s = new Shapec (a);
break;
case "pentagon":
s = new Shapep (a);
break;
}
word = in.next();
}
If you simply want to reduce lines of code, possibly you can go for inline code:
double a;
while (!word.equals("quit")) {
a = in.nextDouble();
if (word.equals("triangle")) {
s = new Shapet(a, in.nextDouble());
} else if (word.equals("rectangle")) {
s = new Shaper(a, in.nextDouble());
} else if (word.equals("square")) {
s = new Shapes(a);
}
// ...
}
P.S. Avoid declaring variables inside loops
If I where you I would leave the code as is and simply change the variable names to something which is more appropriate.
I would let each chunk within your if statements handle their own variables. This would make the code easier to read.
Something like so:
while (!word.equals("quit")) {
if (word.equals("triangle")){
double base = in.nextDouble(); //You could maybe print out 'Enter base length, or something like that, same goes for the one below.
double height = in.nextDouble();
s = new Shapet (base, height);
}
In this case I am assuming that you want to calculate the area of some shape and maybe render it. If this is not the case, then maybe renaming Shapet to something which gives more information on the purpose of the class might also help.
Keep in mind that although you should not write bloated code, readability is key. Thus, if you need to take an extra couple of lines to make your code easier to follow, you should, in most cases, take that path.
I think the variables are inside the if and they are all local. So you can take them out of the if. Because you are studying Java, I'd like to recommend you to change the class name to make it more Object Oriented. You also can use enum for the ShapeType. I think it's a bit far your question but I hope this help you to have a better view (Pls also change the variable "a", "b" to the meaningful one. I still keep it in my sample).
enum ShapeType {
triangle("triangle"), rectangle("rectangle"), square("square"), circle("circle"), pentagon("pentagon");
private String value;
ShapeType(String value) {
this.value = value;
}
public String getValue() {
return this.value;
}
}
Scanner in = new Scanner(System.in);
String word = in.next();
//check the type is ok or not
ShapeType shapeType = ShapeType.valueOf(word);
String quit = "quit";
Shape s = null;
double a = in.nextDouble();
double b = in.nextDouble();
while (!word.equals(quit)) {
switch(shapeType) {
case triangle:
s = new Triangle(a, b);
break;
case rectangle:
s = new Ractangle (a, b);
break;
case square:
s = new Square (a);
break;
case circle:
s = new Circle (a);
break;
case pentagon:
s = new Pentagon (a);
break;
default:
System.out.println("Invalid shape! Pls retry");
}
}

Categories

Resources