Pass user input value from class to class on Java - java

I am working on the parking ticket simulator of the starting out with Java book, so the idea is to ask the user to input the officer's name, officer's badge number and some other other information, I have that information in the class ParkingCarSimulator class located on ParkingCarSimulator.java,
All of that is working fine, now in class called PoliceOfficer located in PoliceOfficer.java file, I would like to know if I can access the user input from the main method in the ParkingCarSimulator into the PoliceOfficer class.
Any ideas will be appreciated, here is the code I have:
import java.util.Scanner;
public class ParkingCarSimulator {
public static void main(String[] arsg)
{
String officerName, Make, carModel, carColor, carLicense;
int badgeNumber, minOnCar, minPurchased;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the officer's name");
officerName = keyboard.nextLine();
System.out.println("Enter the officer's badge number");
badgeNumber = keyboard.nextInt();
System.out.println("Enter the car's make");
Make = keyboard.nextLine();
System.out.println("Enter the car's model");
carModel = keyboard.nextLine();
System.out.println("Enter the car's color");
carColor = keyboard.nextLine();
System.out.println("Enter the car's liscence number");
carLicense = keyboard.nextLine();
System.out.println("Enter minutes on car");
minOnCar = keyboard.nextInt();
System.out.println("Enter the number of minutes purchased");
minPurchased = keyboard.nextInt();
}
}
Here is PoliceOfficer.java
public class PoliceOfficer
{
String policeName = ParkingCarSimulator.officerName;(this throws an error)
}

To create a PoliceOfficer, you need to give it a constructor then instanciate it in the main code
public class PoliceOfficer{
String policeName;
int badgeNumber;
public PoliceOfficer(String policeName, int badgeNumber){
this.policeName = policeName;
this.badgeNumber = badgeNumber;
}
}
use
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the officer's name");
String officerName = keyboard.nextLine();
System.out.println("Enter the officer's badge number");
int badgeNumber = keyboard.nextInt();
PoliceOfficer po = new PoliceOfficer(officerName, badgeNumber);
}

Related

Learning Java, why is the scanner printing two of the questions on the same line?

import java.util.Scanner;
public class MadLibs {
public static void main(String[] args) {
String name, place, college, profession, animal, petName;
int number;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a name: ");
name = keyboard.nextLine();
System.out.print("Enter a number: ");
number = keyboard.nextInt();
System.out.print("Enter a place: ");
place = keyboard.nextLine();
System.out.print("Enter a college: ");
college = keyboard.nextLine();
System.out.print("Enter a profession: ");
profession = keyboard.nextLine();
System.out.print("Enter a animal: ");
animal = keyboard.nextLine();
System.out.print("Enter a pet name: ");
petName = keyboard.nextLine();
keyboard.close();
}
}
console results
Can't figure out why "enter a college" and "enter a place" are printing on the same line and not acting as separate inputs.
Try below snippet it will definitely work :
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a name: ");
String name = keyboard.nextLine();
System.out.print("Enter a number: ");
int number = keyboard.nextInt();
System.out.print("Enter a place: ");
keyboard.next();
String place = keyboard.nextLine();
System.out.print("Enter a college: ");
keyboard.next();
String college = keyboard.nextLine();
System.out.print("Enter a profession: ");
String profession = keyboard.nextLine();
System.out.print("Enter a animal: ");
String animal = keyboard.nextLine();
System.out.print("Enter a pet name: ");
String petName = keyboard.nextLine();
}
The nextLine() method of java.util.Scanner class advances this scanner past the current line and returns the input that was skipped. This function prints the rest of the current line, leaving out the line separator at the end.
enter code here
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String name, place, college, profession, animal, petName;
int number;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a name: ");
name = keyboard.nextLine();
System.out.print("Enter a number: ");
number = keyboard.nextInt();
System.out.print("Enter a place: ");
place = keyboard.nextLine();
keyboard.nextLine(); //brings to next line
System.out.print("Enter a college: ");
college = keyboard.nextLine();
System.out.print("Enter a profession: ");
profession = keyboard.nextLine();
System.out.print("Enter a animal: ");
animal = keyboard.nextLine();
System.out.print("Enter a pet name: ");
petName = keyboard.nextLine();
keyboard.close();
}
}

How can I question the user if they want to add a new record for a file?

My code simply asks the user to enter data for a file. I want to ask them every time if they want to add a new record before doing the process. Following is my code.
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Assign11 {
public static void main(String[] args) throws IOException{
Scanner keyboard = new Scanner (System.in);
System.out.println("enter FILE name");
String FileName = keyboard.nextLine();
FileWriter fwriter = new FileWriter(FileName);
PrintWriter StudentFile = new PrintWriter(fwriter);
String name = "";
int age = 0;
double gpa = 0.0;
String answer = "";
do {
System.out.println("Enter name.");
name = keyboard.nextLine();
System.out.println("Enter age.");
age = keyboard.nextInt();
keyboard.nextLine();
System.out.println("Enter GPA.");
gpa = keyboard.nextDouble();
StudentFile.println (name);
StudentFile.println (age);
StudentFile.println (gpa);
System.out.println("Do you wish to enter a new record? "
+ "Type 'y' or 'n'.");
answer = keyboard.nextLine();
}
while (answer.equalsIgnoreCase("y"));
StudentFile.close();
System.exit(0);
}
}
But the problem is that the question of adding a new record doesn't asked to user. So I was wondering what I did wrong and how I could fix it.
Here is quick fix for you. Please check following code.
You need to use next() in place of nextLine().
public static void main(String arg[]) {
Scanner keyboard = new Scanner (System.in);
System.out.println("enter FILE name");
String FileName = keyboard.nextLine();
try{
FileWriter fwriter = new FileWriter(FileName);
PrintWriter StudentFile = new PrintWriter(fwriter);
String name = "";
int age = 0;
double gpa = 0.0;
String answer = "";
do {
System.out.println("Enter name.");
name = keyboard.next();
System.out.println("Enter age.");
age = keyboard.nextInt();
System.out.println("Enter GPA.");
gpa = keyboard.nextDouble();
StudentFile.println (name);
StudentFile.println (age);
StudentFile.println (gpa);
System.out.println("Do you wish to enter a new record? Type 'y' or 'n'.");
answer = keyboard.next();
}
while (answer.equalsIgnoreCase("y"));
StudentFile.close();
System.exit(0);
}catch(IOException ex){
ex.printStackTrace();
}finally {
keyboard.close();
}
}
Hope this solution works.

Can someone help me figure out why one of my methods is not running at all?

Why when I run my program and enter 5, it allows me to enter my records, but when the main menu runs again and I enter 6, the changePhoneNumber method is not run and it goes back to the main menu. Is the while(true) loop somehow messing things up?
I have a class called Record that looks like:
public static void main(String[] args) {
BankMethods method = new BankMethods();
Scanner input = new Scanner(System.in);
int optionSelected = 0;
while(true){
System.out.println("5. Add a New Record");
System.out.println("6. Change the Phone Number in the Current Record");
optionSelected = input.nextInt();
if (optionSelected == 5){
Scanner getRecord = new Scanner(System.in);
System.out.println("Enter First Name: ");
String firstName = getRecord.nextLine();
System.out.println("Enter Last Name: ");
String lastName = getRecord.nextLine();
System.out.println("Enter Phone Number: ");
String phoneNumber = getRecord.nextLine();
method.addNewRecord(firstName, lastName, phoneNumber);
}
if (optionSelected == 6){
System.out.println("What would you like to change your phone "
+ "number to? ");
String newNumber = input.nextLine();
method.changePhoneNumber(newNumber);
}
and the other class...BankMethods:
public class BankMethods {
LinkedList recordInformation = new LinkedList();
Bankdata mainMenu = new Bankdata();
public void addNewRecord(String firstName, String lastName,
String phoneNumber){
recordInformation.add(firstName); recordInformation.add(lastName);
recordInformation.add(phoneNumber);
}
public void changePhoneNumber(String newNumber){
recordInformation.set(2, newNumber);
System.out.println(recordInformation);
}
The problem is that you are using 2 Scanners to read the one InputStream. When you open the second Scanner you will not be able to read using the original one as the second will have exclusive access to it.
For this application you could easily use a single Scanner.
See: Do not create multiple buffered wrappers on a single InputStream
The correct way is to use one read(scanner) for a input stream. Edited the previous answer to use single read option
Complete program that works is given below
package com.stackoverflow.framework;
import java.util.LinkedList;
import java.util.Scanner;
public class Record {
static Scanner input = new Scanner(System.in);
public static String readData() {
return (input.nextLine());
}
public static void main(String[] args) {
BankMethods method = new BankMethods();
int optionSelected = 0;
while (true) {
System.out.println("5. Add a New Record");
System.out
.println("6. Change the Phone Number in the Current Record");
optionSelected = Integer.parseInt(readData());
if (optionSelected == 5) {
// Scanner getRecord = new Scanner(System.in);
System.out.println("Enter First Name: ");
String firstName = readData();
System.out.println("Enter Last Name: ");
String lastName = readData();
System.out.println("Enter Phone Number: ");
String phoneNumber = readData();
method.addNewRecord(firstName, lastName, phoneNumber);
}
if (optionSelected == 6) {
System.out.println("What would you like to change your phone "
+ "number to? ");
// Scanner getRecord = new Scanner(System.in);
String newNumber = readData();
method.changePhoneNumber(newNumber);
}
}
}
}
class BankMethods {
LinkedList recordInformation = new LinkedList();
public void addNewRecord(String firstName, String lastName,
String phoneNumber) {
recordInformation.add(firstName);
recordInformation.add(lastName);
recordInformation.add(phoneNumber);
}
public void changePhoneNumber(String newNumber) {
recordInformation.set(2, newNumber);
System.out.println(recordInformation);
}
}

"error: variable keyboard is already defined in method main(String [])"

I'm getting several error messages when I try to run my program, the main one which bothers me being "error: variable keyboard is already defined in method main(String [])"
Am I supposed to but main(String []) more than once in my program, or just in the beginning as I have it? What else could be wrong here?
Here is the beginning of my program:
public static void main(String[]args)
{
String firstName, lastName;
int moviesDownloaded, stateResidency;
double movieCost, netPayment, tax, discount, totalCharge, payment, taxRate;
System.out.println("Enter your first name:");
Scanner keyboard = new Scanner(System.in);
firstName = keyboard.nextString();
System.out.println("Enter your last name:");
Scanner keyboard = new Scanner(System.in);
lastName = keyboard.nextString();
System.out.println("Enter the number of movies downloaded:");
Scanner keyboard = new Scanner(System.in);
moviesDownloaded = keyboard.nextInt();
System.out.println("Enter the cost per movie:");
Scanner keyboard = new Scanner(System.in);
movieCost = keyboard.nextDouble();
System.out.println("Indicate your state of residency. Enter 1 for Mississippi or 2 for any other state.");
Scanner keyboard = new Scanner(System.in);
stateResidency = keyboard.nextInt();
You should only declare and initialize keyboard once and then use it. So remove all lines of the type: Scanner keyboard = new Scanner(System.in); apart from the first one.
Otherwise you try to declare the same variable multiple times and thus java complains.
I'm guessing this has been long solved by this point but I came across it and I really like closure, because Ivaylo Strandjev answer was not chosen. Also in case anyone else stumbles across this.
The error is saying you defined the variable keyboard in this scope already and you are trying to define it again.
like Ivaylo Strandjev was saying.
You can try the following:
1 remove the declaration portion
public static void main(String[]args) {
String firstName, lastName;
int moviesDownloaded, stateResidency;
double movieCost, netPayment, tax, discount, totalCharge, payment, taxRate;
System.out.println("Enter your first name:");
Scanner keyboard = new Scanner(System.in);
firstName = keyboard.nextString();
System.out.println("Enter your last name:");
keyboard = new Scanner(System.in); //-----changed
lastName = keyboard.nextString();
System.out.println("Enter the number of movies downloaded:");
keyboard = new Scanner(System.in); //-----changed
moviesDownloaded = keyboard.nextInt();
System.out.println("Enter the cost per movie:");
keyboard = new Scanner(System.in);//-----changed
movieCost = keyboard.nextDouble();
System.out.println("Indicate your state of residency. Enter 1 for Mississippi or 2 for any other state.");
keyboard = new Scanner(System.in);//-----changed
stateResidency = keyboard.nextInt();`
or this, change the new variable names
public static void main(String[]args){
String firstName, lastName;
int moviesDownloaded, stateResidency;
double movieCost, netPayment, tax, discount, totalCharge, payment, taxRate;
System.out.println("Enter your first name:");
Scanner keyboard1 = new Scanner(System.in);
firstName = keyboard1.nextString();
System.out.println("Enter your last name:");
Scanner keyboard2 = new Scanner(System.in);//-----changed
lastName = keyboard2.nextString();
System.out.println("Enter the number of movies downloaded:");
Scanner keyboard3 = new Scanner(System.in);//-----changed
moviesDownloaded = keyboard3.nextInt();
System.out.println("Enter the cost per movie:");
Scanner keyboard4 = new Scanner(System.in);//-----changed
movieCost = keyboard4.nextDouble();
System.out.println("Indicate your state of residency. Enter 1 for Mississippi or 2 for any other state.");
Scanner keyboard5 = new Scanner(System.in);//-----changed
stateResidency = keyboard5.nextInt();`
You don't need to initialize Keyboard every time you use it. You can declare it once at the top of the program, and just call keyboard.next() each time you want to get something from it.

I need to create a program that will add, remove, list, save, and sort students in a created Student, Undergrad, and Graduate classes

I have three different classes, one for grad students, undergrads, and then a general student class, I need to figure out how to add students to an array list, from the main method. I can't figure out how to add a first name because it is private, and it needs to stay private.
package enrollmentdatabase;
import java.util.ArrayList;
import java.util.Scanner;
public class EnrollmentDataBase {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
String option = optionChoise(input);
String option1 = "ADD";//ADD option
String option2 = "REMOVE";//REMOVE OPTION
String option3 = "LIST";//LIST OPTION
String option4 = "SAVE";//SAVE OPTION
String option5 = "SORT";//SORT OPTION
ArrayList studentList = new ArrayList();
}//end of main method
public static String optionChoise(Scanner input){
String opt1 = "ADD";//ADD option
String opt2 = "REMOVE";//REMOVE OPTION
String opt3 = "LIST";//LIST OPTION
String opt4 = "SAVE";//SAVE OPTION
String opt5 = "SORT";//SORT OPTION
System.out.println("Enter what you want to do(ADD, REMOVE, LIST, SAVE, or SORT): ");
String opt = input.nextLine();
if((opt.compareToIgnoreCase(opt1)) !=0 || (opt.compareToIgnoreCase(opt1)) != 0 || (opt.compareToIgnoreCase(opt1)) !=0
|| (opt.compareToIgnoreCase(opt1)) !=0 || (opt.compareToIgnoreCase(opt1)) !=0){//enter this if conditional in order to establish that the input is valid
System.out.println("This is not a valid input, please enter in what you want to do: ");
opt = input.nextLine();
}//end of if conditional
return opt;
}//end of option method
public static ArrayList addList(ArrayList studentList, Scanner input){
System.out.println("Enter the Student's first name: ");
String nameFirst= input.nextLine();
Student student1 = new Student();
student1.firstName = nameFirst;
System.out.println("Enter the Student's last name: ");
System.out.println("Enter the Student's UID: ");
System.out.println("Enter the Student's status: ");
System.out.println("Enter YES for having a thesis option, else NO: ");
System.out.println("Enter Masters for Master Studies of PHD for PHD studies: ");
System.out.println("Enter the name of the major professor: ");
System.out.println("Enter the student class standing: ");
System.out.println("Enter the Student's major: ");
System.out.println("Enter the student's overall GPA: ");
System.out.println("Enter the student's major GPA: ");
}//end of addList method
}//end of class
I can't figure out how to add a first name because it is private,
have public getter and public setter methods for that private data and access it through them.
For instance:
class Student {
private String fName;
public void setFname(String fName){
this.fName = fName;
}
public String getFName(){
return fname;
}
}
class AnotherClass {
public static void main(String...args){
student s = new Student();
System.out.println(s.getFName());//to access fName(which is private) in class Student.
}
}

Categories

Resources