Having trouble with displaying boolean in Java - java

This is my first exercise with boolean. I need to display the output for car_Type whether it's a national car or imported car. The main class was already compiled successfully but when i run it and type in the input it says "Exception in thread "main" java.util.InputMismatchException". Here's the main class:
import java.util.Scanner;
public class CarApp
{
public static void main(String[] args)
{
//declaration
Scanner input = new Scanner(System.in);
String model, brand;
double price;
boolean type;
Car c = new Car();
System.out.println("Enter a car Model : ");//X70/Starex
model = input.nextLine();
System.out.println("\nEnter a car Brand : ");//Proton/Hyundai
brand = input.nextLine();
System.out.println("\nEnter the car price : RM");//95000.00/170000.00
price = input.nextDouble();
System.out.println("\nEnter the car brand [national/imported] : ");//national/imported car
type = input.nextBoolean();
//output
System.out.println("Car Model : "+model);
}
}
Also, here's the car class if you want to check on the error:
public class Car
{
String car_Model;
String car_Brand;
double car_Price;
boolean car_Type;
public Car()
{
car_Model = " ";
car_Brand = " ";
car_Price = 0.0;
car_Type = true;
}
public Car(String cm, String cb, double cp, boolean ct)
{
car_Model = cm;
car_Brand = cb;
car_Price = cp;
car_Type = ct;
}
void SetCar_Model(String cm){
car_Model = cm;
}
void SetCar_Brand(String cb){
car_Brand = cb;
}
void SetCar_Price(double cp){
car_Price = cp;
}
void SetCar_Type(boolean ct){
car_Type = ct;
}
String GetCar_Model()
{
return car_Model;
}
String GetCar_Brand()
{
return car_Brand;
}
double GetCar_Price()
{
return car_Price;
}
Boolean GetCar_Type()
{
return car_Type;
}
public String toString()
{
return "Car Model : " +car_Model + "\nCar Brand : " +car_Brand + "\nCar Price : " +car_Price + "Car Type : " +car_Type;
}
}
Here's the input:
Enter a car Model :
X70
Enter a car Brand :
Hyundai
Enter the car price : RM
95000.00
Enter the car brand [national/imported] :
national
And after i click enter it shows:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextBoolean(Scanner.java:1893)
at CarApp.main(CarApp.java:23)
Thank you for your help!

Java boolean data type, can only take the values true or false.

national can't be parsed as a boolean. You have to parse it yourself according to your logic. You could name the field for example isNational and set it to true if the user entered national and false if imported was entered. In your toString method you can then either return "imported" or "national" according to the boolean of isNational like so
isNational ? "national" : "imported"
this is called a ternary operator.
Also think about what should happen if the user enters neither one of those two choices.
You don't need to declare all your variables at the top of the method and then assign them below. Most of the time, if it's deterministic which value gets assigned you can assign it at the time of declaration.
And lastly: usually Java fields are written in camelCase. Take a look on Java naming conventions here.

Related

Using an ArrayList to display values from another class

I am trying to make a to do list that asks you to enter your tasks one by one then display them in order (as in 1. task1, 2. task 2, 3. task 3 etc). But when it displays the tasks it comes back as "0. null" one time instead of listing any of the tasks entered. Here is the script I am using:
1st class
package todolist;
import java.util.ArrayList;
public class ToDoList1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<ToDoList2> list = new ArrayList<ToDoList2>();
System.out.println("Time to make a digital to-do list!");
ToDoList2 n = new ToDoList2();
list.add(n);
System.out.println(ToDoList2.name + "'s to-do list");
System.out.println(ToDoList2.i + ". " + ToDoList2.l);
for(ToDoList2 enhanced : list)
{
System.out.println(ToDoList2.i + ". " + ToDoList2.m);
}
}
}
2nd class
package todolist;
import java.util.Scanner;
public class ToDoList2 {
public static String name;
public static int i;
public static String l;
public static String m;
{
Scanner s = new Scanner(System.in);
System.out.println("First type your name to identify your list in case you lose it");
name = s.nextLine();
System.out.println("Make sure to type \"end\" when you are finished");
System.out.println("Type in the first item on your to-do list");
String l = s.nextLine();
}
public ToDoList2()
{
Scanner s = new Scanner(System.in);
for(int i = 1; i == i; i++)
{
System.out.println("Type in the next item for your to-do list");
String m = s.nextLine();
if("end".equals(m))
{
break;
}
}
}
}
Your code is not correct. ToDoList2 scanning item list from standard input but not storing it. You should do as follow
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class TodoList {
public static String name;
List<String> tasks;
public TodoList(String name) {
this.name = name;
this.tasks = new ArrayList<>();
}
public void addTask(String task) {
this.tasks.add(task);
}
public String toString() {
int i = 1;
StringBuilder stringBuilder = new StringBuilder();
for (String task : tasks) {
stringBuilder.append(i + ". " + task);
stringBuilder.append("\n");
i++;
}
return stringBuilder.toString();
}
}
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("First type your name to identify your list in case you lose it");
String name = s.nextLine();
System.out.println("Make sure to type \"end\" when you are finished");
System.out.println("Type in the first item on your to-do list");
TodoList todoList = new TodoList(name);
String task = null;
while (!(task = s.nextLine()).equals("end")) {
todoList.addTask(task);
System.out.println("Type in the next item for your to-do list");
}
System.out.println(todoList);
}
}
a) Given that each ToDoList2 object is a separate task, I'm not sure why you've made the object class members static?
b) In your ToDoList2 constructor, you've got a for loop that introduces a local variable i which hides the ToDoList2 member variable i. You'd do well to change one of the variable names.
c) In your ToDoList2 constructor, you've got a for loop which is assigning a string returned by the Scanner to a local variable m. Are you sure you want m to be a local variable or do you actually want to assign the returned string to the member variable, m? I'm thinking the latter since the member variable m is never being assigned a value which explains why the code is printing out null.
d) When writing code, it is good practice to use meaningful variable names. Using names like i is OK as an index in a loop but in all other circumstances, you should go for something more descriptive that tells the reader what the variable is storing.
e) Consider making all your ToDoList2 member variables private (and final if possible). Add a print function to the ToDoList2 class to print out the task details. A key principle is Object Oriented Programming is to hide the internals of a class.

JAVA. How to create method with variable from another scope in Java

I've started writing my own Java program during my freetime called the "Book A Ticket Machine", it's a Java console program with no GUI. It will Ask you for your FullName, FrequentFlyer ID, Age, then match you to your designated airline and flight number. While you travel your fuel will decrease and when it lands the fuel will fill up (I will create a fill method for this). I am having problems with calling a method from outside a scope.
Currently I have two files:
Flights.java --> Launching file. Linked with flightUserDatabase.
flightUserDatabase.java --> Contains all methods and class/blueprints all username, age, frequentFlyer, etc.
Code from Flights.java:
import java.io.Console;
public class Flights {
public static void main (String[] args) {
Console console = System.console();
//Book a Ticket Machine
//From Database otherwise Name not found on Database. Put Database in Another Class. Call it flightUserDatabase.
/* firstName: DONE
lastName: DONE
frequentFlyerID: Otherwise Invalid Number parseInt
Age: parseInt
FUEL MINUS AND FUEL ADD WHEN LAND.
*/
flightUserDatabase database = new flightUserDatabase();
System.out.println("Enter Creditials: ");
database.getDatabase();
String airline = console.readLine("ENTER YOUR AIRLINE: ");
String flightNumber = console.readLine("ENTER YOUR FLIGHT NUMBER: ");
String gate = "B7"; /* Declare data type String called "gate" */
//Next Version, Generate Random Number
System.out.println("This is an automated system. Please Wait...");
System.out.printf("%s %s is Departuring # Gate:%s \n", airline, flightNumber, gate); /* Use printf from java.io.Console library, then output Gate and Flight Number */
/* Notes: Data Types
> String name = "Ohm";
> int age = 42;
> double score = 95.5;
> char group = 'F';
*/
}
}
Code from flightUserDatabase.java:
import java.io.Console;
//Book a Ticket Machine
class flightUserDatabase {
Console console = System.console();
public String fullName;
public boolean getDatabase() {
boolean namesInDatabase;
do {
fullName = console.readLine("ENTER YOUR FULLNAME: ");
namesInDatabase = (fullName.equals("Ohm Passavudh") || fullName.equals("Matt"));
if (!namesInDatabase) {
console.printf("Sorry, that name is not in our database yet. \n");
}
if (namesInDatabase) {
console.printf("Welcome, Mr. %s \n", fullName);
}
} while(!namesInDatabase);
return namesInDatabase;
}
//If Ohm: FFID = 1234569
//If Matt: FFID = 246810
//FFID == FrequentFlyerID
/* Get name from inside scope fullName namesInDatabase variable */
public boolean frequentFlyerID()
I HAVE PROBLEMS HERE!!! I WANT TO SET Ohm's FFID to 1234569. But how to I determine if the user enters Ohm or Matt. I cannot access the String fullName from the other scope. I hope you understand me. If there is any misunderstanding I can clarify.
}
First, please, do work on your formatting, reading that code was awful.
You can create a class field and a getter in flightUserDatabase, so you can get the name after you've determined the name is in the database.
Or you can return it with getDatabase()
Like this...
public String getDatabase()
{
String fullName;
...
return fullName;
}
After all, you're not using that boolean.
... or this ...
class flightUserDatabase
{
private String fullName = "";
...
public String getName()
{
return this.fullName;
}
}
You have to initialize variable public String fullName; -> public String fullName = "";
Work on formating code
Name class begin from upper sign in your case FlightUserDatabase
Remember about encapsulation (private variable)

object java class code

These are the instructions for this assignment. Any help would be appreciated. I am a rookie when it comes to java and cant seem to figure this out.
This exercise has two classes. The first class is named ObjectsToArrayList. The second class is called just Objects.
Your responsibility is to create the Object class and figure out how the ObjectsToArrayList class works.
The ObjectsToArraylist class will create an ArrayList of objects. It will ask for and populate the data fields of an Object, then add it to the ArrayList. This can be done for as many instances of the Object that the user wants to enter.
Requirements for the Object Class.
2 data fields: int obj_id, String obj_name.
2 Constructors: No-Arg and one that takes both values and assigns them to the data field.
Gets and sets for both data fields
A toString() method that returns output like:
The object ID is 22 and the name is Andrea
Here's my code
import java.util.*;
/**
*
* #author Student
*/
public class ObjectsToArrayList {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList <Object> objectList = new ArrayList();
System.out.println("Please enter information for your favorite object!");
do { // collect an indicator to determine the method to call
Object object = new Object();
System.out.println("Enter a whole number for the ID of your object:\n"
+ "or enter 99 to quit.");
int tmpInt = input.nextInt();
// if 99 is entered exit the loop.
if (tmpInt == 99) {
break;
}
object.setObj_id(tmpInt);
input.nextLine();
// ask for the Object Name
System.out.println("Please enter the name of the Object:");
object.setObj_name(input.nextLine());
objectList.add(object);
} while (true); // this is a contineous loop if the break isn't included.
for(Object object:objectList) {
System.out.println(object.toString());
}
}
}
//****************************************************
//**** Objects Class is below this block **
//****************************************************
class Object {
// enter object code here (This is the part I cannot figure out)
}
Here are examples of constructors:
class Objects{
// This is a constructor with no argument
public Objects(){
}
// This is a constructor with 2 arguments
public Objects(int obj_id, String obj_name){
}
}
You can refer in the link below to learn more about creating constructors and assigning values to fields:
http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
Note: Do not use Object as a class because Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.
http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html
Try something like this:
public class ObjectsToArrayList {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList <Object> objectList = new ArrayList();
System.out.println("Please enter information for your favorite object!");
do { // collect an indicator to determine the method to call
Object object = new Object();
System.out.println("Enter a whole number for the ID of your object:\n"
+ "or enter 99 to quit.");
int tmpInt = input.nextInt();
// if 99 is entered exit the loop.
if (tmpInt == 99) {
break;
}
object.setObj_id(tmpInt);//runs the setObj_id method in the Objects class
//for the users input
input.nextLine();
// ask for the Object Name
System.out.println("Please enter the name of the Object:");
object.setObj_name(input.nextLine());//runs the setObj_name method in the Objects class
//for the users input
objectList.add(object);
} while (true); // this is a contineous loop if the break isn't included.
for(Object object:objectList) {
System.out.println(object.toString());//prints out what the toString method returns in
//the Objects class
}
}
}
//****************************************************
//**** Objects Class is below this block **
//****************************************************
public class Objects
{
//add stuff like methods and instance variables
private int ID;
private String name;
public Objects(){//default constructor
}
public Objects(int i, String n){//constructor to change both ID and name at the same time
ID = i;
name = n;
}
public void setObj_id(int i){//constructor to change only ID
ID = i;
}
public void setObj_name(String n){//constructor to change only name
name = n;
}
public String toString(){
return (name + ": " + ID);
}
}
Ok so you want to create your own object soo have 2 classes rather, personProfile and arrayOfProfiles
So class personDetails object note seperate class file not *not in same file
class personProfile{
private int ID = 0;
private String Name = "";
public personProfile(int id,String name){
ID = id;
Name = name;
}
public int getID(){
return ID;
}
public String getName(){
return name;
}
}
now the other class* different file
class arrayOfProfiles{
personProfile profiles[] = new personProfile[0];
public personProfile[] array(){
return profiles;
}
public void addProfileToArray(personProfile profileObject){
personProfile arrayMod = new personProfile[profiles.length+1];
for(int i = 0;i<profiles.length;i++){
arrayMod[i] = profiles[i];
}
arrayMod[arrayMod.length-1] = profileObject;
}
public static void main(String args[]){
arrayOfProfiles profiles = new arrayOfProfiles();
for(int i = 0;i<5;i++){
int id = Integer.parseInt(JOptionPane.showInputDialog("enter ID ");
String name = JOptionPane.showInputDialog("enter name");
profiles.addProfileToArray(new personProfile(id,name));
}
for(int i =0;i<profiles.array().length;i++){
System.out.println("ID :"+profiles[i].getID()+" name - "+profiles[i].getName());
}
}
}

Why aren't my methods returning the String?

I am using a program class to try to test the methods in my object class to see if they work. It is a gas meter reading system and I am trying to deposit money to pay off some of the balance of what the customer owes.
My object class consists of:
package GasAccountPracticeOne;
public class GasAccountPracticeOne
{
private int intAccRefNo;
private String strName;
private String strAddress;
private double dblBalance = 0;
private double dblUnits;
private double dblUnitCost = 0.02;
public GasAccountPracticeOne(int intNewAccRefNo, String strNewName, String strNewAddress, double dblNewUnits)
{
intAccRefNo = intNewAccRefNo;
strName = strNewName;
strAddress = strNewAddress;
dblUnits = dblNewUnits;
}//end of constructor
public GasAccountPracticeOne( int intNewAccRefNo, String strNewName, String `strNewAddress)
{
intAccRefNo = intNewAccRefNo;
strName = strNewName;
strAddress = strNewAddress;
}//end of overloading contructor
public String deposit(double dblDepositAmount)
{
dblBalance = dblBalance - dblDepositAmount;
return "Balance updated";
}
In my program class I have written:
System.out.println("Enter deposit amount");
dblDepositAmount=input.nextDouble();
firstAccount.deposit(dblDepositAmount);
But in my object class in the deposit method I have asked for a string saying return "Balance updated" to be returned.
When I run the test there is no string returned. Banging my head off the table - have I done something ridiculous?
You did nothing to print your string:
1- use your output and print it:
System.out.println("Enter deposit amount");
dblDepositAmount=input.nextDouble();
String myString = firstAccount.deposit(dblDepositAmount); //<-- you store your string somewhere
System.out.println(myString ); // you print your String here
System.out.println(firstAccount.deposit(dblDepositAmount)); // Or you can show it directly
2- You can also make your method print the value
public void deposit(double dblDepositAmount)
{
dblBalance = dblBalance - dblDepositAmount;
System.out.println("Balance updated");
}
So when you call it, it will print by itself (returning a String value is useless in your case).
This line of code discards the result of invoking deposit method, therefore you do not see that string:
firstAccount.deposit(dblDepositAmount);
Try the following instead:
System.out.println(firstAccount.deposit(dblDepositAmount));

Need someone to check my Program, I think my equals method is wrong

I am done with this assignment think god, and was wondering if someone could please check it so I can make sure there are no errors, it seems like I work hard on these programs but always doing something wrong. I am doing this course online so I have a hard time communicating with the instructor. I think my equals to methods might be wrong but, they seem to have no error when running the program and the program is 100% done. Please take the time to look over it, and thank you so much for your time.
Assignment:
About the first class
Create a class named RoomDimension that has two fields: one for the length of the room and another for the width. The RoomDimension class should have two constructors: one with no parameters (a default) and one with two parameters. The class should have all of the appropriate get and set methods, a method that returns the area of the room, a toString method that will allow us to print the length, width and area of the room and an equals method to compare room dimensions.
About the second class
Create another class named RoomCarpet that has two fields: one is a RoomDimension object and the other is a field that holds the cost of carpet per square foot. The class should have two constructors: one with no parameters and one with the two field parameters (RoomDimension and double). The class should have a get and set method for each field, a method that returns the total cost of carpeting the room, a toString method that will print all of the room information (length, width, area) and cost of the carpet per square foot and the total cost to carpet the room. (Dollar amounts should be displayed with two decimal places.), and an equals method that compares room dimensions and carpet cost.
About the application program
Write an application program that contains one RoomDimension object and one RoomCarpet object. The program should allow the user to enter the length and width of the room and the cost of the carpet per square foot. The program should instantiate both objects and use a simple System.out.println statement to print all of the information about the RoomCarpet object.
MY code:
import java.text.DecimalFormat;
public class RoomCarpet {
private RoomDimension rmSize;
private double pricePerSqFt;
//default constructor
public RoomCarpet()
{
this.rmSize = new RoomDimension();
this.pricePerSqFt = 0.00;
}
//parameters constructor
public RoomCarpet(RoomDimension rmSize, double pricePerSqFt)
{
this.rmSize = new RoomDimension(rmSize.getRmLength(),rmSize.getRmWidth());
this.pricePerSqFt = pricePerSqFt;
}
//accessor methods
public RoomDimension getRmSize()
{
return new RoomDimension(rmSize.getRmLength(),rmSize.getRmWidth());
}
public double getPricePerSqFt()
{
return this.pricePerSqFt;
}
// mutator methods
public void setRmSize(RoomDimension rmSize)
{
this.rmSize = new RoomDimension(rmSize.getRmLength(), rmSize.getRmWidth());
}
public void setPricePerSqFt(double pricePerSqFt)
{
this.pricePerSqFt = pricePerSqFt;
}
// Or price for the room to be carpeted
public double rmTotalCost()
{
return rmSize.getAreaRoom() * pricePerSqFt;
}
//toString method
public String toString()
{
DecimalFormat dollar = new DecimalFormat("$#,##0.00");
String str = this.rmSize.toString() + " Price per sq. ft : " +dollar.format(pricePerSqFt) + " Price to carpet Room: " + dollar.format(rmTotalCost()) + '\n';
return str;
}
public boolean equals(RoomCarpet object2)
{
boolean status;
if ((this.equals(object2)==true)&&(this.pricePerSqFt==object2.pricePerSqFt))
status = true;
else
status = false;
return status;
}
}
public class RoomDimension {
private int rmLength;
private int rmWidth;
//Default constructor
public RoomDimension()
{
rmLength=0;
rmLength=0;
}
// constructor with parameters
public RoomDimension(int rmLength, int rmWidth)
{
this.rmLength=rmLength;
this.rmWidth=rmWidth;
}
// accessor methods
public int getRmLength()
{
return this.rmLength;
}
public int getRmWidth()
{
return this.rmWidth;
}
//mutator methods
public void setRmLength(int rmLength)
{
this.rmLength=rmLength;
}
public void setRmWidth(int rmWidth)
{
this.rmWidth =rmWidth;
}
//area of the room
public int getAreaRoom()
{
return this.rmLength * this.rmWidth;
}
//toString Method
public String toString()
{
String str = "Room Length: " + this.rmLength + " Room Width: " + this.rmWidth + " Area of Room: " + this.getAreaRoom();
return str;
}
public boolean equals(RoomDimension object2)
{
boolean status;
if (this.getAreaRoom() == object2.getAreaRoom())
status = true;
else
status = false;
return status;
}
}
import java.util.Scanner;
public class CarpetPrice {
public static void main(String[] args)
{
RoomDimension rmSize;
RoomCarpet rmCarpet;
Scanner keyboard = new Scanner(System.in);
rmSize=new RoomDimension();
System.out.println(" Please enter the length of the room: ");
int rmLength= keyboard.nextInt();
rmSize.setRmLength(rmLength);
System.out.println("Please enter the rooms width: ");
int rmWidth = keyboard.nextInt();
rmSize.setRmWidth(rmWidth);
System.out.println("Please enter the price per sq foot: ");
double pricePerSqFt = keyboard.nextDouble();
rmCarpet = new RoomCarpet(rmSize, pricePerSqFt);
System.out.println("\n"+rmCarpet.toString());
}
}
The equals method must have an Object argument and you have to override the hashCode method too.
#Override
public boolean equals(Object obj)
{
}
I would say that for RoomDimension, two objects are equal only if both length and width match. Especially if you're laying carpet, a 4x5 room would be much different from a 1x20 hallway, even though the total area is the same. For the RoomCarpet object, again equal only if both the dimensions are equal and the price is the same, I guess.
Also, I would write some tests because you may be surprised at what happens when you call RoomCarpet's .equals() method (as written above).
Finally, pay attention to your indenting because that's important for any reader of your code.

Categories

Resources