This question already has answers here:
java.util.NoSuchElementException - Scanner reading user input
(5 answers)
Closed 6 years ago.
Alright so this is my first time posting.
I'm trying to create a box using another class that creates a rectangle. But when I try to run, I get to input the values for height and width but right after I try to input depth this error pops up.
Thanks in advance for any help.
Console:
Ange rektangelns bredd:
10
Ange rektangelns höjd:
10
En rektangelns med bredden 10 och höjden 10 ger arean 100
Ange rektangelns djup:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at cj222qu.Box.<init>(Box.java:18)
at cj222qu.Steg4_lab02.main(Steg4_lab02.java:7)
Box class:
import java.util.Scanner;
public class Box extends Rectangle {
private int depth;
public Box() {
Scanner hej = new Scanner(System.in);
String dep = null;
boolean go3 = true;
while (go3) {
try {
System.out.println("Ange rektangelns djup: ");
dep = hej.next();
Integer.parseInt(dep);
go3 = false;
} catch (NumberFormatException e) {
System.out.println("Ett fel har inträffat! Ange värdet som ett tal");
go3 = true;
}
}
//new Box(getWidth(), getHeight(), Integer.parseInt(dep));
hej.close();
}
public Box(int width, int height, int depth) {
setDepth(depth);
System.out.println(toString());
}
public String toString() {
StringBuilder result = new StringBuilder();
result.append("En låda med bredden " + getWidth() + ", höjden " + getHeight() + " och djupet " + ".");
result.append("Lådans volym är " + computeVolume() + ".");
result.append("Lådans mantelarea är " + computeArea() + ".");
return result.toString();
}
public int computeVolume() {
int volume = 0;
volume = getWidth() * getHeight() * getDepth();
return volume;
}
public int computeArea() {
int mantelarea = 0;
mantelarea = getDepth() * getWidth() * 2 + getDepth() * getHeight() * 2 + getWidth() * getHeight() * 2;
return mantelarea;
}
public int getDepth()
{
return depth;
}
public void setDepth(int d)
{
depth = d;
}
}
Rectangle class:
import java.util.Scanner;
public class Rectangle {
private int height;
private int width;
public Rectangle(int width, int height)
{
setHeight(height);
setWidth(width);
System.out.println(toString());
}
#Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append("En rektangelns med bredden " + width + " och höjden " + height + " ger arean " + computeArea());
return result.toString();
}
public Rectangle()
{
Scanner keyboard = new Scanner(System.in);
String w = null;
String h = null;
boolean go1 = true;
boolean go2 = true;
while (go1) {
try {
System.out.println("Ange rektangelns bredd: ");
w = keyboard.next();
Integer.parseInt(w);
go1 = false;
} catch (NumberFormatException e) {
System.out.println("Ett fel har inträffat! Ange värdet som ett tal");
go1 = true;
}
}
while (go2) {
try {
System.out.println("Ange rektangelns höjd: ");
h = keyboard.next();
Integer.parseInt(h);
go2 = false;
} catch (NumberFormatException e) {
System.out.println("Ett fel har inträffat! Ange värdet som ett tal");
go2 = true;
}
}
new Rectangle(Integer.parseInt(w), Integer.parseInt(h));
keyboard.close();
}
public int computeArea()
{
int area = 0;
area = getHeight() * getWidth();
return area;
}
public int getHeight()
{
return height;
}
public int getWidth()
{
return width;
}
public void setHeight(int h)
{
height = h;
}
public void setWidth(int w)
{
width = w;
}
}
Main:
public class Steg4_lab02 {
public static void main(String[] args) {
new Box();
}
}
You shouldn't instantiate multiple Scanners with System.in, and it's a big no-no to close a Scanner instantiated with System.in (basically closing the STDIN stream) and then creating a new Scanner with System.in.
Rectangle should have a constructor that either takes a Scanner or a constructor that takes a width and height. Then either use the passed in Scanner to collect user input or collect user input in main() and create a Rectangle with the width and height collected from the user.
As Fildor stated in the comments, the Box and Rectangle classes should not be responsible for gathering user input.
Related
Problem:
I'm trying to make a rectangle using strings that would look like this
===
| |
| |
| |
| |
===
So far I've tried this text I want to appear in the console when I tell the program the width and height of the rectangle that I am able to get a rectangle like seen above. Is there an easier was to do this I'm still learning how to use Java. I'm more failure with javascripting.
File: RectangleTester.java
public class RectangleTester extends ConsoleProgram
{
public void run()
{
// Create a new rectangle with a width of 10 and a height of 3
Rectangle rect = new Rectangle(10, 3);
// Print out information about the rectangle
System.out.println(rect);
// Print out the area of the rectangle
System.out.println("The area of the rectangle is " + rect.getArea());
// Print out the height of the rectangle
System.out.println("The height of the rectangle is " + rect.getHeight());
}
}
File: Rectangle.java
public class Rectangle
{
private int width;
private int height;
public String toString()
{
return makeTops() + makeSides() + makeTops();
}
public String makeTop()
{
String tops = "==";
for (int i = 0; i < width; i++){
tops += tops;
}
return tops;
}
private String makeSides(){
String sideSpace = sides + (space += space* (int)tops) + sides;
String sides = "||";
String space = " ";
for (int i = 0; i <= height; i++){
sideSpace += sideSpace;
}
return sideSpace;
}
}
So, makeTops is undefined...
public String toString()
{
return makeTops() + makeSides() + makeTops();
}
You need to change makeTop to makeTops...
public String makeTops() { ... }
I have no idea of what's going on here...
private String makeSides() {
String sideSpace = sides + (space += space * (int) tops) + sides;
String sides = "||";
String space = " ";
for (int i = 0; i <= height; i++) {
sideSpace += sideSpace;
}
return sideSpace;
}
You're trying to make use of variables which are not yet defined and you can't multiple a String, it doesn't make sense.
However, you can repeat a String...
private String makeSides() {
String sides = "||";
String space = " ";
String line = sides + (space.repeat(width - (sides.length() * 2))) + sides;
return (line + "\n").repeat(height - 2);
}
which also suggests you should change makeTops as well...
public String makeTops() {
return "=".repeat(width) + "\n";
}
Runnable example
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
Rectangle rect = new Rectangle(10, 3);
// Print out information about the rectangle
System.out.println(rect);
}
public class Rectangle {
private int width;
private int height;
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
public String toString() {
return makeTops() + makeSides() + makeTops();
}
public String makeTops() {
return "=".repeat(width) + "\n";
}
private String makeSides() {
String sides = "||";
String space = " ";
String line = sides + (space.repeat(width - (sides.length() * 2))) + sides;
return (line + "\n").repeat(height - 2);
}
}
}
Some, the above example will print...
==========
|| ||
==========
Now, before you tell me that's not 10x3, it is, it's 10 columns, but 3 rows.
Now, if you wanted to display the "internal" area as the rectangle instead, you should change it to...
public class Rectangle {
private static String SIDE = "||";
private static String TOP = "=";
private static String SPACE = " ";
private int width;
private int height;
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
public String toString() {
return makeTops() + makeSides() + makeTops();
}
public String makeTops() {
return TOP.repeat(width + (SIDE.length() * 2)) + "\n";
}
private String makeSides() {
String line = SIDE + (SPACE.repeat(width)) + SIDE;
return (line + "\n").repeat(height);
}
}
which will print...
==============
|| ||
|| ||
|| ||
==============
Problem Statement:
A fish has to move in a 2D Aquarium.
At no point two fishes can be at the same Location.
Challenges:
To generate a random direction in which every fish will move.
Fish should not go beyond the Aquarium specifications.
Maintaining a collection which contains the locations of all fishes in the aquarium.
Approach:
I used multi threading via Java so that all the fishes can move at the same time.
Used Enum's to extract direction for X & Y co-ordinates randomly.
Created a Fish Class which extends Location Class.
Please suggest if there could have been a different approach used for this question since I am an Intermediate Level Java Programmer.
Location Class
public class Location {
public int x;
public int y;
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
Location other = (Location) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
public Location(int Size) {
setRandomLocation(Size);
synchronized (Aquarium.location_list) {
Aquarium.location_list.add(this);
}
}
public Location() {
}
public void setRandomLocation(int Size){
int location_exist_ind=0 ;
while(location_exist_ind==0){
this.x = (int)(Math.random() * Size);
this.y = (int)(Math.random() * Size);
location_exist_ind=checkLocation(this);
}
}
public int checkLocation(Location obj){
int temp_ind=0;
synchronized (Aquarium.location_list) {
if(Aquarium.location_list.size()!=0)
for(Location loc1 : Aquarium.location_list )
{
if(obj.equals(loc1)){
System.out.println("This location" + obj.x
+ " , "
+obj.y+ " is already taken by another fish , so generating the random location again.");
temp_ind=0;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
else temp_ind=1;
}
else temp_ind=1;
}
return temp_ind;
}
public void setNextLocation(int x,int y){
int X_location = 0;
int Y_location = 0;
int location_exist_ind=0 ;
while(location_exist_ind==0){
X_location= Direction_X.getRandom_direction_X(x);
Y_location= Direction_Y.getRandom_direction_Y(y);
Location temp_loc= new Location();
temp_loc.setX(X_location);
temp_loc.setY(Y_location);
location_exist_ind=checkLocation(temp_loc);
}
this.setX(X_location);
this.setY(Y_location);
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
}
Aquarium class
import java.util.LinkedList;
import java.util.Scanner;
public class Aquarium {
static int size= 0;
static int number_of_fishes = 1000;
static int number_of_moves = 0;
static LinkedList<Location> location_list = new LinkedList<Location>();
public static void main(String[] args) {
Scanner scn= new Scanner(System.in);
System.out.println("Please enter the size of the aquarium :");
size=scn.nextInt();
while(number_of_fishes >= Math.pow(size,2)){
System.out.println("Please enter the correct number of fishes in the aquarium , MAx allowed fishes are 2 to the power size of Aquarium: ");
number_of_fishes=scn.nextInt();
}
System.out.println("Please enter the Number of Minimum Moves for each of the fishes :");
number_of_moves=scn.nextInt();
Fish[] fishes = new Fish[number_of_fishes];
Thread[] thr = new Thread[number_of_fishes];
for (int i=0;i<number_of_fishes;i++){
fishes[i]= new Fish(size, number_of_moves ,i);
thr[i]= new Thread(fishes[i]);
thr[i].start();
}
try {
for (int i=0;i<number_of_fishes;i++)
thr[i].join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Final Location list goes like : ");
for(Location loc : location_list){
System.out.println(loc.x + " , " + loc.y);
}
}
}
Fish class
public class Fish extends Location implements Runnable{
int moves=0;
int fishnum=0;
public Fish(int AquariumSize, int moves , int fishnum) {
super(AquariumSize);
this.moves=moves;
this.fishnum=fishnum;
}
#Override
public void run() {
for(int i=0;i< moves;i++){
if(i==0)
System.out.println(" Initial location of Fish " + fishnum + " Location is "+this.x + " , "+ this.y);
this.setNextLocation(x, y);
System.out.println(" Location of Fish " + fishnum + " Move number is "+ i + " , new location is "+this.x + " , " + this.y);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Direction enumeration
public enum Direction_X {
RIGHT(1),
NONE(0),
LEFT(-1);
public int direction_X_ind;
Direction_X(int X)
{
direction_X_ind = X;
}
public static int getRandom_direction_X(int x)
{
int X=x;
if(X!=0 && X!=Aquarium.size-1)
{
X = X + values()[(int) (Math.random() * (values().length))].direction_X_ind;
}
else if(x>=Aquarium.size-1)
{
X = X + values()[ (int) (Math.random() * (values().length-1)) + 1 ].direction_X_ind;
}
else
{
X = X + values()[(int) (Math.random() * (values().length-1))].direction_X_ind;
}
return (X);
}
}
public enum Direction_Y {
UP(1),
NONE(0),
DOWN(-1);
public int direction_Y_ind;
Direction_Y(int Y)
{
direction_Y_ind = Y;
}
public static int getRandom_direction_Y(int Y)
{
if(Y!=0 && Y != Aquarium.size-1)
{
Y = Y + values()[ (int) (Math.random() * (values().length))].direction_Y_ind;
}
else if(Y >= Aquarium.size-1)
{
Y = Y + values()[ (int) (Math.random() * (values().length-1)) + 1 ].direction_Y_ind;
}
else
{
Y = Y + values()[ (int) (Math.random() * (values().length-1))].direction_Y_ind;
}
return (Y);
}
}
Multi threading will only make your logic harder. The fishes' direction of movement is dependent on other fishes so this makes no sense letting each and every one of them move on its own with synchronization. Perhaps a better approach will be something involving a game loop. You can read more about it here. Basically its a more sophisticated implementation of an event loop.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have made a program inside of which, there is a specific method that makes sure that all of the objects in an array that point to null point to a blank space. For some reason, whenever I run the code, it gives me a java.lang.NullPointerException.
I understand what a NullPointerException is, which is why I added the if statement, so that it wouldn't give the error, but it still does
Code:
public class TextGraphics {
public static void main(String[] args) {
displaySize size = new displaySize(5,5);
displaySize.output(5,3,size,"H");
displaySize.run(size);
}
}
class displaySize {
public static int indent;
public static int sizeX = 0;
public static int sizeY = 0;
public displaySize() {
}
public displaySize(int screenX, int screenY) {
sizeX = screenX;
sizeY = screenY;
indent = sizeX;
}
public static void output(int x, int y, displaySize size, String print) {
rarray(size)[x + y * size.sizeX] = print;
}
public static String[] rarray(displaySize size) {
String [] display;
return display = new String[sizeX * sizeY];
}
public static void run(displaySize size) {
int next = 0;
for (int i = 0; i < sizeY; i++) {
for (int b = 0; b < indent; b++) {
next++;
if(rarray(size)[next].equals(null) )
{
System.out.print( rarray(size)[next] + " ");
rarray(size)[next] = " ";
}
System.out.print( rarray(size)[next] + " ");
}
System.out.println("/n");
}
}
}
first problem used .equals(null) instead of == null
second problem your code throws a arrayoutofindex because your next++ was in the wrong for loop
finally your new line character was wrong its \n not /n
corrected code
public class TextGraphics {
public static void main(String[] args) {
displaySize size = new displaySize(5,5);
displaySize.output(5,3,size,"H");
displaySize.run(size);
}
}
class displaySize {
public static int indent;
public static int sizeX = 0;
public static int sizeY = 0;
public displaySize() {
}
public displaySize(int screenX, int screenY) {
sizeX = screenX;
sizeY = screenY;
indent = sizeX;
}
public static void output(int x, int y, displaySize size, String print) {
rarray(size)[x + y * size.sizeX] = print;
}
public static String[] rarray(displaySize size) {
String [] display;
return display = new String[sizeX * sizeY];
}
public static void run(displaySize size) {
int next = 0;
for (int i = 0; i < sizeY; i++) {
next++;
for (int b = 0; b < indent; b++) {
if(rarray(size)[next]==(null) )
{
rarray(size)[next] = " ";
System.out.print( rarray(size)[next] + " ");
}
System.out.print( rarray(size)[next] + " ");
}
System.out.println("\n");
}
}
}
Okay so the program I'm working on needs to create an arrayList of change objects minimum of 1,000 and then compute the change that would be produced from that amount kind of like in a point of sale environment. I have everything working except I'm stumped on how to actually calculate the change. I have methods written in another class to do it, but I'm not sure how to pass the entire arrayList over to them in order to do so. If anyone could give me a hand with this it would be much appreciated.
Change class :
public class Change {
private double amount, remainingAmount;
private int occurences;
public Change() {
super();
this.amount = 17.87;
this.remainingAmount = (int)(amount * 100);
}
public Change(double amount, double remainingAmount) {
super();
this.amount = amount;
this.remainingAmount = remainingAmount;
}
public Change(float nextChange) {
this.amount = amount;
this.remainingAmount = remainingAmount;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public double getRemainingAmount() {
return remainingAmount;
}
public void incrementOccurence() {
occurences++;
}
public void setRemainingAmount(double remainingAmount) {
this.remainingAmount = remainingAmount;
}
public double numberOfOneDollars() {
int numberOfOneDollars = (int) (remainingAmount / 100);
remainingAmount = remainingAmount % 100;
return numberOfOneDollars;
}
public double numberOfQuarters() {
int numberOfQuarters = (int) (remainingAmount / 25);
remainingAmount = remainingAmount % 25;
return numberOfQuarters;
}
public double numberOfDimes() {
int numberOfDimes = (int) (remainingAmount / 10);
remainingAmount = remainingAmount % 10;
return numberOfDimes;
}
public double numberOfNickels() {
int numberOfNickels = (int) (remainingAmount / 5);
remainingAmount = remainingAmount % 5;
return numberOfNickels;
}
public int numberOfPennies() {
int numberOfPennies = (int) remainingAmount;
return numberOfPennies;
}
#Override
public String toString() {
return "Change [amount=" + amount + ", remainingAmount="
+ remainingAmount + "]\n";
}
}
Change ArrayList Class:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Scanner;
public class ChangeArrayList {
private ArrayList<Change> changeArray = new ArrayList<Change>();
private static int numOfChangeObjects = 1000;
private static String FILE_NAME = "changeData.dat";
public static void makeChangeData() {
PrintWriter outputStream = null;
try
{
outputStream = new PrintWriter(FILE_NAME);
}
catch(FileNotFoundException e) {
System.out.println("Error opening the file " + FILE_NAME);
System.exit(0);
}
for (int count = 0; count < numOfChangeObjects; count++) {
//get random number between 0-1, move decimal right two places, typecast to float
//to get rid of decimals, then divide by 10.0 to get decimal left one place
//then add 3 to make sure numbers are >3
DecimalFormat df = new DecimalFormat("#.##");
double changeData = (float)(Math.random() * 100)/10.0 + 3;
double twoDecimal = Double.valueOf(df.format(changeData));
outputStream.println(twoDecimal + " ");
}
outputStream.close();
System.out.println("Those lines were written to " + FILE_NAME);
}
public void makeChangeArray(String fileName) {
changeArray = new ArrayList<Change>();
Scanner inputStream = null;
try
{
inputStream = new Scanner(new File(FILE_NAME));
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file " +
FILE_NAME);
System.exit(0);
}
while (inputStream.hasNext())
{
//read in a change object from the file
float nextChange = inputStream.nextFloat();
//Stuck here. Can't figure out what to put in to make this work
//everything else works except this. My change keeps coming out as 0
changeArray.add(new Change(nextChange));
//Stuck here. Can't figure out what to put in to make this work
//everything else works except this. My change keeps coming out as 0
}
inputStream.close();
}
public void writeToFile() {
String fileName = "out.txt"; //The name could be read from
//the keyboard.
PrintWriter outputStream = null;
try
{
outputStream = new PrintWriter(fileName);
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file " +
fileName);
System.exit(0);
}
outputStream.println(toString());
outputStream.close( );
System.out.println("Those lines were written to " +
fileName);
}
public String toString() {
String s = "";
for (int i = 0; i < changeArray.size(); i++) {
s += changeArray.get(i).toString(); }
return s;
}
public static void main(String[] args) {
ChangeArrayList.makeChangeData();
ChangeArrayList tester = new ChangeArrayList();
tester.makeChangeArray("changeData.dat");
//Something should go here to calculate change
//Not sure how to go about doing this
tester.writeToFile();
}
}
Approach 1:
You can make getter method for changeArray in ChangeArrayList. And after calling makeChangeArray() method in main method, you can call getter method and pass that returned arraylist to required method as a parameter.
Approach 2: I wll prefer this approach.
Do not declare class level changeArray, instead declare it inside your makeChangeArray() method and change return type to List instead of void and return the prepared arraylist.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am trying to code a program that can take user input data about a carpet, parse the string into the necessary pieces of information and create carpet objects based off the shape. My code is
public class CarpetParser{
public static Carpet parseStringToCarpet(String lineToParse)
{
String delims = "[/]";
String[] info = lineToParse.split(delims);
if(info[0].equalsIgnoreCase("rectangle")){
double priceFor = Double.parseDouble(info[2]);
int height = Integer.parseInt(info[3]);
int width = Integer.parseInt(info[4]);
RectangleCarpet theCarpet = new RectangleCarpet(info[1], priceFor, height, width);
return theCarpet;
}else if(info[0].equalsIgnoreCase("circle")){
double priceFor = Double.parseDouble(info[2]);
int radius = Integer.parseInt(info[3]);
CircleCarpet theCarpet = new CircleCarpet(info[1], priceFor, radius);
return theCarpet;
}
}
}
for the parser,
public abstract class Carpet{
protected int area = 0;
protected double unitPrice = 0;
protected double totalPrice = 0.0;
protected String carpetID;
public Carpet(String ID, double thisPrice){
carpetID = ID;
unitPrice = thisPrice;
}
public String getCarpetId(){
return carpetID;
}
public String toString(){
String carpet = new String("\n" + "The CarpetId:\t\t" + getCarpetId() + "\nThe Area:\t\t" + area + "\nThe Unit Price\t\t" + unitPrice + "\nThe Total Price\t" + totalPrice + "\n\n");
return carpet;
}
public abstract void computeTotalPrice();
}
for the carpet,
public class RectangleCarpet extends Carpet{
private int height;
private int width;
public RectangleCarpet(String ID, double priceOf, int h, int w){
super(ID, priceOf);
height = h;
width = w;
computeTotalPrice();
}
public void computeTotalPrice(){
super.area = height * width;
super.totalPrice = unitPrice * area;
}
public String toString(){
String forThis = new String("\nThe Carpet Shape:\tRectangle\nThe Height:\t\t" + height + "\nThe Width:\t\t" + width +"\n");
return forThis + super.toString();
}
}
for one of the carpet shapes and
public class CircleCarpet extends Carpet{
private int radius;
public CircleCarpet(String ID, double priceOf, int rad){
super(ID, priceOf);
radius = rad;
computeTotalPrice();
}
public void computeTotalPrice(){
super.area = radius * radius * 3;
super.totalPrice = area * unitPrice;
}
public String toString(){
String forThis = new String("\nThe Carpet Shape:\tCircle\nThe radius:\t\t" + radius + "\n");
return forThis + super.toString();
}
}
for the other shape. The problem is the parseStringToCarpet is missing a return value, and I can't figure out what it needs to return, because if I try to return theCarpet it says it is the wrong type.
The calling class is
`import java.io.*; //to use InputStreamReader and BufferedReader
import java.util.*; //to use ArrayList
public class Menu
{
public static void main (String[] args)
{
char input1;
String inputInfo = new String();
String line = new String();
boolean found;
// ArrayList object is used to store carpet objects
ArrayList carpetList = new ArrayList();
try
{
printMenu(); // print out menu
// create a BufferedReader object to read input from a keyboard
InputStreamReader isr = new InputStreamReader (System.in);
BufferedReader stdin = new BufferedReader (isr);
do
{
System.out.println("What action would you like to perform?");
line = stdin.readLine().trim();
input1 = line.charAt(0);
input1 = Character.toUpperCase(input1);
if (line.length() == 1)
{
switch (input1)
{
case 'A': //Add Carpet
System.out.print("Please enter a carpet information to add:\n");
inputInfo = stdin.readLine().trim();
carpetList.add(CarpetParser.parseStringToCarpet(inputInfo));
break;
case 'C': //Compute Total Price For Each Carpet
for (int i=0; i<carpetList.size();i++)
((Carpet) carpetList.get(i)).computeTotalPrice();
System.out.print("total prices computed\n");
break;
case 'D': //Search for Carpet
System.out.print("Please enter a carpetID to search:\n");
inputInfo = stdin.readLine().trim();
found = false;
for (int i=0; i<carpetList.size();i++)
{
if (inputInfo.equals(((Carpet)carpetList.get(i)).getCarpetId()))
{
found = true;
}
}
if (found == true)
System.out.print("carpet found\n");
else
System.out.print("carpet not found\n");
break;
case 'L': //List Carpets
if (carpetList.isEmpty())
System.out.print("no carpet\n");
else
for (int i=0; i < carpetList.size(); i++)
System.out.print(carpetList.get(i).toString());
break;
case 'Q': //Quit
break;
case '?': //Display Menu
printMenu();
break;
default:
System.out.print("Unknown action\n");
break;
}
}
else
{
System.out.print("Unknown action\n");
}
} while (input1 != 'Q'); // stop the loop when Q is read
}
catch (IOException exception)
{
System.out.println("IO Exception");
}
}
/** The method printMenu displays the menu to a use **/
public static void printMenu()
{
System.out.print("Choice\t\tAction\n" +
"------\t\t------\n" +
"A\t\tAdd Carpet\n" +
"C\t\tCompute Total Price For Each Carpet\n" +
"D\t\tSearch for Carpet\n" +
"L\t\tList Carpets\n" +
"Q\t\tQuit\n" +
"?\t\tDisplay Help\n\n");
}
}
` I'm not allowed to edit the code of the calling class.
You always have to make sure all the paths in a method with returning value have a return in it or throw exception. In this case, you could add:
else {
return null;
}
to the last part of the method parseStringToCarpet, or just write return null at the end of the method.
The problem returning null is that a method that calls this function should know that it might return null, so you should document it.
Return a null object in the end which will be called when if-else condition is not met but make sure you do a not-null check when calling this
public class CarpetParser{
public static Carpet parseStringToCarpet(String lineToParse)
{
String delims = "[/]";
String[] info = lineToParse.split(delims);
if(info[0].equalsIgnoreCase("rectangle")){
double priceFor = Double.parseDouble(info[2]);
int height = Integer.parseInt(info[3]);
int width = Integer.parseInt(info[4]);
RectangleCarpet theCarpet = new RectangleCarpet(info[1], priceFor, height, width);
return theCarpet;
}else if(info[0].equalsIgnoreCase("circle")){
double priceFor = Double.parseDouble(info[2]);
int radius = Integer.parseInt(info[3]);
CircleCarpet theCarpet = new CircleCarpet(info[1], priceFor, radius);
return theCarpet;
}
return null;
}
As you declared the function as returning a Carpet, your class must return a Carpet (even if null).
When info[0] is neither circle or rectangle, your function does not return anything.
A quick fix is to either add a return null; at the end, or throw an exception (i.e. create InvalidArgumentException).
In the second case you must edit the calling class to handle the exception or throw it further up the stack though.