I am trying to make a class and a separate printer class for post cards. The idea is to make a postcard that can take user inputs for sender, recipient, and occasion. Then add in something that allows us to send the same postcard to another friend. This is my post card class
public class Postcard
{
private String message;
//define other variables that you need in this class
private String sender;
private String recipiant;
private String occasion;
private String print;
// Methods go here
public Postcard()
{
String message = "Happy holidays too ";
String sender = "Michael";
String recipiant = "";
String occasion = "";
}
public void setmessage(String m)
{
this.message = m;
}
public void setSender(String s)
{
this.sender = s;
}
public void setRecipiant(String r)
{
this.recipiant = r;
}
public void setOccasion(String o)
{
this.occasion = o;
}
public String print()
{
print = message + sender + recipiant + occasion;
return print;
}
}
and this is the post card print class
import java.util.Scanner;
public class PostcardPrinter
{
public static void main(String[] args)
{
String text = "Happy Holiday to ";//write your msg here
Postcard myPostcard = new Postcard(); // use the constructor method
//use the mutator method to set the name of the recipient
Scanner op = new Scanner(System.in);
String recipant = op.nextLine();
String sender = op.nextLine();
String occassion = op.nextLine();
myPostcard.print();
//write the code to send the same msg to another friend
System.out.println("Do you want to send another? Type 'yes' or 'no' ");
String choice = op.nextLine();
while (choice != no)
{
String text = "Happy Holiday to ";
Postcard myPostcard = new Postcard();
Scanner op = new Scanner(System.in);
String recipant = op.nextLine();
String sender = op.nextLine();
String occassion = op.nextLine();
}
}
}
Error's appear in the while loop saying that varriable no doesn't exist and when commented out, nothing happens. Virtual machine is running, but nothing happens. Any help would be greatly appreciated
The line:
while (choice != no)
Is looking for a variable called no, not a string constant. You want:
while (!choice.equals("no"))
Or, the case-insenstive method:
while (!choice.equalsIgnoreCase("no"))
One thing to point out - since the value of choice never changes once inside the loop, you'll basically be looping forever. You'll probably want to ask again after each iteration of the loop. You can probably just set the initial value of choice to an empty string, then immediately start the loop when the program begins. This would allow you to remove the redundant code above the loop.
Related
i thinkj i have a type argument problem which im really confused about, Ive started with an Arraylist which, extends to the another class with my main methods. and i have a Events class, which i want to categorize from the txt file, the main problem i have is adding from my txt file which iread into an ArrayList, java pops up with this error message
incompatible types: java.lang.String cannot be converted to CSC8012.Events
But in my events it has String? Im really confused
This is my generic arraylist i think?
import java.util.ArrayList;
public class SortedArrayList<E extends Comparable> extends
ArrayList<E> {
public void insert(E e) {
this.add(e);
int lastIndex = 0;
for( lastIndex = this.size() -1 ; lastIndex > 0 && this.get(lastIndex-1).compareTo(e) > 0 ; lastIndex--){
this.set(lastIndex, this.get(lastIndex-1));
}
this.set(lastIndex,e);
}
}
Heres my events class objects
public class Events implements Comparable<Events>{
//fields setting up the variables
String ticketsbought;
String eventname;
public Events(String ticketsbought, String eventname ){
this.ticketsbought = ticketsbought;
this.eventname = eventname;
}
#Override
public int compareTo (Events E){
return
ticketsbought.compareTo(E.getTicketsbought()) + eventname.compareTo(E.getEventname());
}
public String getTicketsbought() {
return ticketsbought;
}
public String getEventname() {
return eventname;
}
//setting it up for the main method from the constructor fields above
public void setTicketsbought(String ticketsbought) {
this.ticketsbought = ticketsbought;
}
public void setEventname(String eventname) {
this.eventname = eventname;
}
#Override
public String toString()
{
return "Tickets bought " + this.ticketsbought + "Event name " + this.eventname;
}
}
My main menu class
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Objects;
import java.util.ArrayList;
import java.util.Collections;
java.util.Scanner;
public class MainProgram extends SortedArrayList{
public static void main(String[] args) throws FileNotFoundException{
boolean bye = false;
String line;
String option;
Scanner sc = new Scanner(System.in); //tos take in our input
do{
System.out.println("Choose an option.."); // heres our options
System.out.println("e Information on all events");
System.out.println("c All information on clients");
System.out.println("f to quit");
System.out.println("b to update when tickets are bought by a registered Client");
System.out.println("r to update the stored data when a Client cancels a ticket");
option = sc.nextLine();
switch (option) { // these are splitting our inputs to these cases with different outcomes
case "e":
//System.out.println("information on events");
Scanner inFile = new Scanner(new FileReader("input.txt"));
// Other declarations// Reading and processing the input data// Printing out the results outFile.close();
ArrayList<Events> events = new ArrayList<>();
while(inFile.hasNextLine()) {
String data = inFile.next();
events.add(data);//error based on these? Event is based off of arraylist<E> and inherits from those whilst i have them as string?
You are seeing the exception because of Generics in Java.
Your ArrayList is declared to take Events objects.
ArrayList<Events> events = new ArrayList<>();
However, you are trying to add a String object to it.
String data = inFile.next();
events.add(data); //Cannot add a String object, only Events object allowed.
One way to fix this is to create an Events object using the String, and then add to the Arraylist. I am assuming each line has Event name and String in it, separated by a comma.
//Get your event name and tickets from the String data.
String tokens[] = data.split(",");
String eventName = tokens[0];
String ticketsBought = tokens[1];
//create an events object
Events eventObj = new Events(eventName, ticketsBought);
//Now add to your arraylist.
events.add(eventObj);
As an aside, you do not need to extend SortedArrayList in MainProgram. The main class is usually top level class in your project, and it will only contain objects (this is a common practice). If you want to use the new logic you have added in SortedArrayList, then instead of creating ArrayList<Events> events = new ArrayList<>();, you can create SortedArrayList<Events> events = new SortedArrayList<>();
import java.util.Scanner;
class BloodData{
static Scanner in = new Scanner(System.in);
static String bloodType;
static String rhFactor;
public BloodData(){
bloodType = "O";
rhFactor = "+";
}
public BloodData(String bt, String rh){
bloodType = bt;
rhFactor = rh;
}
public void display() {
System.out.println(bloodType+rhFactor+" is added to the blood bank");
}
public static void main(String[]args) {
System.out.println("Enter Blood Type(O, A, B, AB)");
System.out.println("Enter rhFactor('+' or '-')");
BloodData bd= new
BloodData(BloodData.bloodType=in.nextLine(),BloodData.rhFactor=in.nextLine());
BloodData bd1= new BloodData();
bd.display();
}
}
How can i use the constructor with 2 String parameters? because when I always run the code the first one only run. I'm only a beginner so hope someone could help because I already watched a lot of Youtube vids and I really didn't know why this happens
Java doesn't use named parameters like this for method or constructors. I would be surprised if a video showed such syntax...
new BloodData(BloodData.bloodType=in.nextLine(),BloodData.rhFactor=in.nextLine())
You need to define String variables on the line above, then pass them into the constructor. You also shouldn't be combining instance constructors with static variables
class BloodData{
private String bloodType;
private String rhFactor;
public BloodData(String type, String rhFactor) {
this.bloodType = type;
this.rhFactor = rhFactor;
}
...
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String x = in.nextLine();
String y = in.nextLine();
BloodData bd = new BloodData(x, y);
}
if you want to call a constructor having two parameters: Use this
BloodData blooddata = new BloodData("A","+");
simply i have this file reading it and storing it into array and then want to call the values back later to print them
my text file
`101
12-7-2017
14-7-2017
some name
00000.. phone number
520
29-8-2017
1-9-2017
some name
00000.. phone number
1020
30-12-2017
1-1-2018
some name
00000.. phone number`
this the main test code
public class test {
public static void main(String[] args) throws ParseException, FileNotFoundException{
Scanner res = new Scanner (new File("reservations.txt"));
int z=0;
do{
int room_numb = res.nextInt();
String cInr=res.next();
String cOutr=res.next();
String Fname=res.next();
String Lname=res.next();
String phone_numb=res.next();
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
Date cIn = df.parse(cInr);
Date cOut = df.parse(cOutr);
Reservation.reserv[z]=new Reservation (room_numb, cIn, cOut, new Guest(Fname, Lname, phone_numb));
z=z+1;
}while(res.hasNext()==true);
Guest FLnames=Reservation.reserv[0].getguest();
System.out.println(FLnames);
}
my classes are these 3
reservation
public class Reservation {
static Reservation[] reserv= new Reservation[200];
Guest guest;
int room_numb;
Date in, out;
public Reservation(int room_numb, Date in, Date out, Guest g) {
this.room_numb = room_numb;
this.in = in;
this.out = out;
g= guest;
}
public int getroom_numb(){
return room_numb;
}
public Date getin(){
return in;
}public Date getout(){
return out;
}public Guest getguest(){
return guest;
}
Room
public class Room {
int room_numb;
String indate;
public void setRoom(int i) {
room_numb =i;
}
public int getRoom(){
return room_numb;
}
and guest
public class Guest {
String Fname;
String Lname;
String phone_number;
public Guest(String fname, String lname, String phone_numb ){
Fname=fname;
Lname=lname;
this.phone_number=phone_numb;
return;
}
public String getFname(){
return Fname;
}
public String getLname(){
return Lname;
}
public String getphone_number(){
return phone_number;
}
}
i have been able to get all variables such as room numb/checkin date and checkout date/ but when ever i ask for guest through
Guest FLnames=Reservation.reserv[0].getguest();
System.out.println(FLnames);
it gives me null which mean it doesn't reference to anything
so i am not able to use String Fname=Reservation.reserv[0].getguest().getFname();
so how to get the data from guest in reservation array?
Note: i am new to java so be gentle with ma please :) also the sysout is just for testing in the main method
Thanks :).
I'm not going to fix your code for you. Doing that is part of your homework. However, here are a couple of hints to start you in the right direction.
Hint: Look carefully at how your Reservation constructor (tries to) initialize the object's fields. See the problem?
Hint 2: The problem that tripped you up is that getguest() is returning null .......
While I have your attention, there are numerous style errors in your code, but the worst is your complete disregard of the Java converions for identifier names:
A class name must start with a capital letter and be in camel-case: Test not test.
A method or variable name must start with a lower case and be in camel-case; e.g. getGuest not getguest.
We don't need or use "hungarian" notation in Java. The type of a variable is expressed in the type declaration.
Your choice of variable names is inconsistent and "uninspired".
And "numb" is what happens when your fingers get cold.
Having trouble trying to get my program to work for my AP Computer Science class. Comments have been made inside the code to show my problem. Thanks guys/gals.
Java Class
import java.util.*;
public class Allosaur extends Dinosaur
{
private boolean hungry;
private String response, answer;
private String Allosaur;
// Prompt asks for 3 constructors: A Default constructor, a constructor with just a name, and a constructor with a name and hunger "response"
public Allosaur()
{
}
public Allosaur(String name)
{
Allosaur=name;
}
public Allosaur(String name, boolean hungry)
{
Allosaur=name;
this.hungry=hungry;
}
// Used this method to "find out" whether the dinosaur is hungry or not
public boolean getHunger()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Are you hungry? ");
response = keyboard.next();
if(response.equals("Yes"))
hungry = true;
else if(!response.equals("Yes"))
hungry= false;
return hungry;
}
// Asks us to print out "RRRRRRR" if the dinosaur is NOT hungry and "HUNGRRRRRRRY" if the dinosaur IS hungry
public String roar()
{
if(hungry == true)
answer = "HUNGRRRRRRRY";
else if(hungry == false)
answer = "RRRRRRR";
return answer;
}
//When I use the toString() method in my driver class, none of these pop up, why?
public String toString()
{
String Dino = super.toString();
Dino = "The Dinosaur's name is: " + Allosaur;
Dino += "Is the Dinosaur hungry? :" + getHunger() + "\n" + roar();
return Dino;
}
}
And here is my Driver Class:
public class DinosaurMain extends Allosaur
{
public static void main(String[] args)
{
Allosaur Dino = new Allosaur("Jacob");
Dino.toString();
}
}
I'm very confused as to why nothing will show up when I run the program.
Nothing shows up after the String input is requested because you're simply doing the call in DinosaurMain as Dino.toString(). This just makes the String representation for your object. It doesn't print that String representation out. If you were to change it to System.out.println(Dino.toString()); you would see the result.
So i've been messing around with String data types in the constructor of my class file, and while everything compiles correctly, when I run the application file, the program doesn't give the desired result. I kept it short to see if it would work, so my class file is as follows:
public class StringPractice
{
private String color;
private String brand;
public StringPractice() {
String color = "";
String brand = "";
}
public StringPractice(String clor, String brnd) {
setColor(clor);
setBrand(brnd);
}
public void setColor(String clor) {
if (clor.equalsIgnoreCase("Red")) {
color = clor;
}
else {
System.out.println("We dont't carry that color");
}
}
public void setBrand(String brnd) {
if (brnd.equalsIgnoreCase("Gibson")) {
brand = brnd;
}
else {
System.out.println("We do not carry that brand");
}
}
public String getColor() {
return color;
}
public String getBrand() {
return brand;
}
public void display() {
System.out.println("Our brands are: " + brand + "Our colors are: " + color);
}
My application file is as follows:
import java.util.Scanner;
public class UseStringPractice
{
public static void main(String[] args)
{
String brand = "";
String color = "";
Scanner keyboard = new Scanner(System.in);
StringPractice Guitar1;
System.out.println("Please enter the brand you would like");
brand = keyboard.next();
System.out.println("Please enter the color you would like");
color = keyboard.next();
Guitar1 = new StringPractice(brand, color);
Guitar1.display();
}
}
What am I doing incorrectly? Am I using the wrong methods to parse the information from scanner? Or am I using equalsIgnoreCase incorrectly? This is my first attempt at implementing these methods, so I may be wayyy off for all I know. When I run the application class, my result is that of the trailing else clause, or, "We do not carry those brands" or "We don't carry that color". Then, in my display statement, the variable names are replaced with "null". This is all for practice so any insight would be fantastic. Thanks!
Your arguments being passed to your constructor should be flipped.
In your application:
Guitar1 = new StringPractice(brand, color);
but in your code:
public StringPractice(String clor, String brnd) {