My goal is the get number of guests associated with the name. However that's not what I am getting.Can you please suggest an alternative solution to this?
public class GuestAdult {
public String guestFname;
public int aNum;
public static ArrayList<String>adGuestName= new ArrayList<String>();
public static ArrayList<Integer>adGuestNum= new ArrayList<Integer>();
public static Scanner userInput= new Scanner(System.in);
public void createAdultList(){
System.out.println("Enter family name: ");
guestFname=userInput.next();
System.out.println("Enter adult guest number: ");
aNum=userInput.nextInt();
adGuestName.add(guestFname);
adGuestNum.add(aNum);
}
public void totalAdultGuests(){
System.out.println("The number of total adults is " + adGuestNum.size());
}
}
Current Output
Enter family name:
R
Enter adult guest number:
2
Add another guest: Y/N
N
The number of total adults is 1 <How can I see 2 here?>
END
An ArrayList is, like the name, a list of items - in your case, a list of Integers. When you take the user's input for the number of guests, you are taking a single Integer with the value 2, then adding it as the first number in adGuestNum, which is a list of numbers. Since calling size() on an ArrayList just gives you the number of elements in the list, and you only added one element (even though that element is 2, 2 is just one number regardless of its value), size() is going to return 1.
Since it looks like you're going to want to add multiple families and loop over some of your code multiple times, you probably want to be adding up the contents of the list, instead of just looking at how many numbers are in the list. For this, you'll need to loop over the list and look at each number, adding it to a counter as you go:
public void totalAdultGuests(){
int totalGuests = 0;
for(Integer guests : adGuestNum) {
totalGuests += guests;
}
System.out.println("The number of total adults is " + totalGuests);
}
This looks at each number in adGuestNum and adds it to the counter totalGuests. Once it's done, it prints out the totalGuests instead of just the number of groups in adGuestNum.
Related
I have an issue for creating an array based on the total amount of numbers entered into the array.
Essentially the program is expected to work as the following: the user is prompted for n numbers to enter into an array. So until the user types '000' as their input, the user will be prompted for a new number.
Note: for this array, I do not want the user to input the amount of numbers they want to enter for the array size. Instead, I want the user to continue inputting random numbers until '000' has been inputted, then, the total amount of numbers that has been entered into the array, is the size of such array.
For example: this would work if we have int array[] = {1, 2, 4, 6}, this will automatically set array size to 4, without actually explicitly declaring the array size as 4 elements. Similarly, with my code, I want it where the numbers that the user enters is added to the array, and then the array size is automatically given from the amount of numbers the user has entered like above.
It is important to note that we do not know the length of the array until the user has entered all n numbers.
I have attempted a skeleton, but it returns a cannot find symbol error:
Code:
//Array Code
import java.util.*;
class setArray {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int stopInput = 000;
int number;
System.out.print("Enter a number: ");
number = input.nextInt();
while(number != stopInput) {
System.out.print("Enter a number: ");
number = input.nextInt();
int array[] = {number};
}
System.out.print("Array size: " + array.length);
} // Main brace
} // Class brace
setArray.java:19: error: cannot find symbol
System.out.print("Array Size: " + array.length);
symbol: variable array
location: class setArray
1 error
You have a few errors here. The first is understanding why you get your immediate error. The variable array is declared within the scope of the while loop. It can not be seen outside of this loop. That is why the compiler is complaining.
The second is that the size of the array (if declared outside of the loop) will always be 1. From my understanding of what you have written as an attempt to solve the problem you have describe shows that you are not tackling the problem correctly.
While you don't known the the final length of the array to be entered; you do need to store the values entered (my inference) to populate the final array. To store the value entered by the user you need a list that will grow with the input.
List<Integer> values = new ArrayList<>();
while (number != stopInput) {
System.out.print("Enter a number: ");
values.add(Integer.valueOf(input.nextInt()));
}
Integer[] array = values.toArray(new Integer[values.size()]);
Firstly, the compilation error is because the array variable is not visible from the System.out.println line. This is because it's declared inside the while loop, so is only visible inside the while loop.
To make it visible to the whole method, declare it before the while loop.
Secondly, arrays cannot be resized. You declare an array to be a certain size, and you cannot add or remove elements.
My suggestion would be to use an ArrayList. Declare one before your loop, and add the new number inside the loop. After the loop, the size should be how many numbers were entered.
Finally, there's no difference between 000 and 0. Is 0 a valid input number?
You can use
List<Integer> array=new ArrayList<Integer>();
while(number != stopInput) {
System.out.print("Enter a number: ");
number = input.nextInt();
array.add(number);
}
This sounds like a job for java.util.ArrayList - this is the array that doesn't have a fixed size and is growing as you add values to it automatically under the covers.
The error is caused because you are creating the array only within the scope of the while loop. You need to create it outside the loop. Secondly, standard arrays are not dynamic, so you would need to either set the size and increase it as needed, or just simply use an ArrayList.
Psuedo:
ArrayList<Integer> list = new ArrayList<Integer>()
...
while(not stop number)
list.add(number)
...
print(list.size())
If you really want to use an Array, here is how you can do it
public static void main(String[] args){
STOP_ENTRY = "000";
scan = new Scanner(System.in);
entry = "";
while(true){
System.out.print("Enter #: ");
String tempS = scan.nextLine();
if(tempS.equals(STOP_ENTRY)) break;
else entry += tempS + ":";
}
String[] split = entry.split(":");
int[] intArray = new int[split.length];
System.out.println("Length of created intArray = " + intArray.length); //length of created array
for(int i = 0; i < intArray.length; i++){
intArray[i] = Integer.parseInt(split[i]);
System.out.println("intArray[" + i + "] => " + String.valueOf(intArray[i]));
}
}
I would recommend an ArrayList, as it dynamically changes is size when you add an element, but do whatever you'd like.
An important note, this does not handle any malicious entry that you might not want (characters, symbols), and will error if they are entered, something you can easily add if you need
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();
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.
I"m trying to make a program that retrieves an endless amount of numbers that user inputs until the user quits and display the numbers .Here is the code I have so far.After entering the first and second number it shows an exception at the line array1[i]=s1
import java.util.Scanner;
public class Program_2 {
public static void main(String[] args) {
int a=1,i;
Scanner sn = new Scanner(System.in);
String[] array1= new String[a];
for(i=0;i<a;i++)
{
System.out.println("Enter Value Number "+ (i+1));
System.out.println("Press Q or q to Exit");
String s1=sn.next();
if(s1.equalsIgnoreCase("q"))
{
for(i=0;i<a;i++)
{
System.out.println("Value of Number "+(i+1)+" is "+ array1[i]);
}
a=0;
}
else
{
array1[i]=s1;
a=(i+2);
}
}
}
}
Your array is of size 1 (a is 1 at the beginning of your code).
The first input works because i is 0 and array1[0] exists. The second input crashes because array1[1] does not exist.
You need to increase your array. That can be done by copying the array into a larger one and using the result of the copy, but that is clumsy.
Better way to do it is to use an ArrayList instead of a simple array and you do not have to worry about the size as it is managed automatically.
For one, a is only incremented when they press q, when you go to the else statement. So the the for loop is going to end after a couple of iterations.
You also set a to 0 in the inside for loop, making sure it won't run more.
Also, your quit code doesn't quit.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Array sorting input
Implement a program to process votes for 5 candidates in a talent
contest.
The program should use a String array to hold the names of the 5
candidates and an integer array to record the number of votes for each
contestant.
It should prompt the user to enter the number of the candidate they
wish to vote for (in the range 0 – 4), until -1 is entered, which
signifies the end of voting. An error message should be output if the
candidate selected is not in the required range.
At the end of voting, the program should sort the votes into
descending order and output them, before outputting messages showing
who was in 3rd, 2nd and 1st place
Well, so far I had some failures that's all. I will not have any problem with sorting and swapping the input. But the input itself is a pain for me.
//exam result processing - using selection sort
import java.util.*;
public class VoteCount {
public static void main(String[] args) {
//create empty array
int[] votes = new int[5];
//input data
input(votes);
}
public static void input(int[] votes)
{
Scanner kybd = new Scanner(System.in);
System.out.println("Enter vote number of the candidate results: ");
int votecount = kybd.nextInt();
while (votecount !=-1)
{
votes[votecount]++;
System.out.println("Candidate" + votes +"Has" +votecount + "votes");
}
}
}
you have to read the user's input inside the while cycle, like this:
Scanner kybd = new Scanner(System.in);
System.out.println("Enter vote number of the candidate results: ");
int votecount = kybd.nextInt();
while (votecount !=-1)
{
votes[votecount]++;
System.out.println("Candidate "+names[votecount]+" Has "+votes[votecount]+" votes");
System.out.println("Enter vote number of the candidate results: ");
votecount = kybd.nextInt();
}
in additional, "votes" is an array, so printing in will give you something like "0#562fb45", so let's say you wil create some "names" array, which will hold the candidates names, like this for example:
String names = {"Peter", "Tomas", "Jonny", "Mark", "Jane"};
You should use kybd.hasNext() to test whether there is any more vote number. and you can input in the terminal like this:
0,1,2,1,3
and modify while() to:
while(kybd.hasNext())
there is no need of -1 to end input, and you have to input all vote number in one line. you can use <space>、comma or <Tab> to split vote numbers.