User Input from Class to Main Class in Java - java

I'm trying to create a program that (1) prompts for a user's full name and then generates a username; (2) prompts for a number and then determines if the number is odd or even. I wrote out the code for the username and odd/even classes and would like to call them from the main class. However, when called from the main class, the username method prompts the user twice before generating the username and the odd/even method doesn't actually determine if the number the user inputted is odd/even. When I remove the scanner object from the username class, I get a out of bounds compilation error so I'm forced to put it back in just so the program will run. Should I be using return statements?
Username
/**
* Class to generate the username based on user's first name and randomly generated numbers
*/
public void username()
{
Scanner inputReader = new Scanner(System.in);
String fullName = inputReader.nextLine();
// create random object and variable to store it in
Random randomizer = new Random();
int randomNumber = randomizer.nextInt(1000);
// create variable to store lowercase username
String lowercase = (fullName.toLowerCase());
// create string variable to format username to first three characters in lowercase
String firstThreeLetters = (lowercase.substring(0, 3));
// concatenate lowercase characters and random number
String usernameFinal = (firstThreeLetters + randomNumber);
// print out final username
System.out.println("Your username is " + usernameFinal);
}
Odd/even
/**
* Class to determine if a user inputted value is odd or even
*/
public void OddEven1()
{
Scanner inputReader = new Scanner(System.in);
int userInteger = 0;
// if/else to determine if number is odd or even
if (userInteger % 2 == 0)
{
System.out.println(userInteger + " is an even number.");
}
else
{
System.out.println(userInteger + " is an odd number.");
}
}
Main method
{
/**
* This class holds the main method through which all other classes are run.
*/
public static void main(String[] args)
{
// create objects
Username usernameGenerator = new Username();
OddEven oddeven = new OddEven();
Scanner inputReader = new Scanner(System.in);
// prompt for real name and print username
System.out.print("Name: ");
String fullName = inputReader.nextLine();
usernameGenerator.username();
// prompt for number
System.out.print("Give me a number: ");
// variable to store value
int userInteger = inputReader.nextInt();
oddeven.OddEven1();
}
Output:

1 - You request user's name twice, one in here
String fullName = inputReader.nextLine();
And one in here
Scanner inputReader = new Scanner(System.in);
String fullName = inputReader.nextLine();
I would recommend keeping the first method and pass fullName to the username() function. As an example:
/**
* Class to generate the username based on user's first name and
randomly generated numbers
*/
public void username(fullName)
{
// create random object and variable to store it in
Random randomizer = new Random();
int randomNumber = randomizer.nextInt(1000);
// create variable to store lowercase username
String lowercase = (fullName.toLowerCase());
// create string variable to format username to first three characters in lowercase
String firstThreeLetters = (lowercase.substring(0, 3));
// concatenate lowercase characters and random number
String usernameFinal = (firstThreeLetters + randomNumber);
// print out final username
System.out.println("Your username is " + usernameFinal);
}
2 - You do the same in the second function OddEven1() . I would recommend passing a parameter to it too. As an exmaple:
public void OddEven1(number)
{
int userInteger = number;
// if/else to determine if number is odd or even
if (userInteger % 2 == 0)
{
System.out.println(userInteger + " is an even number.");
}
else
{
System.out.println(userInteger + " is an odd number.");
}
}
3 - So your main function becomes:
public static void main(String[] args)
{
// create objects
Username usernameGenerator = new Username();
OddEven oddeven = new OddEven();
Scanner inputReader = new Scanner(System.in);
// prompt for real name and print username
System.out.print("Name: ");
String fullName = inputReader.nextLine();
usernameGenerator.username(fullName);
// prompt for number
System.out.print("Give me a number: ");
// variable to store value
int userInteger = inputReader.nextInt();
oddeven.OddEven1(userInteger);
}

You should change your code like below
inside main method
System.out.print("Give me a number: ");
// variable to store value
int userInteger = inputReader.nextInt();
oddeven.OddEven1(userInteger );
Odd/even
public void OddEven1(int userInteger )
{
// if/else to determine if number is odd or even
if (userInteger % 2 == 0)
{
System.out.println(userInteger + " is an even number.");
}
else
{
System.out.println(userInteger + " is an odd number.");
}
}
Now lets discuss about username. You have already captured the username from your main method. So you dont need to get it from user again.
String fullName = inputReader.nextLine();
usernameGenerator.username(fullName );
public void username(String fullName )
{
//Your logic
}

Related

How to I do an array with a JOptionPane

The question asks "The number of fuel tanks can only be (2,4,8,10, 15,20)" this is aNbrTanks in the code below. I been trying to use an array to have these inputs. But then I get the error of Object cant be converted to int or int[] to int. I need to ask for input by JOptionPane and then ask again if it doesn't meet the standards.
package project2;
import javax.swing.JOptionPane;
/**
*
* #author Administrator
*/
public class VehicleApp {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
//name
String firstName = JOptionPane.showInputDialog("Please enter your first name");
while(firstName.equals("")){
firstName =JOptionPane.showInputDialog("Please enter a valid first name");
}
String lastName = JOptionPane.showInputDialog("Please enter your last name");
while(lastName.equals("")){
lastName =JOptionPane.showInputDialog("Please enter a valid first name");
}
String aName = firstName + " " + lastName;
//phone
String aphone = JOptionPane.showInputDialog("Please enter your number");
while(aphone.length()!=10){
aphone = JOptionPane.showInputDialog("Please enter a valid phone number");
}
String aPhone = ("" + aphone).replaceAll("(...)(...)(....)", "$1-$2-$3");
//vechicle number
int aNbrVehicles = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of Vehicles"));
while(aNbrVehicles < 1 || aNbrVehicles > 10 ){
aNbrVehicles = Integer.parseInt(JOptionPane.showInputDialog("valid number of Vehicles"));
}
//fuel tank
int aNbrTanks = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of Tanks"));
VehicleFactory JarApp = new VehicleFactory(aName, aPhone, aNbrVehicles, aNbrTanks);
JarApp.calcManufacturingCost();
JarApp.calcFuelTankCost();
JarApp.calcSubtotal();
JarApp.calcTax();
JarApp.calcTotal();
JOptionPane.showMessageDialog(null, JarApp.getSummary());
}
}
I just need ideas or help figuring out how to get an array or a statement that be used as int aNbrTanks like the question asks.
You could request values in a loop, as you suggest anyway.
My example shows the loop you can use. There are more efficient ways to test for the allowed values.
int aNbrTanks = 0;
while (true) {
try {
aNbrTanks = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of Tanks"));the number of Vehicles"));
} catch (NumberFormatException e) {
e.printStackTrace(e);
}
if (aNbrTanks==2) {
break;
}
}
Coming back to your title question, you can use JOptionPane with an Object[], not int[]. It will then convert your list of choices into a JComboBox. Here is an example:
public static void main(String[] args) {
Object[] choices = new Object[]{2,3,5,8};
System.out.println(Arrays.toString(choices));
Object choice = JOptionPane.showInputDialog(null, "Enter the number of Tanks", "Tanks", JOptionPane.PLAIN_MESSAGE, null, choices, 2);
System.out.println(choice);
}

Take two user inputs and print them out with a random number at the end

package stringvars;
import java.util.Scanner;
public class ConcertID {
public static void main(String[] args) {
try (Scanner userInput = new Scanner (System.in)) {
String yourName;
System.out.print ("enter the last letter of your second name: ");
yourName = userInput.next();
String yourDOB;
System.out.print ("enter your Year Of Birth: ");
yourDOB = userInput.next();
String ConcertID;
ConcertID = yourName + " " + yourDOB;
System.out.println("your concert ID is " + ConcertID);
}
}
}
I'm trying to get the code to take the user input, add a number between 1 and 10 at the end and print it as Y18867. Currently it prints as Y 1886.
(And I've yet to figure out the math.random part.)
Let me recommend you start using the StringBuilder class to create concatenated strings. It has a better performance regarding time consuming to concatenate strings.
The following code generates the random number as well as the concertId string that you are trying to get.
public class ConcertID
{
public static void main(String[] args)
{
try (Scanner userInput = new Scanner(System.in))
{
String yourName;
System.out.print("Enter the last letter of your second name: ");
yourName = userInput.nextLine();
String yearOfBirth;
System.out.print("Enter your Year of Birth: ");
yearOfBirth = userInput.nextLine();
StringBuilder concertId = new StringBuilder();
concertId.append(yourName);
concertId.append(yearOfBirth);
concertId.append(generateNumber());
System.out.println(concertId.toString());
}
}
public static int generateNumber()
{
int number = 0;
Random random = new Random();
number = random.nextInt(1, 10);
return number;
}
}

Java - Array outputing null

My program is supposed to output labels. All of the input works when I run it but the output is wrong and all that it outputs is null, for every part of the label except for the box number.
import javax.swing.JOptionPane;
public class MailOrderpractice {
static String nameAddressArray[] = new String[7];
public static void main(String[] args) {
// declare variables
String nameAddressArray[] = new String[7];
String numBoxesInput;
int numBoxes;
String enterAnother = "Y";
int counter;
getLabelData();
numBoxesInput = JOptionPane.showInputDialog("Enter number of boxes in the order:");
numBoxes = Integer.parseInt(numBoxesInput);
// begin outer loop logic that determines when user is finished entering mail orders
while (enterAnother.equalsIgnoreCase("Y")) {
counter = 1;
// begin the inner loop to display a label and increment the counter
while (counter <= numBoxes) {
System.out.println(nameAddressArray[0] + " " + nameAddressArray[1] + " " + nameAddressArray[2]);
System.out.println(nameAddressArray[3]);
System.out.println(nameAddressArray[4] + ", " + nameAddressArray[5] + " " + nameAddressArray[6]);
System.out.println("Box " + counter + " of " + numBoxes);
System.out.println();
counter = counter + 1;
}
enterAnother = " "; // initialize the variable to something other than "Y" before sending the prompt
enterAnother = JOptionPane.showInputDialog("Do you want to produce more labels? Y or N");
while (!enterAnother.equalsIgnoreCase("Y") && !enterAnother.equalsIgnoreCase("N")) {
enterAnother = JOptionPane.showInputDialog(null, "Invalid Response. Please enter Y or N.",
"DATA ENTRY ERROR", JOptionPane.ERROR_MESSAGE);
} // end while
if (enterAnother.equalsIgnoreCase("Y")) {
getLabelData();
numBoxesInput = JOptionPane.showInputDialog("Enter number of boxes in the order:");
numBoxes = Integer.parseInt(numBoxesInput);
} // end if
} // end while
System.exit(0);
}
public static void getLabelData() {
nameAddressArray[0] = JOptionPane.showInputDialog("Enter title (Mr., Ms., Dr., etc.): ");
nameAddressArray[1] = JOptionPane.showInputDialog("Enter first name: ");
nameAddressArray[2] = JOptionPane.showInputDialog("Enter lastname: ");
nameAddressArray[3] = JOptionPane.showInputDialog("Enter street address: ");
nameAddressArray[4] = JOptionPane.showInputDialog("Enter city: ");
nameAddressArray[5] = JOptionPane.showInputDialog("Enter state (IL, MO, etc.): ");
nameAddressArray[6] = JOptionPane.showInputDialog("Enter zip (e.g., 62025): ");
}
The array nameAddressArray is declared twice. You have a static field
static String nameAddressArray[] = new String[7];
You also have a local variable with the same name in the main method.
String nameAddressArray[] = new String[7];
Your main method is putting values into the second array, whereas your getLabelData method is using the values from the static field, and these are all the initial value (null).
One way to solve this problem is to just get rid of the local variable. Then both parts of the code will use the same array.
Alternatively, you could get rid of the static field, and pass the array as a parameter to the getLabelData method. This is probably a better solution, as mutable static fields are generally not a good idea.
you just need to comment this line into Main method(),
// String nameAddressArray[] = new String[7];

Two methods executing at the same time? Why?

package contractmanager;
import java.util.*;
/**
*
* #author Tom McCloud
*/
public class ContractManager {
static Scanner keyb = new Scanner(System.in);
// global scanner
public static void main(String[] args) {
int option;
//variable declaration
String clientName;
String packageSize;
String dataBundle;
String reference;
int period;
boolean intlCalls;
//display menu to user
System.out.println("Welcome: \n");
System.out.println("1. Enter new contract ");
System.out.println("2. Display contract summary");
System.out.println("3. Display summary of contract for selected month");
System.out.println("4. Find and display contract");
System.out.println("0. Exit");
//take option off user
option = keyb.nextInt();
//WIP - only working on option 1 at the minute
switch(option) {
case 1:
clientName = clientName();
packageSize = packageSize();
dataBundle = dataBundle();
reference = reference();
break;
}
exit();
}
public static void exit()
{
System.out.println("Thank you for using the contract manager. Goodbye!");
}
public static String clientName()
{
String name = " ";
System.out.println("Please input your full name: ");
name = keyb.nextLine();
return name;
}
public static String packageSize()
{
String size;
System.out.println("Please input your package size: ");
System.out.println(" 1. Small \n 2. Medium \n 3. Large");
size = keyb.next();
return size;
}
public static String dataBundle()
{
String data;
System.out.println("Please input data bundle size: ");
System.out.println("1. Low \n 2. Medium \n 3. High \n 4. Unlimited");
data = keyb.next();
return data;
}
public static String reference()
{
String ref;
boolean isRefValid = false;
do {
System.out.println("Please input your reference code: ");
ref = keyb.next();
if(ref.length() > 6)
{
System.out.println("Reference number too long, re-enter!");
}
for(int i = 0; i < 2; i++)
{
if(Character.isDigit(ref.charAt(i)))
{
System.out.println("First two characters must be letters!");
}
}
} while(isRefValid = false);
return ref;
}
}
So, this is some code I have. If I press enter code hereone, it executes these, now technically shouldn't this be in order of one another once each method reaches completion and returns?
For example, on execution after pressing "1" I get the following output:
Please input your full name:
Please input your package size:
1. Small
2. Medium
3. Large
Whereas this should come one by one, after the full name has been inputted it should move onto the package size step. If I input it goes to the third step rather than repeating for the second step's input.
I think it's because in your clientName function you have just printed "Please input your full name: " without waiting for input. For example you have to do something like below here scan.nextLine() will wait until user have press enter:
Scanner scan = new Scanner();
System.out.println("Please input your full name:");
String name= scan.next();
System.out.println(name);
scan.nextLine();
Updated: Try by updating clientName function as below
public static String clientName() {
String name = " ";
System.out.println("Please input your full name: ");
name = keyb.next();
keyb.nextLine();
return name;
}

new scanner object inside constructor

Java noob here. My instructor told me specifically to "instantiate the scanner INSIDE the constructor". The problem is, i am not seeing a constructor in our ScannerLab class. Nor am i seeing any inheritance. I have a field named scan which is of type java.util.Scanner that i need to use. How do i instantiate the scanner inside the constructor?
code:
public class ScannerLab {
private java.util.Scanner scan;
public void echoStrings() {
String word;
// create a new storage array
String[] myList = new String[5];
// set for loop
for(int i = 0; i < 5; i ++) {
// prompt for the value
System.out.print("Enter word " + i + ": ");
// get the input value
word = scan.next();
// echo the input value
System.out.println("You entered " + word);
// store the input value into the array
myList[i] = word;
}
String line = "";
// loop through the array and concatenate the values
// put a space between the words
System.out.println("The words you entered are: " + line);
System.out.println("list is" + myList);
}
public void echoIntsAndTotal() {
int inputValue;
// declare an array to hold the 5 values
for(int i = 0; i < 5; i ++) {
// prompt for the value
System.out.print("Enter integer value " + i + ": ");
// get the input value
inputValue = 23;
// echo the input value
System.out.println("You entered " + inputValue);
// store the input value into the array
}
int total = 0;
// loop through the array and add the values
System.out.println("The total of your values is " + total);
}
public static void main(String[] args) {
ScannerLab lab;
lab = new ScannerLab();
lab.echoStrings();
// lab.echoIntsAndTotal();
}
}
i have tried:
setting the scan field as a reference variable to:
private java.util.Scanner scan = new java.util.Scanner(System.in);
then in my application method i used:
public static void main(String[] args) {
ScannerLab lab;
lab = new ScannerLab(scan);
didnt work. The only way it would compile and run is if i switch my field to:
private static java.util.Scanner scan = new java.util.Scanner(System.in);
but he wont allow us to use static fields, and that is still not being instantiated inside the constructor.
where is the constructor, and how do i instantiate a new scanner in it?
Thank you
If there is no constructor in your class yet, you have an implicit default constructor available (see this question too). You can choose to override it at any point:
public class ScannerLab {
public ScannerLab() {
scan = new java.util.Scanner(System.in);
}
...
}
From https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html:
The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass.
How about writing a constructor then?
// Constructor
public ScannerLab() {
scan = new java.util.Scanner(System.in);
}
Other than that, this line
System.out.println("list is" + myList);
doesn't work. It will give you the class name and hashcode, since that is the default implementation.
Try something like this:
System.out.println("\nThe words you entered are:");
System.out.println(Arrays.toString(myList));
which will give you an output like:
The words you entered are:
[apple, banana, carrot, dududu, elephant]

Categories