Passing Strings between Classes - java

Fair new to java. Read a few other questions but haven't found the solution yet. Im looking to pass acname, dob and balance1 (all input by the user) to another class. currently it results in nullnullnull. Please help:
First Class:
public static String acname;
public static String dob;
public static String balance1;
public static void main(String[] args) {
switch (menu) {
case 1: Scanner sc=new Scanner(System.in);
System.out.println("Please enter account holders name:");
String acname = sc.nextLine();
Scanner sc2=new Scanner(System.in);
System.out.println("Please enter account holders date of birth:");
String dob = sc2.nextLine();
BankAccount balance1 = new BankAccount(0, 0.10);
balance1.getBalance();
System.out.println("Account Created. Overview and Balance: " + "\n" + acname + "\n" + dob + "\n" + "£" + balance1.getBalance() + "\n");
Second Class:
public class MainMenu {
public static void main(String[] args) {
System.out.println("--WELCOME TO BEAN BANKING LTD--");
System.out.println("");
System.out.println("1. Create new account");
System.out.println("2. View account details and balance");
System.out.println("3. Deactivate account");
System.out.println("4. Exit System");
Scanner scanner = new Scanner(System.in);
int menu = scanner.nextInt();
switch (menu) {
case 1: AccountCreator.main(null);
case 2: System.out.println(AccountCreator.acname + AccountCreator.dob + AccountCreator.balance1);

You are declaring local variables with the same names as your class variables. The local variables will be assumed unless you qualify references to them.
Instead of:
String acname = sc.nextLine();
Just do:
acname = sc.nextLine();

Related

How do I accept the user input and put it into the while condition

This is my code, the while loop does not have an input and the rep variable does not accept an input:
import java.util.Scanner;
public class MixedData {
public static void main(String[] args) {
String rep = "";
do {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter your full name");
String name = keyboard.nextLine();
System.out.print("Enter your GPA: ");
double gpa = keyboard.nextDouble();
System.out.println("Name: " + name + ", GPA: " + gpa);
System.out.println("Do you want to enter the data for another student?(y/n)");
rep = keyboard.nextLine();
} // This does not accept input
while (rep.equals("y"));
}
}
Either just add one more keyboard.nextLine() before rep = keyboard.nextLine(); (in order to clear the newline character), or read your double gpa value with:
double gpa = Double.parseDouble(keyboard.nextLine());
Important point to understand here (especially if you're a novice Java developer), about why your code doesn't work, is, that you invoke nextDouble() as a last method on your Scanner instance, and it doesn't move the cursor to the next line.
A bit more details:
All the methods patterned nextX() (like nextDouble(), nextInt(), etc.), except nextLine(), read next token you enter, but if the token isn't a new line character, then the cursor isn't moved to the next line. When you enter double value and hit Enter, you actually give to the input stream two tokens: a double value, and a new line character, the double value is initialized into the variable, and the new line character stays into input stream. The next time you invoke nextLine(), that very new line character is read, and that's what gives you an empty string.
Here's the same code using a while loop instead of do-while. It works the way you want it to.
import java.util.Scanner;
public class MixedData {
public static void main(String[] args) {
String rep = "y";
while (!rep.equals("n")) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter your full name: ");
String name = keyboard.nextLine();
System.out.print("Enter your GPA: ");
double gpa = keyboard.nextDouble();
System.out.println("Name: " + name + ",GPA: " + gpa);
System.out.println("Do you want to enter the data for another student?(y/n)");
rep = keyboard.next();
}
}
}
You need to skip blank lines.
public static void main(String[] args) {
String rep;
Scanner keyboard = new Scanner(System.in);
do {
System.out.print("Enter your full name");
String name = keyboard.nextLine();
System.out.print("Enter your GPA: ");
double gpa = keyboard.nextDouble();
System.out.println("Name: " + name + ", GPA: " + gpa);
System.out.println("Do you want to enter the data for another student?(y/n)");
rep = keyboard.next();
keyboard.skip("\r\n"); // to skip blank lines
}
while (rep.equalsIgnoreCase("y"));
keyboard.close();
}
Use nextLine instead of nextDouble:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String rep = "";
do {
System.out.println("Enter your full name:");
String name = keyboard.nextLine();
System.out.println("Enter your GPA:");
// double gpa = keyboard.nextDouble();
double gpa = Double.parseDouble(keyboard.nextLine());
System.out.println("Name: " + name + ", GPA: " + gpa);
System.out.println("Do you want to enter the data for another student?(y/n)");
rep = keyboard.nextLine();
} while (rep.equals("y"));
keyboard.close();
}

Is it possible detect single enterkey with java.util.Scanner?

I am trying to write a terminal-based toy app, which allows user to input product category and inventory.
Is it possible to implement a feature of pressing enter key to input the default inventory.
Here is the procedure/steps
app print "product category:"
user input a category, such as shoe
app print "Inventory(press enter key for 999):"
user press enterkey or input another number
app print product_category + product_inventory
here is my code
import java.util.Scanner;
public class ProductScanner {
public static void main(String[] args) {
System.out.print("product category: ");
Scanner scanner = new Scanner(System.in);
String product_category = scanner.next();
System.out.print("Inventory(press enter key for 999): ");
int product_inventory = scanner.nextInt();
scanner.close();
System.out.println(String.format("%s, %d", product_category, product_inventory));
}
}
this code does not support "enterkey for default" feature.
quesion
is it possible detect single enterkey with java.util.Scanner to implement the default input?
I also tried this code, even worse
import java.util.Scanner;
public class ProductScanner {
public static void main(String[] args) {
System.out.print("product category: ");
Scanner scanner = new Scanner(System.in);
String product_category = scanner.next();
scanner.close();
System.out.print("Inventory(press enter key for 999): ");
scanner = new Scanner(System.in);
String product_inventory_str = "999";
if(scanner.hasNext()){
System.out.println("hasNext");
product_inventory_str = scanner.nextLine();
}
else{
System.out.println("does not have Next");
}
int product_inventory = 999;
if(product_inventory_str.isEmpty()){
System.out.println("isEmpty");
}
else{
product_inventory = Integer.parseInt(product_inventory_str);
}
scanner.close();
System.out.println(String.format("%s, %d", product_category, product_inventory));
}
}
You could always read an entire line (because user will have to press Enter anyway) and then decide what to do with it, something like this:
public static void main(String[] args) {
System.out.print("product category: ");
Scanner scanner = new Scanner(System.in);
String product_category = scanner.nextLine();
System.out.print("Inventory(press enter key for 999): ");
String pi_string = scanner.nextLine();
int product_inventory = pi_string.isEmpty()?
999:Integer.parseInt(pi_string);
scanner.close();
System.out.println(String.format("%s, %d",
product_category, product_inventory));
}

How to repeatedly store data in linked lists?

I have a program where I want to continue adding in an integer and string in a linked list. However when I print out the linked list it only prints out the last entered values and not the previous ones. So If I entered 3 Sally and then entered 6 Bob the linked list only prints out 6 bob. I want to be able to print out everything in the linkedlist no just the last entered.
public class Texteditor {
/**
* #param args the command line arguments
*/
static int myInt;
static String myString;
public Texteditor(int a, String s){
myInt = a;
myString = s;
}
public String toString(){
return myInt + " " + myString;
}
public static void main(String[] args) {
LinkedList<Texteditor> myLL = new LinkedList<Texteditor>();
int isExit = 0;
System.out.println("Hello Welcome to Your Personal Texteditor! ");
System.out.println("There are many options you can do with this text editor");
System.out.println("1. If you enter a line number with no text, the line number will be deleted.");
System.out.println("2. If you enter LIST alone the editor will print everything in the list with line number.");
System.out.println("3. If you enter RESEQUENCE the line numbers will be resequenced to start at 10.");
while(isExit ==0) {
// myLL = new LinkedList<Texteditor>();
System.out.println("");
System.out.println("Please enter the line number: ");
Scanner kb = new Scanner(System.in);
myInt = kb.nextInt();
System.out.println("Plese enter text as a string: ");
Scanner kb1 = new Scanner(System.in);
myString = kb1.nextLine();
Texteditor a1 = new Texteditor(myInt, myString);
myLL.add(a1);
System.out.println("Would you like to keep going? Enter yes or no: " );
Scanner kb2 = new Scanner(System.in);
if (kb2.next().equals("no")){
isExit = 1;
}
}
for (Texteditor element : myLL){
System.out.println(element + "\n");
}
}
}
Your myInt and myString are static, which means they're shared by instances. Make them non-static and the code should work correctly.
Also, don't recreate the Scanner every time in the loop. Once is enough.
The problem is that you are making the myInt and myString variables static. Remove the static modifier and then in your while loop, instead of referencing the class's myInt and myString variables, create local int and String variables instead.
public class Texteditor {
/**
* #param args the command line arguments
*/
int myInt;
String myString;
public Texteditor(int a, String s){
myInt = a;
myString = s;
}
public String toString(){
return myInt + " " + myString;
}
public static void main(String[] args) {
LinkedList<Texteditor> myLL = new LinkedList<Texteditor>();
int isExit = 0;
System.out.println("Hello Welcome to Your Personal Texteditor! ");
System.out.println("There are many options you can do with this text editor");
System.out.println("1. If you enter a line number with no text, the line number will be deleted.");
System.out.println("2. If you enter LIST alone the editor will print everything in the list with line number.");
System.out.println("3. If you enter RESEQUENCE the line numbers will be resequenced to start at 10.");
while(isExit ==0) {
// myLL = new LinkedList<Texteditor>();
System.out.println("");
System.out.println("Please enter the line number: ");
Scanner kb = new Scanner(System.in);
int myInt = kb.nextInt();
System.out.println("Plese enter text as a string: ");
Scanner kb1 = new Scanner(System.in);
String myString = kb1.nextLine();
Texteditor a1 = new Texteditor(myInt, myString);
myLL.add(a1);
System.out.println("Would you like to keep going? Enter yes or no: " );
Scanner kb2 = new Scanner(System.in);
if (kb2.next().equals("no")){
isExit = 1;
}
}
for (Texteditor element : myLL){
System.out.println(element + "\n");
}
}
}
The problem with your code is that the variables myInt and myString are static and hence they don't belong to each individual object (they belong to the class). Thus when you reference them here:
for (Texteditor2 element : myLL){
System.out.println(element + "\n");
}
You're calling the same values you set last n amount of times.
This should fix the problem:
Create a new TextEditorObject file:
public class TextEditorObject {
int myInt;
String myString;
public TextEditorObject(int a, String s){
myInt = a;
myString = s;
}
public String toString() {
return myInt + " " + myString;
}
}
Change Texteditor like so:
public class Texteditor {
public static void main(String[] args) {
int myInt;
String myString;
LinkedList<TextEditorObject> myLL = new LinkedList<TextEditorObject>();
int isExit = 0;
System.out.println("Hello Welcome to Your Personal Texteditor! ");
System.out.println("There are many options you can do with this text editor");
System.out.println("1. If you enter a line number with no text, the line number will be deleted.");
System.out.println("2. If you enter LIST alone the editor will print everything in the list with line number.");
System.out.println("3. If you enter RESEQUENCE the line numbers will be resequenced to start at 10.");
while(isExit ==0) {
// myLL = new LinkedList<Texteditor>();
System.out.println("");
System.out.println("Please enter the line number: ");
Scanner kb = new Scanner(System.in);
myInt = kb.nextInt();
System.out.println("Plese enter text as a string: ");
Scanner kb1 = new Scanner(System.in);
myString = kb1.nextLine();
TextEditorObject a1 = new TextEditorObject(myInt, myString);
myLL.add(a1);
System.out.println("Would you like to keep going? Enter yes or no: " );
Scanner kb2 = new Scanner(System.in);
if (kb2.next().equals("no")){
isExit = 1;
}
}
for (TextEditorObject element : myLL){
System.out.println(element + "\n");
}
}
}

Java! How to go to the specific line?

I just started to code in Java and I have a question. After my "else" statement, I want to repeat my code again. How do I do that? Is there a keyword or something?
import java.util.Scanner;
public class UserInputStory {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
userinput:
System.out.println("Enter you name:");
String name = input.nextLine();
System.out.println("OK! Now enter your age:");
int age;
age = input.nextInt();
System.out.println("Good! And the city you live in, please:");
Scanner in = new Scanner(System.in);
String city = in.nextLine();
System.out.println("So, let's check");
System.out.println(
"Your name is " + name + ". You are " + age + " years old and you currently live in " + city + ".");
System.out.println("Is that right?");
Scanner inp = new Scanner(System.in);
String yesno = inp.nextLine();
if (yesno.equals("yes") || yesno.equals("Yes") || yesno.equals("YES")) {
System.out.println("Great job!");
}
else {
System.out.println("Let's try again then!");
}
}
}
Place the body of your code that you want repeating inside a while loop and break when your end-condition is true:
public static void main(String[] args) {
while(true) {
Scanner input = new Scanner(System.in);
userinput:
System.out.println("Enter you name:");
String name = input.nextLine();
System.out.println("OK! Now enter your age:");
int age;
age = input.nextInt();
System.out.println("Good! And the city you live in, please:");
Scanner in = new Scanner(System.in);
String city = in.nextLine();
System.out.println("So, let's check");
System.out.println("Your name is " + name + ". You are " + age + " years old and you currently live in " + city + ".");
System.out.println("Is that right?");
Scanner inp = new Scanner(System.in);
String yesno = inp.nextLine();
if (yesno.equals("yes") || yesno.equals("Yes") || yesno.equals("YES")) {
System.out.println("Great job!");
break;
}
else {
System.out.println("Let's try again then!");
}
}
}
You can envelop our whole code by:
while(1)
ut its not a good approach and there must be some condition applied (depending upon the xontext of your program) which can take you out of the loop

Java - Trouble with brackets

I am having some trouble with the placing of brackets. I wanted to write a few methods within the confines of my main method, but I always end up with with a bunch of red lines and errors telling me "Multiple markers at this line
- Syntax error on token "void", # expected
- addVehicleBooking cannot be resolved to a type"
I don't want my methods to return anything, I just want them to execute some code and print some stuff on the screen.
EDIT:
This is the start of the code, no need to worry about unused variables and such. Thanks for everyone's help =].
import java.util.Scanner;
public class FerryMenu {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
public static void addVehicleBooking()
{
String booking_ID = "";
System.out.print("Enter your booking ID");
booking_ID = input.next();
String registration = "";
System.out.print("Enter registration number");
registration = input.next();
String make_model = "";
System.out.print("Enter vehicle make/model");
make_model = input.next();
int number_passengers = 1;
System.out.print("Enter number of passengers");
number_passengers = scan.nextInt();
}
String menu_choice = "";
while(!"X".equals(menu_choice)){
System.out.println("*** Ferry Ticketing System Menu ***");
System.out.println("A - Add Vehicle Booking");
System.out.println("B - Display Booking Info");
System.out.println("C - Update Insurance Status");
System.out.println("D - Display Booking Summary");
System.out.println("X - Exit");
System.out.print("Enter your selection: ");
menu_choice = input.next();
}
}
}
You can't declare methods inside a method.. It's not about brackets.. It's about syntax.
Ok, Dean, here I'll describe it once again..
First thing, throw away the code that you have written.. Lets start fresh..
Follow these steps to approach your problem: -
Create a class say Demo
Add a method to that class, getUserInput()
Add main method also to your class.
Have a constructor (0-arg)
Now, your program starts executing from main().. If you want to take user input.. Call your getUserInput() method from here.. As the first statement..
In your getUserInputMethod(), after reading all the input, invoke your constructor to initialize your instance variables..
After this, your getUserInput() will return control to your main() method.. You can proceed with your code from there..
You can not define a method inside a method. Declare it outside the method and inside the class.
public class FerryMenu {
public static void addVehicleBooking()
{
//...
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
// just call the method here
addVehicleBooking();
//...
}
}
you are writing your addvehicalBooking method inside your main method.
thus those red line :remove that method from main.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
}
public static void addVehicleBooking()
{
String booking_ID = "";
System.out.print("Enter your booking ID");
booking_ID = input.next();
String registration = "";
System.out.print("Enter registration number");
registration = input.next();
String make_model = "";
System.out.print("Enter vehicle make/model");
make_model = input.next();
int number_passengers = 1;
System.out.print("Enter number of passengers");
number_passengers = scan.nextInt();
}
Try taking out addVehicleBooking() outside main and call it and declare the variables in a constructor
You have a static method inside your main static method which is probably causing the problems. Have you tried moving the addVehicleBooking() method to the space between public class FerryMenu and the main method? (the addVehicleBooking() method should be a member of the class FerryMenu, not the main method)
Why are you making a static method inside public static void main. I dont think that there is a need to make it.
Remove the word static from "static void addVehicleBooking".
I'll edit this answer and add the corrected code asap.
you can not define method in method.
you can define it in class like this:
import java.util.Scanner;
public class FerryMenu {
static Scanner input = new Scanner(System.in);
static Scanner scan = new Scanner(System.in);
public static void addVehicleBooking()
{
String booking_ID = "";
System.out.print("Enter your booking ID");
booking_ID = input.next();
String registration = "";
System.out.print("Enter registration number");
registration = input.next();
String make_model = "";
System.out.print("Enter vehicle make/model");
make_model = input.next();
int number_passengers = 1;
System.out.print("Enter number of passengers");
number_passengers = scan.nextInt();
}
public static void main(String[] args)
{
String menu_choice = "";
while(!"X".equals(menu_choice)){
System.out.println("*** Ferry Ticketing System Menu ***");
System.out.println("A - Add Vehicle Booking");
System.out.println("B - Display Booking Info");
System.out.println("C - Update Insurance Status");
System.out.println("D - Display Booking Summary");
System.out.println("X - Exit");
System.out.print("Enter your selection: ");
menu_choice = input.next();
}
}
}
and fields "input" and "scan" must be defined as static because you are invoking them as static
The addVehicleBooking should be placed outside main. BTW: I hope that you're using somewhere the variables used for user's input because in the code posted are unused.
The refactored code should look like:
import java.util.Scanner;
public class FerryMenu {
public static void main(String[] args) {
addVehicleBooking();
}
public static void addVehicleBooking() {
String menu_choice = "";
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
String booking_ID = "";
System.out.print("Enter your booking ID");
booking_ID = input.next();
String registration = "";
System.out.print("Enter registration number");
registration = input.next();
String make_model = "";
System.out.print("Enter vehicle make/model");
make_model = input.next();
int number_passengers = 1;
System.out.print("Enter number of passengers");
number_passengers = scan.nextInt();
while (!"X".equals(menu_choice)) {
System.out.println("*** Ferry Ticketing System Menu ***");
System.out.println("A - Add Vehicle Booking");
System.out.println("B - Display Booking Info");
System.out.println("C - Update Insurance Status");
System.out.println("D - Display Booking Summary");
System.out.println("X - Exit");
System.out.print("Enter your selection: ");
menu_choice = input.next();
}
}
}

Categories