Help with arrays & counting characters in arrays
I am trying to figure out how to count how many times each characters appears in the array (but I have to do all the counts at once).
I am supposed to store the counts in an int[] array of 27 elements (26 letters & an extra count for everything else). How would I go about declaring the array, allocating it, & then setting each of the 27 elements zero?
Thanks so much the help.
public class CharCount {
public static void main(String[] args) {
new CharCount().process();
public void process() {
// This declares an array of char and then assigns it a value. The value comes from another one
// of my secret programs.
char[] countThese = Lab8.simple();
printChars(countThese);
for (int count =0; count < countThese.length; count++) {
System.out.println(countThese[count]);
// This method should print the characters in the array called print, one-by-one
// Use a println ONLY after all the chars have been printed.
public void printChars(char[] print) {
public int charToInt(char ch) {
if (ch >= 'A' && ch <= 'Z')
return ch - 'A';
else if (ch >= 'a' && ch <= 'z')
return ch - 'a';
else return 26;
}
I take it the charToInt method was given to you. If you don't know what it does, it will give you a value from 0 to 26 depending on what char you pass as a parameter. So if you pass an 'a' or an 'A' it will return 0, 25 for 'z' or 'Z' and 26 for anything else. You use this value to access an array an increment the value (the number of times that letter has occured.
int value = charToInt('a');
arr[value]++;
System.out.println("Number of a's = " + arr[0]);
Similar Messages
-
Need help with connecting file inputs to arrays
In this assignment I have a program that will do the following: display a list of names inputed by the user in reverse order, display any names that begin with M or m, and display any names with 5 or more letters. This is all done with arrays.
That was the fun part. The next part requires me to take the names from a Notepad file, them through the arrays and then output them to a second Notepad file.
Here is the original program: (view in full screen so that the code doesn't get jumbled)
import java.io.*; //Imports the Java library
class progB //Defines class
public static void main (String[] arguments) throws IOException
BufferedReader keyboard; //<-
InputStreamReader reader; // Allows the program to
reader = new InputStreamReader (System.in); // read the the keyboard
keyboard = new BufferedReader (reader); //<-
String name; //Assigns the name variable which will be parsed into...
int newnames; //...the integer variable for the amount of names.
int order = 0; //The integer variable that will be used to set the array size
String[] array; //Dynamic array (empty)
System.out.println (" How many names do you want to input?"); //This will get the number that will later define the array
name = keyboard.readLine ();
newnames = Integer.parseInt (name); // Converts the String into the Integer variable
array = new String [newnames]; //This defines the size of the array
DataInput Imp = new DataInputStream (System.in); //Allows data to be input into the array
String temp;
int length; //Defines the length of the array for a loop later on
for (order = 0 ; order < newnames ; order++) //<-
{ // Takes the inputed names and
System.out.println (" Please input name "); // gives them a number according to
temp = keyboard.readLine (); // the order they were inputed in
array [order] = temp; //<-
for (order = newnames - 1 ; order >= 0 ; order--) //<-
{ // Outputs the names in the reverse
System.out.print (" \n "); // order that they were inputed
System.out.println (" Name " + order + " is " + array [order]); //<-
for (order = 0 ; order < newnames ; order++) //<-
if (array [order].startsWith ("M") || array [order].startsWith ("m")) // Finds and outputs any and all
{ // names that begin with M or m
System.out.print (" \n "); //
System.out.println (array [order] + (" starts with M or m")); //
} //<-
for (order = 0 ; order < newnames ; order++) //<-
length = array [order].length (); //
if (length >= 5) // Finds and outputs names
{ // with 5 or more letters
System.out.print (" \n "); //
System.out.println ("Name " + array [order] + " have 5 or more letters "); //<-
}The notepad file contains the following names:
jim
laruie
tim
timothy
manny
joseph
matty
amanda
I have tried various methods but the one thing that really gets me is the fact that i can't find a way to connect the names to the arrays. Opening the file with FileInputStream is easy enough but using the names and then outputing them is quite hard. (unless i'm thinking too hard and there really is a simple method)By "connect", do you just mean you want to put the names into an array?
array[0] = "jim"
array[1] = "laruie"
and so on?
That shouldn't be difficult at all, provided you know how to open a file for reading, and how to read a line of text from it. You can just read the line of text, put it in the array position you want, until the file is exhausted. Then open a file for writing, loop through the array, and write a line.
What part of all that do you need help with? -
Desperate HELP with Random Numbes in an Array & Do / While
Please somebody help, I have been working this problem for over 7 days now and can't get it. I have tried everything from a while to a do while to this and that. I need to have an Array of 8 that when run will produce random numbers for output between 15 to 25. I CAN"T GET IT PLEASE HELP. I am new to JAVA and have done everything I can think of to resolve this. I even have purchased a new book and looked at every site trying to find a solution. PLEASE HELP! Here it is:
import javax.swing.*;
public class RandomArray{
public static void main (String [ ] args) {
JTextArea outputArea = new JTextArea ( );
int myArray [ ]; //array declaration
myArray = new int [ 8 ]; //allocating memory
String output = "Array values at initializatioon ";
output += "\nIndex\tValues";
for ( int i = 0; i < myArray.length; i ++)
output += "\n" + i + "\t" + myArray [ i ];
output += "\n\nArray values after assigning values within the range of 15 and 25";
do {( int i = 0; i <myArray.length; i++)
while myArray [ i ] = 15 + (int) (Math.random ( ) * 25);
output += "\n" + i + "\t" + myArray [ i ];}
outputArea.setText (output);
JOptionPane.showMessageDialog (null, outputArea,
"Array Value before and after",
JOptionPane.INFORMATION_MESSAGE);
System.exit ( 0 );
The output that I need is in two columns one with the initial array 0-7 and the second should be random numbers 15-25. Please help, pleasehere you are :
import javax.swing.*;
public class RandomArray
public static void main (String [ ] args)
JTextArea outputArea = new JTextArea();
int myArray [] = new int[8];
String output = "Array values at initializatioon ";
output += "\nIndex\tValues";
for (int i = 0; i < myArray.length; i ++)
output += "\n" + i + "\t" + myArray [ i ];
output += "\n\nArray values after assigning values within the range of 15 and 25";
for (int i = 0; i < myArray.length; i++)
myArray [ i ] = 15 + (int) (Math.random ( ) * 10);
output += "\n" + i + "\t" + myArray [ i ];
outputArea.setText(output);
JOptionPane.showMessageDialog (null, outputArea,
"Array Value before and after",
JOptionPane.INFORMATION_MESSAGE);
System.exit(0); -
Need some help with a counting function
Hello,
I use a simple sheet to organize the timetable of my patients. Now I'd like to count how many different patients I attend, without counting a patient twice if I attend him twice a week for example. My sheet looks like this:
Mon
Tue
Wed
Thu
John
Steve
John
Wesley
Mary
Harry
Deborah
Peter
Arnold
Carol
Chris
Mary
Sarah
Karen
Karen
Carol
Larry
Peter
So the answer would be 13, because I attend 13 different patients a week. Fields in blank should no be counted, the cell contend changes frequently.
A friend of mine tried to help me with a countif function but it didn't work out for me, it would count the fields left blank too.
Any idea?
Thanks, gabrielHi Gabriel,
Here's another, more generalized, approach that doesn't need adjusting for maximum number of visits/week at the cost of just a few more formulas. But only two tables!
Formula in A2 and copied down:
=ROUNDUP((ROW(cell)−1)÷$B$27,0)
Formula in B2 and copied down:
=IF(MOD(ROW(cell)−1,$B$27)=0,$B$27,MOD(ROW(cell)−1,$B$27))
The formula in C2 and copied down:
=OFFSET(Schedule::$A$1,0,B−1)
The formula in D2 and copied down:
=IFERROR(OFFSET(Schedule::$A$1,A2,B2−1,rows,columns),"")
The formula in E2 and copied down:
=IF(AND(D2≠0,LEN(D2)>0),COUNTIF($D$1:D2,D2),"")
The formula in F2 and copied down:
=IFERROR(IF(E=1,1,""),"")
The formula in F27: =SUM(F)
The value in B27 is 4, the number of day columns in the Schedule table. You would change that if you increase or decrease the number of days on which you see patients.
Column C is cosmetic, not needed in the calculation.
The error triangle means all of the cells in the Schedule table are already accounted for in the rows above.
Probably more compact ways to do this but it gets the job done.
SG -
Help with inserting counter code
hi friends, i want to put an invisible counter on my website but i cant seem to do it. i got the counter code from statcounter and i also downloaded a trial version of bbedit. in bbedit when i do a search for the code i have to replace bbedit comes up with nothing on the search, im not html savy in the slightest...can somebody walk me through this step by step.
If you want to insert the code by hand, just open each page.html file and scroll to the end. You will see a <body><html> tag. Just copy and paste your code before the <body> tag and the save.
But if you want an easy and automatic way to do this for your pages...just download iComment 3.0. Launch it and paste your StatCounter code in the appropriate window. Then point iComment to your Sites folder and click Go. It will place the StatCounter code on every page in your site.
If you don't want to do the Haloscan commenting, you can just leave that blank in iComment.
James
http://www.dirtdoog.com/ -
Help with French Accent Characters Corrupted
Hi, All.
I am developing a Flex Front end connect with Java back-end.
The back-end sends data retrieved from XML file to the Flex
front-end; displays it in an TextArea, and allow user to change.
After user changes the data, hit "Save" button, then Flex sends the
data to the back-end.
I check with the back-end, make sure the data was correct
when sending out to Flex, and the French accented characters gets
corrupted when sending back from Flex. However, in Flex side, this
change cannot be awared. (i.e. The French accents characters
display correctly in Flex, but sending wrong character back). I'm
guessing that might be something related to character sets.
However, I cannot find anywhere to set character sets in
HTTPService. Anybody has idea?Use Ariel MS Unicode font.
-
Help with "distint count" in query
Hi
I have a query that returns the following error:
ORA 00936: Missing Expression
and also after running it again
I get ORA 00900: Invalid SQL statement.
The query is as follows:
SELECT
DISTINCT student_id,
COUNT(student_id),
ABSENCE_REASON_CODE,
calendar_date,
attendance_status,
FROM AT_HOURLY_ATTENDANCE_RECORDS
WHERE (absence_reason_code = 'UC')
OR (absence_reason_code = '1');all help is gratefully acknowledged. Thanks in advanceHi
Thanks to both guys for helping me out.. (Steven and Gasparatto)
The query still has the following problem:
ORA-00900: invalid SQL statement
I wonder why this is happening..
(Toad is pointing out student_id as a possible culprit
the code again is:
SELECT
DISTINCT student_id,
COUNT(student_id),
ABSENCE_REASON_CODE,
calendar_date,
attendance_status
FROM AT_HOURLY_ATTENDANCE_RECORDS
WHERE (absence_reason_code = 'UC')
OR (absence_reason_code = '1');Please excuse me for my naive questions. I have learnt a lot today itself. Thanks a lot again -
Need help with voltage counter
I have a system that passes current through a resistor when ever a button is pushed. The voltage across the resistor (about 100mV) is read by a cFP-AI-102 Analog Input voltage module. I'm trying to figure out a way to count the number of times this happens. In other words, I need to count how many times the button is pushed.
I've tried using a While Loop, but since it counts with every iteration I end up with way too many counts for each button push. Is there a way I only count once?
Thanks,
EricHi!
If I understand, you want to measure how many times button is pushed, i.e. how many transition 0 -> 100 mV, right? I'd do that with a shift register and a while loop.... just save the past state of the analog in, if the comparison between the past state and curtrent state is > 50 mV, you have a push.... (actually it depends on how terminals are connected...)
Post your code, perhaps I can understand better the starting point.
remember: this way you're going to measure too many transitions, because usually, when a button is pressed or released you have some oscillating voltage (I don't know if you ever tried to handle a switch button with a microcontroller, there you can see this). But maybe, AI module sample at "low frequencies" respect to this phenomenon.
graziano -
Help with number counting project
the program is supposed to let the user enter numbers and and then return the numbers they entered and how many times they entered each one. this is what i have so far and i dont know what i need to put next so can anybody give me a hint or help me please thanks
* Joey McCashland
* 02/04/08
* CS3 AP
* PP 6.1
import java.util.*;
public class PP6_1
public static void main()
ArrayList dean = new ArrayList();
Scanner s = new Scanner (System.in);
int num = 0;
while(( num <= 50) && (num >= 0 ));
System.out.println("Enter any integers from 0 to 50. Enter -1 to stop");
num = s.nextInt();
dean.add(num);
System.out.println(num);
}Edited by: Encephalopathic on Feb 17, 2008 6:02 PM
-
Hey there
A while ago I added javascript to some parts of my PDF around the use of dates and phone numbers, I now have Acrobat 11, and I am at a loss of how to add a new javascript (i cant remember at all) the code I have is
if (!event.willCommit) {
event.change = event.change.replace(/\, "-");
and it does not appear to be working, but if the code is right, then I am guessing I am putting it in the wrong place.
Any help would be awesome.
CheersProbably like this:
// Custom Keystroke script
if (!event.willCommit) {
event.change = event.change.replace(/\, "-");
event.change = event.change.toUpperCase();
If it doesn't work, post what the other script is and where it's placed. -
Help with a COUNT query...
I have created the following tables:
create table ZONE (
ZoneNo number(2),
State char(3),
PRIMARY KEY (ZoneNo)
create table SCHOOL (
SchoolType char(1),
SchoolNumber number(4),
SchoolName char(40),
SchoolZone number(2),
PRIMARY KEY (SchoolNumber,SchoolType),
FOREIGN KEY (SchoolZone) REFERENCES ZONE
create table TEACHER (
TeacherCode char(5),
Surname char(30),
FirstName char(30),
Gender char(1),
WorksFor number(4),
YearCommenced number(4),
LivesIn number(2),
TeachingType char(1),
PRIMARY KEY (TeacherCode),
FOREIGN KEY (WorksFor, TeachingType) REFERENCES SCHOOL(SchoolNumber,SchoolType),
FOREIGN KEY (LivesIn) REFERENCES ZONE
create table COMPUTER (
SerialNumber char(10),
Description char(50),
RegisteredTo char(5),
PRIMARY KEY (SerialNumber),
FOREIGN KEY (RegisteredTo) REFERENCES TEACHER
My question is, how would i make a COUNT (or similar) query that would display each SchoolName and show the total amount of teachers who work at that school in the second column?Yes, it needs to join all columns on foreign key.
This is usual, gentle, safety, and universal approach.
insert into ZONE values (6,'CA');
insert into SCHOOL values ('E',600,'Oracle Elemental School',6);
insert into SCHOOL values ('J',600,'Oracle Middle School',6);
insert into SCHOOL values ('S',600,'Oracle High School',6);
insert into TEACHER values (12001,'Suzuki','Akiko','F',600, 2005, 6, 'E');
insert into TEACHER values (12002,'Scott','Tiger','M',600, 2005, 6, 'E');
insert into TEACHER values (12003,'Zhong','San','M',600, 2005, 6, 'J');
insert into TEACHER values (12004,'Li','Si','M',600, 2005, 6, 'J');
insert into TEACHER values (12005,'Wang','Wu','M',600, 2005, 6, 'J');
insert into TEACHER values (12006,'Kim','Youngae','F',600, 2005, 6, 'S');
insert into TEACHER values (12007,'Kim','Jiu','F',600, 2005, 6, 'S');
insert into TEACHER values (12008, null,'Joe','M',600, 2005, 6, 'S');
column schoolname format a30
set lines 120
select s.SchoolName
,count(*) "ALL"
,count(t.TeacherCode) "ALL(CODE)"
,count(distinct t.TeacherCode) "DISTINCT(CODE)"
,count(t.surname) "ALL(NAME)"
,count(distinct t.surname) "DISTINCT(NAME)"
from School s, Teacher t
where s.SchoolNumber = t.WorksFor
and s.SchoolType = t.TeachingType
group by s.SchoolName
SCHOOLNAME ALL ALL(CODE) DISTINCT(CODE) ALL(NAME) DISTINCT(NAME)
Oracle Elemental School 2 2 2 2 2
Oracle High School 3 3 3 2 1
Oracle Middle School 3 3 3 3 3select s.SchoolName
,count(*) "ALL"
,count(t.TeacherCode) "ALL(CODE)"
,count(distinct t.TeacherCode) "DISTINCT(CODE)"
,count(t.surname) "ALL(NAME)"
,count(distinct t.surname) "DISTINCT(NAME)"
from School s, Teacher t
where s.SchoolNumber = t.WorksFor
--and s.SchoolType = t.TeachingType
group by s.SchoolName
SCHOOLNAME ALL ALL(CODE) DISTINCT(CODE) ALL(NAME) DISTINCT(NAME)
Oracle Elemental School 8 8 8 7 6
Oracle High School 8 8 8 7 6
Oracle Middle School 8 8 8 7 6 -
Given this info:
ID Name Class ID Location ID Location Name
101 John Smith 1001 1A Location 1
101 John Smith 2002 2B Location 2
101 John Smith 3003 2B Location 2
101 John Smith 4004 3C Location 3I want to be able to get this output:
ID Name Max Location
101 John Smith Location 2 Using this:
Select id, name, MAX("Amt") from (select id, name,
(case when location_id = '1A' then Count(pidm_key)
when location_id = '2B' then Count(pidm_key)
when location_id = '3C' then Count(pidm_key) else null end) "Amt"
from Table1
group by id, name, location_id)
group by id, name
I get:
ID Name Amt
101 John Smith 2 But of course I want the other output.What is you db version?
you can use the KEEP syntax for the max aggregate in the outer query.
Along the lines of
not syntax checked
MAX(location_name) keep (dense_rank last order by "Amt") -
Need help with Java app for user input 5 numbers, remove dups, etc.
I'm new to Java (only a few weeks under my belt) and struggling with an application. The project is to write an app that inputs 5 numbers between 10 and 100, not allowing duplicates, and displaying each correct number entered, using the smallest possible array to solve the problem. Output example:
Please enter a number: 45
Number stored.
45
Please enter a number: 54
Number stored.
45 54
Please enter a number: 33
Number stored.
45 54 33
etc.
I've been working on this project for days, re-read the book chapter multiple times (unfortunately, the book doesn't have this type of problem as an example to steer you in the relatively general direction) and am proud that I've gotten this far. My problems are 1) I can only get one item number to input rather than a running list of the 5 values, 2) I can't figure out how to check for duplicate numbers. Any help is appreciated.
My code is as follows:
import java.util.Scanner; // program uses class Scanner
public class Array
public static void main( String args[] )
// create Scanner to obtain input from command window
Scanner input = new Scanner( System.in);
// declare variables
int array[] = new int[ 5 ]; // declare array named array
int inputNumbers = 0; // numbers entered
while( inputNumbers < array.length )
// prompt for user to input a number
System.out.print( "Please enter a number: " );
int numberInput = input.nextInt();
// validate the input
if (numberInput >=10 && numberInput <=100)
System.out.println("Number stored.");
else
System.out.println("Invalid number. Please enter a number within range.");
// checks to see if this number already exists
boolean number = false;
// display array values
for ( int counter = 0; counter < array.length; counter++ )
array[ counter ] = numberInput;
// display array values
System.out.printf( "%d\n", array[ inputNumbers ] );
// increment number of entered numbers
inputNumbers++;
} // end close ArrayYikes, there is a much better way to go about this that is probably within what you have already learned, but since you are a student and this is how you started, let's just concentrate on fixing what you got.
First, as already noted by another poster, your formatting is really bad. Formatting is really important because it makes the code much more readable for you and anyone who comes along to help you or use your code. And I second that posters comment that brackets should always be used, especially for beginner programmers. Unfortunately beginner programmers often get stuck thinking that less lines of code equals better program, this is not true; even though better programmers often use far less lines of code.
// validate the input
if (numberInput >=10 && numberInput <=100)
System.out.println("Number stored.");
else
System.out.println("Invalid number. Please enter a number within range."); Note the above as you have it.
// validate the input
if (numberInput >=10 && numberInput <=100)
System.out.println("Number stored.");
else
System.out.println("Invalid number. Please enter a number within range."); Note how much more readable just correct indentation makes.
// validate the input
if (numberInput >=10 && numberInput <=100) {
System.out.println("Number stored.");
else {
System.out.println("Invalid number. Please enter a number within range.");
} Note how it should be coded for a beginner coder.
Now that it is readable, exam your code and think about what you are doing here. Do you really want to print "Number Stored" before you checked to ensure it is not a dupe? That could lead to some really confused and frustrated users, and since the main user of your program will be your teacher, that could be unhealthy for your GPA.
Since I am not here to do your homework for you, I will just give you some advice, you only need one if statement to do this correctly, you must drop the else and fix the if. I tell you this, because as a former educator i know the first thing running through beginners minds in this situation is to just make the if statement empty, but this is a big no no and even if you do trick it into working your teacher will not be fooled nor impressed and again your GPA will suffer.
As for the rest, you do need a for loop inside your while loop, but not where or how you have it. Inside the while loop the for loop should be used for checking for dupes, not for overwriting every entry in the array as you currently have it set up to do. And certainly not for printing every element of the array each time a new element is added as your comments lead me to suspect you were trying to do, that would get real annoying really fast again resulting in abuse of your GPA. Printing the array should be in its own for loop after the while loop, or even better in its own method.
As for how to check for dupes, well, you obviously at least somewhat understand loops and if statements, thus you have all the tools needed, so where is the problem?
JSG -
Hello guys need help with reverse array
Need help reversing an array, i think my code is correct but it still does not work, so im thinking it might be something else i do not see.
so far the input for the array is
6, 25 , 10 , 5
and output is still the same
6 , 25 , 10 , 5
not sure what is going on.
public class Purse
// max possible # of coins in a purse
private static final int MAX = 10;
private int contents[];
private int count; // count # of coins stored in contents[]
* Constructor for objects of class Purse
public Purse()
contents = new int[MAX];
count = 0;
* Adds a coin to the end of a purse
* @param coinType type of coin to add
public void addCoin(int coinType)
contents[count] = coinType;
count = count + 1;
* Generates a String that holds the contents of a purse
* @return the contents of the purse, nicely formatted
public String toString()
if (count == 0)
return "()";
StringBuffer s = new StringBuffer("(");
int i = 0;
for (i = 0; i < count - 1; ++i)
s.append(contents[i] + ", "); // values neatly separated by commas
s.append(contents[i] + ")");
return s.toString();
* Calculates the value of a purse
* @return value of the purse in cents
public int value()
int sum = 0; // starts sum at zero
for( int e : contents) // sets all to e
sum = sum + e; //finds sum of array
return sum; //retur
* Reverses the order of coins in a purse and returns it
public void reverse()
int countA = 0;
int x = 0;
int y = countA - 1; // 5 - 1 = 4
for (int i = contents.length - 1; i >=0 ; i--) // 4, 3 , 2, 1, 0
countA++; // count = 5
while ( x < y)
int temp = contents[x];
contents[x] = contents [y];
contents [y] = temp;
y = y- 1; // 4 , 3 , 2, 1 , 0
x = x + 1 ; // 0 , 1, 2 , 3 , 4
}ok so i went ahead and followed what you said
public void reverse()
int a = 0;
int b = contents.length - 1;
while (b > a)
int temp = contents[a];
contents[a] = contents;
contents [b] = temp;
a++;
b--;
}and its outputting { 0, 0, 0, 0}
im thinking this is because the main array is has 10 elements with only 4 in use so this is a partial array.
Example
the array is { 6, 25, 10, 5, 0, 0, 0, 0, 0, 0,}
after the swap
{0, 0 , 0 , 0, 0 , 0 , 5 , 10 , 25, 6}
i need it to be just
{ 5, 10, 25, 6}
so it is swapping the begining and end but only with zeroes the thing is i need to reverse the array without the zeroes -
Help with my array problem.
Here I have 3 class. One main class, a class to add passengers and a class to display the seating chart.
A blank seat represented by a "-" is turned into "x". When that is done it goes back to the main class to ask the user if if another passenger wants to be added, display seating chart or quit.
The problem I have is if the user wants to add passengers after the first time then the array is set back to all blanks "-". I need help how on how to use the changed array after the first time so I can build onto existing seats that are already full, but initially the array has to be filled with "-". Also this changed array needs to be sent to the SeatingChart class to display the changed seating chart if the user selects that.
I tried some stuff with tempArray[] but can't figure it out. Any help would be appreciated, thanks.
Main class
import java.util.*;
public class Airline {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int mainOption = 0, passengers = 0;
String seatingClass;
Reservation reserveSeat;
SeatingChart displaySeat = new SeatingChart();
while (mainOption != 3){
mainOption = 0;
// Menu loop
while (mainOption < 1 || mainOption > 3) {
System.out.println("Welcome to the Airline. Please choose an option.\n");
System.out.println(
"Press 1 to add passengers. \nPress 2 to display the " +
"seating chart. \nPress 3 to Quit.");
mainOption = scan.nextInt();
// if statement when 1 is chosen to add passengers
if (mainOption == 1) {
Scanner input = new Scanner(System.in);
// User chooses first or economy class
do {
System.out.println("Type E for economy or F for first class:");
seatingClass = input.nextLine();
while (!seatingClass.equalsIgnoreCase("e") &&
!seatingClass.equalsIgnoreCase("f"));
// If statement to get number of passengers for economy class
if (seatingClass.equalsIgnoreCase("e")) {
do {
System.out.println("Enter the numbers of passengers: ");
passengers = scan.nextInt();
while (passengers < 1 || passengers > 3);
// If statment to get number of passengers for first class
if (seatingClass.equalsIgnoreCase("f")) {
do {
System.out.println("Enter the numbers of passengers: ");
passengers = scan.nextInt();
while (passengers < 1 || passengers > 2);
// Passes info to Reservation class
reserveSeat = new Reservation(seatingClass, passengers);
// Prints out seating chart
System.out.println(reserveSeat);
// if statement when 2 is chosen to display seating chart
if (mainOption == 2) {
System.out.println(displaySeat);
// if statement when 3 is chosen to quit
if (mainOption == 3) {
System.exit(0);
} reservation class for adding passengers.
[codepublic class Reservation {
private String seatClass;
private int numPassengers;
// First class has 8 seats (2 rows of 4 seats each)
String[] firstClassSeat = new String[8];
// Economy class has 24 seats (4 rows of 6 seats each)
String[] economyClassSeat = new String[18];
// Temp array for first class
String[] tempArrayF = new String[8];
// Temp array for economy class
String[] tempArrayE = new String[18];
public Reservation(){
for (int i = 0; i < firstClassSeat.length; i++)
firstClassSeat[i] = "-";
for (int i = 0; i < economyClassSeat.length; i++)
economyClassSeat[i] = "-";
public Reservation(String c, int p) {
seatClass = c;
numPassengers = p;
for (int i = 0; i < firstClassSeat.length; i++)
firstClassSeat[i] = "-";
for (int i = 0; i < economyClassSeat.length; i++)
economyClassSeat[i] = "-";
for (int i = 0; i < tempArrayF.length; i++){
tempArrayF[i] = firstClassSeat;
for (int i = 0; i < tempArrayE.length; i++){
tempArrayE[i] = economyClassSeat[i];
// First class statements
if (seatClass.equalsIgnoreCase("f")) {
if (numPassengers == 1){
int countF = 0;
for (int i = 0; i < firstClassSeat.length; i++){
if (countF < 1){
// If seat is blank - then fill seat with x
if (firstClassSeat[i] == "-"){
firstClassSeat[i] = "x";
countF++;
// Economy class statements
if (seatClass.equalsIgnoreCase("e")) {
if (numPassengers == 1){
int countE = 0;
for (int i = 0; i < economyClassSeat.length; i++) {
if (countE < 1){
// If seat is blank - then with seat with x
if (economyClassSeat[i] == "-"){
economyClassSeat[i] = "x";
countE++;
for (int i = 0; i < tempArrayF.length; i++){
tempArrayF[i] = firstClassSeat[i];
for (int i = 0; i < tempArrayE.length; i++){
tempArrayE[i] = economyClassSeat[i];
Getter Methods
public String getSeatingClass() {
return seatClass;
public int getNumPassengers() {
return numPassengers;
public String[] getFirstClassSeat(){
return firstClassSeat;
public String[] getEconomyClassCeat(){
return economyClassSeat;
public String toString(){
int f = 0, e = 0, count1;
String text = "";
while (f < 8) {
if (f == 0 || f == 4 || f == 2 || f == 6) {
text += firstClassSeat[f];
f++;
if (f == 1 || f == 5) {
text += firstClassSeat[f] + "\t";
f++;
if (f == 3 || f == 7) {
text += firstClassSeat[f] + "\n";
f++;
while (e < 18) {
if (e == 0 || e == 1 || e == 3 || e == 4 || e == 6 || e == 7 ||
e == 9 || e == 10 || e == 12 || e == 13 || e == 15 || e == 16) {
text += economyClassSeat[e];
e++;
if (e == 2 || e == 8 || e == 14) {
text += economyClassSeat[e] + "\t";
e++;
if (e == 5 || e == 11 || e == 17) {
text += economyClassSeat[e] + "\n";
e++;
return text;
Display Seating chart class
public class SeatingChart extends Reservation{
String seatClass;
int numPassengers;
// First class has 8 seats (2 rows of 4 seats each)
String[] firstClassDisplay = new String[8];
// Economy class has 24 seats (4 rows of 6 seats each)
String[] economyClassDisplay = new String[24];
public SeatingChart(){
public SeatingChart(String[] f, String[] e) {
firstClassDisplay = f;
economyClassDisplay = e;
Getter Methods
public String[] getFirstClassDisplay(){
return firstClassDisplay;
public String[] getEconomyClassDisplay(){
return economyClassDisplay;Then how do I pass the information and keep the same object and not let it get set skip over the initialation part in Class Reservation so it doesn't go back too "-".
Heres some updated since we can't edit. But it still doesn't work.
Main Airline class
import java.util.*;
public class Airline {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int mainOption = 0, passengers = 0;
String seatingClass;
Reservation reserveSeat;
SeatingChart displaySeat = new SeatingChart();
while (mainOption != 3){
mainOption = 0;
// Menu loop
while (mainOption < 1 || mainOption > 3) {
System.out.println("Welcome to the Airline. Please choose an option.\n");
System.out.println(
"Press 1 to add passengers. \nPress 2 to display the " +
"seating chart. \nPress 3 to Quit.");
mainOption = scan.nextInt();
// if statement when 1 is chosen to add passengers
if (mainOption == 1) {
Scanner input = new Scanner(System.in);
// User chooses first or economy class
do {
System.out.println("Type E for economy or F for first class:");
seatingClass = input.nextLine();
while (!seatingClass.equalsIgnoreCase("e") &&
!seatingClass.equalsIgnoreCase("f"));
// If statement to get number of passengers for economy class
if (seatingClass.equalsIgnoreCase("e")) {
do {
System.out.println("Enter the numbers of passengers: ");
passengers = scan.nextInt();
while (passengers < 1 || passengers > 3);
// If statment to get number of passengers for first class
if (seatingClass.equalsIgnoreCase("f")) {
do {
System.out.println("Enter the numbers of passengers: ");
passengers = scan.nextInt();
while (passengers < 1 || passengers > 2);
// Passes info to Reservation class
reserveSeat = new Reservation(seatingClass, passengers);
// Prints out seating chart
System.out.println(reserveSeat);
// if statement when 2 is chosen to display seating chart
if (mainOption == 2) {
System.out.println(displaySeat);
// if statement when 3 is chosen to quit
if (mainOption == 3) {
System.exit(0);
}Reservation class
public class Reservation extends Airline{
private String seatClass;
private int numPassengers, count;
// First class has 8 seats (2 rows of 4 seats each)
String[] firstClassSeat = new String[8];
// Economy class has 24 seats (4 rows of 6 seats each)
String[] economyClassSeat = new String[18];
// Temp array for first class
String[] tempArrayF = new String[8];
// Temp array for economy class
String[] tempArrayE = new String[18];
public Reservation(){
for (int i = 0; i < firstClassSeat.length; i++)
firstClassSeat[i] = "-";
for (int i = 0; i < economyClassSeat.length; i++)
economyClassSeat[i] = "-";
public Reservation(String c, int p) {
seatClass = c;
numPassengers = p;
if (count < 1){
for (int i = 0; i < firstClassSeat.length; i++)
firstClassSeat[i] = "-";
for (int i = 0; i < economyClassSeat.length; i++)
economyClassSeat[i] = "-";
if (count > 0){
for (int i = 0; i < tempArrayF.length; i++) {
firstClassSeat[i] = tempArrayF;
for (int i = 0; i < tempArrayE.length; i++) {
economyClassSeat[i] = tempArrayE[i];
// First class statements
if (seatClass.equalsIgnoreCase("f")) {
if (numPassengers == 1){
int countF = 0;
for (int i = 0; i < firstClassSeat.length; i++){
if (countF < 1){
// If seat is blank - then fill seat with x
if (firstClassSeat[i] == "-"){
firstClassSeat[i] = "x";
countF++;
// Economy class statements
if (seatClass.equalsIgnoreCase("e")) {
if (numPassengers == 1){
int countE = 0;
for (int i = 0; i < economyClassSeat.length; i++) {
if (countE < 1){
// If seat is blank - then with seat with x
if (economyClassSeat[i] == "-"){
economyClassSeat[i] = "x";
countE++;
for (int i = 0; i < tempArrayF.length; i++){
tempArrayF[i] = firstClassSeat[i];
for (int i = 0; i < tempArrayE.length; i++){
tempArrayE[i] = economyClassSeat[i];
count++;
Getter Methods
public String getSeatingClass() {
return seatClass;
public int getNumPassengers() {
return numPassengers;
public String[] getFirstClassSeat(){
return firstClassSeat;
public String[] getEconomyClassCeat(){
return economyClassSeat;
public String toString(){
int f = 0, e = 0, count1;
String text = "";
while (f < 8) {
if (f == 0 || f == 4 || f == 2 || f == 6) {
text += firstClassSeat[f];
f++;
if (f == 1 || f == 5) {
text += firstClassSeat[f] + "\t";
f++;
if (f == 3 || f == 7) {
text += firstClassSeat[f] + "\n";
f++;
while (e < 18) {
if (e == 0 || e == 1 || e == 3 || e == 4 || e == 6 || e == 7 ||
e == 9 || e == 10 || e == 12 || e == 13 || e == 15 || e == 16) {
text += economyClassSeat[e];
e++;
if (e == 2 || e == 8 || e == 14) {
text += economyClassSeat[e] + "\t";
e++;
if (e == 5 || e == 11 || e == 17) {
text += economyClassSeat[e] + "\n";
e++;
return text;
display seat class
public class SeatingChart extends Reservation{
String seatClass;
int numPassengers;
// First class has 8 seats (2 rows of 4 seats each)
String[] firstClassDisplay = new String[8];
// Economy class has 24 seats (4 rows of 6 seats each)
String[] economyClassDisplay = new String[24];
public SeatingChart(){
public SeatingChart(String[] f, String[] e) {
firstClassDisplay = f;
economyClassDisplay = e;
Getter Methods
public String[] getFirstClassDisplay(){
return firstClassDisplay;
public String[] getEconomyClassDisplay(){
return economyClassDisplay;
Maybe you are looking for
-
Posting on required field for CO-PA in MIRO
We are using MIRO for all our postings on vendors (one workflow) When we are making postings is possible in a situation that we crated the CO-PA posting without the required field for CO-PA. Steps: We fill in all information from the posting like Bu
-
I found two answers to the Safari going dead on me after a Security Update
I don't know if this helps but I will try not to make this too long. I was confronted with a Mac Software Update out of the blue and didn't expect it, so I complied and let it do its thing. It took about 30 minutes but everything seemed to work ok bu
-
MSI 915p Thoughts & ram questions
Hi All, I'm thinking of buying one of MSI 915P neo2 Platinum motherboards, but i have a couple of questions. Firstly i'm having dificulty finding reviews for this mobo, so i've come here to see what you think of it (unbiased of course). Sec
-
I have an ABAP program that creates multiple reports that are individually sent to various supervisors as an attachment to a workflow (one supervisor/agent per report/workitem). The supervisors (wf agents) will open their work item and choose to eit
-
I want to know about my desktop subseries
It is 3000H SERIES desktop,but i m not aware of subseries whether it is h105or h100 or anything else,how could i know about it.