I am trying to create a program for an assignment in Java and are looking for a push in the right direction. I am currently taking the class online so asking a teacher for help is not an option for me.
I am trying to create a simple java program that allows a user to enter their first name and last name, and their requested seat number. If the seat is taken, the program is supposed to find the nearest available seat. So far I have succeeded at getting all the input from the user (albeit in a roundabout way) and creating and printing an array.
Question
Can I store boolean values in an array? I just want to store false if the seat is taken and then have and if else statement test for true or false, and store a false if the value returned is true(very confusing but thats my train of thought) is there an easier way to go about this? Also how would I also store the persons first and last name with that boolean value? Do I have to create a seperate array? I have attached my code so far that succeeds in getting the user info and printing out an array.
//Import scanner and arrays
package airlinereservations;
import java.util.Scanner;
import java.util.Arrays;
public class AirlineReservations {
public static void main(String[] args) {
//Print the header
System.out.println("___________________________________");
System.out.println("|WELCOME TO FLY BY NIGHT AIRLINES!|");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
// Promt user for first and last name
System.out.println("Please enter your first name:");
Scanner scan= new Scanner(System.in);
String first = scan.nextLine();
System.out.println("Please enter your last name:");
String last = scan.nextLine();
//Greet the user
System.out.println("Hello! " + first + " "+ last);
//Get the requested seat
System.out.println("Please enter your requested seat row number 1-9:");
int rowz = scan.nextInt();
System.out.println("Please enter your requested seat column number 1-4:");
int colz = scan.nextInt();
//Tell the user if the seat is already taken
if(int rowz == rowz, System.out.println("This seat is already taken!"));
else(return true);
//Print out the array
int[][] Seating= new int[9][4];
for(int row=0; row<Seating.length; ++row){
for(int col=0; col<Seating[row].length; ++col){
Seating[row][col] = (row + col) % 9 + 1;
for(int ro=0; ro<Seating.length; ++ro);
}
System.out.println();
for(int col=0; col<Seating [row].length; ++col)
System.out.print(Seating[row][col]);
}
System.out.println();
}
}
For a push in the right direction, as you said, I see two quick options to consider:
One would be to add a Map. This would allow you to store a bunch of key-value pairs which you could use to represent seats, and whether or not they are taken.
Another option is to create a Seat class, that has a field for seatName and whether or not it is taken, and you could create an Array of these seat objects.
If you don't know where to begin on implementing either of those, I will help you, but I challenge you to at least try implementing one or the other first.
EDIT
Or, even more simply, you could create a two-dimensional array holding strings, like this:
String[][] seats = new int[numberofseats][2];
seats[0][0] = "Seat Number 1";
seats[0][1] = "true";
And you can force that second dimension to only hold values true or false, and later check them like this:
if(seats[0][1].equals("true")) // Then seat number 1 is taken
This might not be the best solution as far as error handling, but it is a possibility.
EDIT 2 If you were to create a seat class, I would set it up like this:
public class Seat{
private String seatName;
private boolean isTaken;
public Seat(String s, boolean t){
this.seatName = s;
this.isTaken = t;
}
public boolean isSeatTaken(){
return this.isTaken;
}
}
Then, later you can do something like this:
ArrayList<Seat> myArrayList = new ArrayList<Seat>(); // Or a regular array if you prefer
// Add elements
// Below checks if first seat in list is taken
boolean firstSeatTaken = myArrayList.get(0).isSeatTaken();
Related
I have created an Array holding [24] data, and I assigned some information in each index. my problem is when I want to call the indexes using Scanner from the keyboard, let's say I called index[12] from the user, next time I call it I want it to say, u already selected that number, choose a different number so on so forth. basically, I shouldn't call the same index twice, what is the best thing to use.
your help is much needed.
Use a java.util.Set to store the selected indexed, for exmaple, java.util.HashSet.
It should look like:
Set<Integer> selected = new HashSet<>();
int userInput = ...; // get input from user
while (selected.contains(userInput)) {
// print u already selected that number, choose a different number so on so forth
userInput = ...; // get input from user
}
selected.add(userInput);
// do something with the index
You must save the index of selected numbers, and then you make a comparison of all new numbers with your list's elements.
Scanner s = new Scanner (System.in);
int choice = s.nextInt();
List<Integer> choiced = new ArrayList<Integer>();
while (true) {//or your condition
label:
for (Integer i : choiced) {
if (choice == i) {
System.out.println("Index already selected, please select a different one");
break label;
}
}
choiced.add(choice);
choice = s.nextInt();
}
I tried both of your ways but still could solve it here is my code how would u have applied the codes that u guys wrote in here.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int number = 0;
String [] differentChocolate = new String[24];
differentChocolate[0] = "You receive: A star that weighs 7 grams";
differentChocolate[1] = "You receive: Praline Bag Assorted 800g";
differentChocolate[2] = "You receive: Kinder Surprise Santa 75g";
differentChocolate[3] = "You receive: Woolworths Christmas Chocolate Net Bag 72g";
differentChocolate[4] = "You receive: Quality Street Tub 726g";
differentChocolate[5] = "You receive: Cadbury Favourites Snowman Bowl 700g";
differentChocolate[6] = "You receive: Lindt Santa Pouch Bag 80g";
differentChocolate[7] = "You receive: Praline Bag Assorted 800g";
while (true){
System.out.println("Choose a chocolate (0-23): ");
number = in.nextInt();
System.out.println(differentChocolate[number]);
}
}
}
I am trying to generate an arraylist in java by first inputting the default size desired of the said arraylist. Then I want to get the user to input the string to fill the arraylist. I have made one that almost works. The only problem is that for some reason I get a default value at the start.
For example, if I set the list length to 3 the list returned is: [,example,value,here]. I understand a value of 3 means 4 values in a list but I feel like that just doesn't look too nice. The problem I think lies in the way I set the size of the list but I don't see any other way.
When I set the list value manually in the for loop I don't get this problem. It only happens when I want the user to input the length. Where is the small error?
import java.util.*;
public class ListsPractice {
public static void main(String[] args) {
Scanner userin = new Scanner(System.in);
System.out.println("Enter length of desired list: ");
int lenlist = userin.nextInt();
ArrayList list1 = new ArrayList();
for(int counter = 0; counter <= lenlist; counter++) {
System.out.println("Enter an element: ");
String value=userin.nextLine();
list1.add(value);
}
System.out.println("the result is: "+list1.subList(1, lenlist+1));
}
}
I have to make a Java Program, where a user type in the total numbers of students, so I made this code:
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
int numReaders = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of magazin readers:");
numReaders = scan.nextInt();
Now, after adding the total number of students, we should add their names into an array:
//Creating an array of names, where the length is the total number entered by the user
String[] nameStr = new String[numReaders];
int[] ages = new int[numReaders];
for(int i=0; i<numReaders; i++)
{
Scanner n = new Scanner(System.in);
System.out.println("Enter the name of reader: "+i);
nameStr[i] = n.next();
}
After that, we should add correspondingly the age of each name, so I made this portion of code:
for(int i=0; i<numReaders; i++)
{
Scanner a = new Scanner(System.in);
System.out.println("Enter the age of reader: "+i);
ages[i] = a.nextInt();
}
//Display the results
System.out.println("Number of readers is: "+numReaders);
for (int i=0; i<numReaders; i++)
{
System.out.println("The name of reader "+i+" is "+nameStr[i]+ " and his age is "+ages[i]);
}
After making this code, I tested it using Ideone and Command Prompt and it works properly:
Now, I need to call method according to selection of the user:
if he typed 'a' a method should be called to specify the name and the age of the oldest student.
If he typed 'b' a method called to see how many students have an age specified by the user and If he typed 'c', a function called to calculate the average age of them all.
I am new to methods so I don't know how to add arrays into methods and make statements.
Here is the full code:
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
int numReaders = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of magazin readers:");
numReaders = scan.nextInt();
//Creating an array of names, where the length is the total number entered by the user
String[] nameStr = new String[numReaders];
int[] ages = new int[numReaders];
for(int i=0; i<numReaders; i++)
{
Scanner n = new Scanner(System.in);
System.out.println("Enter the name of reader: "+i);
nameStr[i] = n.next();
}
for(int i=0; i<numReaders; i++)
{
Scanner a = new Scanner(System.in);
System.out.println("Enter the age of reader: "+i);
ages[i] = a.nextInt();
}
//Display the results
System.out.println("Number of readers is: "+numReaders);
for (int i=0; i<numReaders; i++)
{
System.out.println("The name of reader "+i+" is "+nameStr[i]+ " and his age is "+ages[i]);
}
//Choosing a statistic
//if a:
System.out.println("Please choose a, b or C:");
Scanner stat = new Scanner(System.in);
char X;
X = stat.next().charAt(0);
if(X=='a')
System.out.println(X+X);
else if(X=='b')
//System.out.println(X);
//Scanner newAge = new Scanner(System.in);
//int ageToSearchFor = newAge.nextInt();
//maxAge(ageToSearchFor);
else
System.out.println(X);
}
}
Right, so to start with your user enters an input, for example 'a', so let's go with this:
Firstly, you need to create the method where the name of the oldest student is displayed, so let's call it 'getOldestStudent' - when naming methods this is the typical naming convention, starting lowercase and then moving to uppercase for each new word - try and make them as intuitive as possible.
When making the method signature, you need to give it its visibility and also what it is going to return. In this case, as you are only using one class, we will give it private, so it is only visible by this class.
Now we need to return 2 things, so we can either put these into a string or put them into an array, which is what I would recommend, so we are going to return an array. However, you want to input an array to search through, so this goes in tbe brackets as parameters (or arguments). Therefore our method signature is the following:
private String[] getOldestStudent(String[] students, int[] ages)
Then inside this method, you can simply do the code you need to find the oldest student, add their name and age to the array and then return this.
Need anymore help just drop a comment.
On a side note, you would have been better off creating a 'Student' object and then giving this object a 'name' property and an 'age' property and then simply making an array of students and getters and setters (or accessors and mutators) for these properties.
James Lloyd's covers your question pretty well, I thought I might add some input as I think you are struggling with some principles.
At first, I would do as James advised and create a class Student that stores the values for each person.
public class Student {
public String name;
public int age;
// Constructors allow you to create a new Object and set some variables
// when you create it.
public Student (String name) {
this.name = name;
}
}
I used public to avoid getters and setters for this explanation, but I'd use private most had I to write it by myself.
Anyways, that way you only have to use one instead of two arrays (and name and age are connected with each other, e.g., you know the age of a student you know the name of, whereas with two different arrays it could happen that you don't know if nameArray[0] belongs to ageArray[0].
So you have an array Student[] students = new Student[numReaders]; and you can set each Student after reading the input, i.e., after reading the name you call students[i] = new Student(name); If you want to set the age of a Student afterwards you can do so by using student[i].age = age.
Now that we have filled our array, we can advance to your actual question.
char method;
method = stat.next().charAt(0);
// I think switch is a little easier to read for such cases
switch(method) {
case 'a': Student oldest = getOldestStudent(students);
if (oldest != null)
System.out.println(oldest.name);
break;
case 'b': //another method
break;
default: // equals to else as if none of the other cases was fulfilled
break;
}
Now you can write your own method for each scenario you have to cover.
public Student getOldestStudent(Student[] students) {
// at first we check some cases that do not require further checks
if (students.length == 0) {
System.out.println("No students have been specified");
return null; // this might lead to a NullPointerException so check the return Object whether it is null before doing anything with it
} else if (students.length == 1)
return students[0];
// no we have to see which students if the oldest in the regular case
// the first student will be used for comparison
Student oldestStudent = students[0];
for (int i = 1; i < students.length; i++) {
// see if our current student is older
if (oldestStudent.age < students[i].age)
oldestStudent = students[i];
}
return oldestStudent;
}
This way you can easily access the Students name afterwards (see above in the switch). You can build all your methods like this by passing the array to the methods and iterating through it. Depending on whether you want to return one or more Students (as it might vary between the different methods) you have to change the return type from Student to Student[].
Hi I am encountering a problem with a uni project I am working on. I am trying to validate the input so that the BookID that is entered when attempting to loan the book, is only valid if it exists in the array named 'BookList'. At the minute I have it working so that it validates it to make sure that an integer is entered, and not letters or negative numbers.
I have tried endlessly but I am stuck completely?? any tips or help, I would much appreciate it.
thanks
//loan a book method
public void loanBook() {
int loanID;
do {
System.out.println("Please enter the Book ID of the book that you wish to borrow");
while (!input.hasNextInt()) { // checking that the ID entered is an integer - validation
System.out.println("That is not an integer");
input.nextLine(); //pushing the scanner on
}
loanID = input.nextInt(); //setting the loanID variable equal to the input from the scanner.
}
while (loanID < 0 || loanID > 100000000); //VALIDATION - NEED TO CHANGE SO THAT WHILE LOAN ID EXISTS IN ARRAY LIST ????
for (int i = 0; i < BookList.size(); i++) { //for loop to go through and check for the ID entered to remove the book that it corresponds to
if (BookList.get(i).getBookID() == loanID ) {
System.out.println("The book named : " + BookList.get(i).getTitle() + " has now been taken out on loan. Please return within 2 weeks!");
BookList.get(i).setStatus("On Loan");;
}//end of if statement
}//end of for loop
} //end of return book method
You can use the .contains() method for Arraylists. You just need to make sure you are removing items depending on their status.
if(bookList.contains(loanID)){
//logic for book exists
}else{
//book is on loan.
}
Now as I said you need to make sure you are doing proper verification for removing of the books on loan etc for this to work. The way you have your logic right now is doing a LOT of unnecessary work with your loops. This way you can easily scan the list and find the item needed. Of course there are better ways to set up your lists etc but this should work keeping your code very similar.
EDIT
You requested information on how you would find the index of the item after you have verified it exists. This is still very simple. Once you have verified that the item exists you would use the line:
int index = bookList.indexOf(loanID);
This will return the index in your ArrayList for the location of the book. Once you have the index you can begin doing everything you were doing before with:
bookList.get(index).getBookId();
or
bookList.get(bookList.indexOf(itemId)).getBookId();
This is almost exactly what you were doing previously but cut down to 3 lines and can be made even shorter.
if (BookList.contains(loanID)) {
int index = BookList.indexOf(loanId);
if (!BookList.get(index).getStatus().equals("On Loan")) {
System.out.println("The book named: " + BookList.get(index).getTitle() + " has now been taken on loan.");
BookList.get(index).setStatus("On Loan.");
}else{
System.out.println("Book is on loan already.");
}
}else{
//logic for not existing.
}
Create a variable int isExist = 0; After getting the input from user...go through the array and see if that book exists. Then make isExist=1; And then of the loop just make if statement
if( isExist == 0) {
System.out.println("Book is not found");
}
By the way once you have found the book in the array you want to break out of the loop using break;
I am making a program that prompts the user for 3 integers and prints out the biggest one chosen. I am stuck with 2 problems at the moment. I would like to know how I can make the program so that the user can only choose integers from the array. I would also like to know how to find and print out the biggest integer from the ones that the user chose. I'm quite new to programming so all feedback is appreciated.
Thanks!
import java.util.Scanner;
public class Lab14C // name of class file
{
public static void main(String [] args)
{
int[] array = {0,1,2,3,4,5,6,7,8,9};
for(int i=0; i<array.length; i++)
{
System.out.print(array[i] + " ");
}
System.out.println("\n");
Scanner array1 = new Scanner(System.in);
System.out.println("What is your first integer? ");
double array11 = array1.nextInt();
Scanner array2 = new Scanner(System.in);
System.out.println("What is your second integer? ");
double array22 = array2.nextInt();
Scanner array3 = new Scanner(System.in);
System.out.println("What is your third integer? ");
double array33 = array3.nextInt();
System.out.println("\n");
}
}
I don't think there is a way to force a user to input an element. Few things you could do is :
Tell the user he has to select a number in a particular range.
Keep the input statement in a loop. If the entered element exists in array , go ahead. Else tell the user to enter again.
Printing the biggest integer can be done using Math.max(double,double) function. For three elements you can try System.out.println("Max of three is "+Math.max(array11,Math.max(array22,array33)))
You can do it yourself if you want instead of built in function like:
if(array1>array2&&array1>array3)
//print max as array1
else if(array2>array1&&array2>array3)
//print max as array2
else //print array3 as max
Also change your element types to int as you are reading integer.
1) There is no need to create a new Scanner all the time.
Just create one Scanner (which I would just call input or scanner or something that makes sense).
2) If you're reading int's why are you storing them in doubles?
3) To check for a certain condition you use if(*condition*) { /*do something */ }. So if you want to check if x is smaller than y you do if(x < y) { /* do something */ }. (In your case you'll want to check if current input is greater than biggest input and if so set the biggest input to current input.)
4) For a sorted array you can use Arrays.binarySearch(array, elementToSearch) which will return the index of the element when found, or a negative number if not found (the negative number is (-(insertionPoint)-1)). (So you can check if the number entered by the user is in the array and keep asking for a new number if is not.)
1) How I can make the program so that the user can only choose integers from the array.?
You are declaring array variable as int[] so it stores only integer values. Whenever you retrives the value from this array, it returns int value only so you don't have to worry about it.
2)how to find and print out the biggest integer from the ones that the user chose.?
To find the maximum or minimum from a set of values, Java provide a function name Math#max(). You can use it like this :
int maxValue = Math.max(Math.max(array11,array22),array33);
Here is the doc for Math library.