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);
}
Related
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
}
Thanks to some online assistance from the wonderful stackoverflow users, here is the edits to the enroll and drop student methods to add to the Student array set up. Now it's just on to get the other methods to work as well. Any insight for those would be helpful, especially for speed and efficiency at those points.
import java.util.Scanner;
public class School {
private Student[] theStudents;
public School() {
this.theStudents = new Student[] { null };// needs to start out as empty
}
/*
* next two methods would allow a user to add or drop a student into the
* student array for the school Also with Enroll student, should be able to
* assign a class to the student, i.e. Calculas, history, etc
*/
public void enrollStudent(Student newStudent) {
Student newStudents[] = new Student[theStudents.length+1];
for (int i = 0; i < theStudents.length; i++)
{
newStudents[i] = theStudents[i];
}
newStudents[theStudents.length] = newStudent;
theStudents = newStudents;
}
public void dropStudent(Student dropStudent) {
Student newStudents[] = new Student[theStudents.length-1];
for (int i = 0; i > theStudents.length; i--)
{
newStudents[i] = theStudents[i];
}
newStudents[theStudents.length] = dropStudent;
}
// add Test Score for a student
public double addTestScore(String newStudent, double testScore) {
testScores[posi] = testScore;
}
/*
* count the number of students in a given class, not the school
*/
public int countClassSize(String course) {
}
// get average average score of a given class
public double averageAverageScore(String course) {
}
/*
* add a programming language to only CS students at the school Will need to
* use the instanceof for proper type casting
*/
public String addProgrammingLanguage(String studentName, String programLanguage) {
}
/*
* Count the number of students in the school that know a certain
* programming language, again will need to typecast properly
*/
public int numberThatKnowLanguage(String programLanguage) {
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
String dropStudent, course;
System.out.println("Welcome to the School. Please select " + "Option 1 to enroll a regular student, \n "
+ "Option 2 to enroll a CompSci student, \n" + "Option 3 to drop a student, \n"
+ "Option 4 to add test score or programming language, or \n" + "Option 5 to perform class analytics.");
int Operation = input.nextInt();
/*
* Simple UI to add and drop students, will need to set the operation to
* call the add and drop students to fit them to the Student body array
* will need to make these two options loop until the user is satisfied
* with the size of the student body
*/
if (Operation == 1) {
System.out.println("Enter the # of regular students that you want to add to the school.");
int addStudents = input.nextInt();
/*
* Possibly create some type of input array to
* make it easier to enter the students' names
*/
System.out.println("Please enter the name and course of the student you are enrolling:");
Student newRegularStudent = (String) input.next();
course = input.next();
}
else if (Operation == 2) {
System.out.println("Enter the # of CompSci students that you want to add to the school.");
int addStudents = input.nextInt();
/*
* Possibly create some type of input array to make it easier to
* enter the students' names
*/
System.out.println("Please enter the name and course of the student you are enrolling:");
Student newCompSciStudent = (String) input.next();
course = input.next();
}
else if (Operation == 3) {
System.out.println("Enter the # of students that you want to drop from the school.");
int dropStudents = input.nextInt();
/*
* Possibly create some type of input array to make
* it easier to enter the students' names
*/
System.out.println("Please enter the name of the student you wish to drop from the school:");
dropStudent = (String) input.next();
/*
* After the first two operations, will need to build to the UI to
* call the other five methods, will need to make it into a
* while/for loop so user can continue to add information as needed.
*/
}
else if (Operation == 4) {
System.out.println("Enter the # for what you want to add to a student's records."
+ "Enter 1 to enter a test score\n " + "Enter 2 to enter a programming language, enter 2.");
int optionNum1 = input.nextInt();
/*
* Possibly create some type of input array
* to make it easier to enter the students' names
*/
if (optionNum1 == 1) {
} else if (optionNum1 == 2) {
}
}
else if (Operation == 5) {
System.out.println("This is the analytics section of this program.\n");
System.out.println("Enter the # for which of the following analytics options that you want performed: "
+ "Enter 1 to count the # of students for a particular class,\n "
+ "Enter 2 to calculate the average average score for all students take a particular course, or\n "
+ "Enter 3 to count the # of CompSciStudents.");
int optionNum2 = input.nextInt();
if (optionNum2 == 1) {
System.out.println("Enter the course name that you want to know the # of students for.");
course = input.next();
Student classSize;
classSize.countClassSize(course);
}
else if (optionNum2 == 2) {
System.out.println("Enter the course name that you want \n"
+ "to calculate the average average test value for.");
course = input.next();
Student testAvg;
testAvg.averageAverageScore(course);
}
else if (optionNum2 == 3) {
System.out.println("Count the # of CompSciStudents who know a \n"
+ "particular programming language by entering that language name now.");
String programLanguage = input.next();
CompSciStudent csStudent;
csStudent.knowsLanguage(programLanguage);
}
}
input.close();
}
}
I don't know if this is the best way, but if I were you, I would just create a new array one size larger or smaller and fill it will the values from the old array each time you add or remove a value. For example:
public void enrollStudent(Student newStudent) {
Students newStudents[] = new Student[theStudents.length+1];
for (int i = 0; i < theStudents.length; i++)
{
newStudents[i] = theStudents[i];
}
newStudents[theStudents.length] = newStudent;
theStudents = newStudents;
}
Not very efficient but hey, it doesn't sound like you're doing anything that needs to be super efficient.
I am unsure of how to do this. I am in a intro to java class and it asks us to use a message box (instead of just system.out.println) I remember we imported something and it was an easy change, but I am unable to find any notes on it.
Furthermore all examples I've found across the web and this site are taking it beyond the scope of this class.
I apologize in advance if this is an incorrect format, this is my first time posting here.
TLDR: Trying to change
System.out.print("Enter renter name: ");
renterName = input.next();
to appear in a message box instead of in the Eclipse Console
I know we imported something (same way we import Scanner) to make this work, but every example I find is essentially saying create your own dialog box methods which is beyond my scope of knowledge, and this class.
COMPLETE CODE IS FOLLOWS:
import java.util.Scanner;
public class RentYourVideo {
public static void main(String[] args) {
int numberOfRentals, finalBill;
VideoRental rental = new VideoRental(); //runs constructor
Scanner input = new Scanner(System.in);
String renterName;
System.out.print("Enter renter name: ");
renterName = input.next();
System.out.print("Enter number of videos to rent: ");
numberOfRentals = input.nextInt();
rental.setRentalFee(); //needs to set rental fee to $5 according to assignment
rental.calculateBill(numberOfRentals); //from prev input
finalBill = rental.getFinalBill();
System.out.println(renterName + " your total bill for " +numberOfRentals+ " videos is $" +finalBill);
input.close();
}
}
//CHANGE ALL PROMPTS & OUTPUT TO DIALOG/MESSAGE BOX!!!!
public class VideoRental {
private int rentalFee, finalBill, numberOfRentals;
public VideoRental() { //constructor method
rentalFee = 0;
finalBill = 0;
}
public void setRentalFee() { //set method
rentalFee = 5;
} //the assignment claims this must set rentalFee = 5
public void calculateBill(int inRented) {
numberOfRentals = inRented;
finalBill = rentalFee * numberOfRentals;
}
public int getFinalBill() {
return finalBill;
}
}
Check this out:
String name = JOptionPane.showInputDialog(null, "Enter name here:");
http://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html
import javax.swing.JOptionPane;
[...]
public static void main(String[] args) {
int numberOfRentals, finalBill;
VideoRental rental = new VideoRental(); //runs constructor
String renterName;
renterName = JOptionPane.showInputDialog(null, "Enter renter name: ");
numberOfRentals = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number of videos to rent: "));
rental.setRentalFee(); //needs to set rental fee to $5 according to assignment
rental.calculateBill(numberOfRentals); //from prev input
finalBill = rental.getFinalBill();
JOptionPane.showMessageDialog(null, renterName + " your total bill for " +numberOfRentals+ " videos is $" +finalBill);
}
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;
}
This program is meant to prompt a user for address information. Identify the address that would come first by zip code, and then print that address.
I'm having a couple of issues. When I try to assign an int value to the apartment variable, I get an error. Same thing with the zip code portion. Once the minimum value is found, then I want to get the index of the minimum value so that I can print the same index value of each arraylist.
Can someone point me in the right direction or give me a good reference for this? I think I'm just confusing a few things.
package newchapter7;
import java.util.*;
/**
*
* #author Crazy
*/
public class Address {
ArrayList<Integer> houses = new ArrayList<>();
ArrayList<String> streets = new ArrayList<>();
ArrayList<Integer> apts = new ArrayList<>();
ArrayList<String> cities = new ArrayList<>();
ArrayList<String> states = new ArrayList<>();
ArrayList<Integer> zips = new ArrayList<>();
int minValue;
/**
* Adds a house number to the address
* #param house house number
*/
public void addHouse(int house)
{
houses.add(house);
}
public ArrayList<Integer> getHouse()
{
return houses;
}
/**
* Adds a street name to the address
* #param street street name
*/
public void addStreet(String street)
{
streets.add(street);
}
public ArrayList<String> getStreet()
{
return streets;
}
/**
* constructor to add an apartment number that equals 0
*/
public void addApt()
{
}
/**
* Adds an apartment number to the address
* #param aptNbr apartment number
*/
public void addApt(int aptNbr)
{
apts.add(aptNbr);
}
public ArrayList<Integer> getAptNbrs()
{
return apts;
}
/**
* Adds a city to the address
* #param city city
*/
public void addCity(String city)
{
cities.add(city);
}
public ArrayList<String> getCity()
{
return cities;
}
/**
* Adds a state to the address
* #param state state
*/
public void addState(String state)
{
states.add(state);
}
public ArrayList<String> getState()
{
return states;
}
/**
* Adds a zip code to the address
* #param zip zip code
*/
public void addZip(int zip)
{
zips.add(zip);
}
public ArrayList<Integer> getZip()
{
return zips;
}
public int arrValue()
{
minValue = zips.indexOf(Collections.min(zips));
return minValue;
}
}
Main
package newchapter7;
import java.util.*;
public class NewChapter7 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Address addy = new Address();
for (int i = 0; i < 3; i++)
{
System.out.print("Please enter a house number: ");
int house1 = in.nextInt();
addy.houses.add(house1);
System.out.print("Please enter the street name: ");
String street1 = in.next();
addy.streets.add(street1);
System.out.print("Please enter an apartment number if applicable: ");
int apartment;
apartment = in.nextInt();
addy.apts.add(apartment);
if (apartment != 0)
{
addy.apts.add(apartment);
}
else
{
addy.apts.add(0);
}
System.out.print("Please enter the city name: ");
String city2 = in.nextLine();
addy.cities.add(city2);
System.out.print("Please enter the state name: ");
String states2 = in.nextLine();
addy.states.add(states2);
System.out.print("Please enter the zip code: ");
int zipC = in.nextInt();
addy.zips.add(zipC);
}
}
}
This is a homework assignment. I think I've confused the material quite a bit and even if this works, I would like to learn a more efficient way to accomplish the same task.
Error
Please enter a house number: 772
Please enter the street name: Apple Drive
Exception in thread "main" java.util.InputMismatchException
Please enter an apartment number if applicable:
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at newchapter7.NewChapter7.main(NewChapter7.java:32)
Java Result: 1
BUILD SUCCESSFUL (total time: 21 seconds)
Assignment:
Implement a class Address. An address has a house number, a street, an optional apartment number, a city, a state, and a postal code. Supply two constructors: one with an apartment number and one without. Supply a print method that prints the address with the street on one line and the city, state, and postal code on the next line. Supply a method public boolean comesBefore (Address other) that tests whether this address comes before another when the addresses are compared by postal code.
Your Address class is mixed up and actually seems backwards to me. I think that you'd be much better off if it represented the state of a single address. If so, then it should not hold ArrayLists, but rather individual fields for a single house with getter and setter methods for each field, a constructor that accepts the field parameters, and perhaps a default constructor that accepts no parameters if desired.
Then if you need to work with many Addresses, you can create a single ArrayList<Address> for this.
Note that as an aside, I wouldn't use int for apartment number or zip code. While these look like numbers and comprise the digits of numbers, they don't behave as numbers. Use String instead.
change
String street1 = in.next();
addy.streets.add(street1);
line to
in.nextLine();
String street1 = in.nextLine();
addy.streets.add(street1);
and other next() to nextLine() also.
Ok the suggestion above is not working this is the full working code, but you have a possible logical error in this. Since it is homework you should be able to solve that. However...
for (int i = 0; i < 3; i++)
{
System.out.print("Please enter a house number: ");
int house1 = in.nextInt();
addy.houses.add(house1);
System.out.print("Please enter the street name: ");
in.nextLine();
String street1 = in.nextLine();
addy.streets.add(street1);
System.out.print("Please enter an apartment number if applicable: ");
int apartment;
apartment = in.nextInt();
addy.apts.add(apartment);
if (apartment != 0)
{
addy.apts.add(apartment);
}
else
{
addy.apts.add(0);
}
System.out.print("Please enter the city name: ");
in.nextLine();
String city2 = in.nextLine();
addy.cities.add(city2);
System.out.print("Please enter the state name: ");
String states2 = in.nextLine();
addy.states.add(states2);
System.out.print("Please enter the zip code: ");
int zipC = in.nextInt();
addy.zips.add(zipC);
}