Download The characters // denote my comments or explanations of what a

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
The characters // denote my comments or explanations of what a line of code
does. // is the character command within java that tells the program you are
making comments. The compiler will skip over the comments. Use // for
single line comments. Use /* blahblahblah */ for multiple line comments.
Program structure:
public class name
{
public static void main (String [] args)
{
Body of your program
}} //close the initial curly brackets.
//replace “name” above with your program’s name. (ex. profitCalculator,
myProgram, diceRoller, etc.) Program name must be the same as the .java file name
that you save the program under (case-sensitive). Symbols and numbers can be
used in the program name (I wouldn’t use symbols if I could help it though). Name
your programs logically so that they are easy to distinguish and find.
//public is always lower case and String always upper case in this structure. These
statements will not compile if they are followed by semi-colons as most other java
statements should be.
Data types:
int value = 10; // Creates a variable named value and sets it equal to 10. Note int is
lower case, the variable name “value” is lower case, any name can be given to a
variable (however you don’t want to use names that java has a definition for. For
example, “double” or “integer” aren’t good variable names. The program may run
properly but may be confusing to someone using your program). Use logical names
for your variables. Finally, this statement ends in a semi-colon.
int value1 = 13.5; // note that numbers can be used in variable names. Integer
values do not have decimals and the value of variable1 would be cut to 13 in your
calculations.
double newVariable = 14.6943; // double is lower case. Double values have
decimals and can store large numbers, however more space is allocated to double
values than integer values. This slows down a program and makes a program
larger. Note the capitalization of the variable name. This is camel hump formatting
where a second word is capitalized to distinguish it from a preceding word.
String phrase1 = “There are two kinds of people in the world.”; // assigns the value
“There are two kinds of people in the world.” To a string named phrase1. String
must be capitalized and the content of it must be encased in quotes. A string is
simply a line of text.
char myCharacter = ‘a’; Assigns the letter “a” to a variable named myCharacter.
Note the character you assign to the variable is encase in single rather than double
quotes. Char is lower case. Ends with a semi-colon.
boolean found = true; // assigns true to a Boolean variable named found.
final double GRAVITY = 9.8; // final followed by the declaration of a variable is used
to designate a constant. It is conventional to use all caps to name a constant. Final
must be lower case.
//Other data types exist but are used infrequently. Among them are float, short,
long, and byte.
Displaying data:
System.out.println(); // displays data within the parentheses.
System.out.println(“The door is red.”); //displays The door is red. The command
println means that if you display something else it will be displayed on the line
below “The door is red.” The command System.out.print does not enter down to the
next line. Note that System must be capitalized.
int cost = 909; //assigns value 909 to an integer variable named cost.
System.out.println(cost); // displays that value of cost. Displays 909 and enters
down to the next line.
int cost = 909;
int variable1=3;
System.out.print(cost);
System.out.print(variable1)
//generates the following display:
9093
int cost = 909;
int variable1=3;
System.out.println(cost);
System.out.println(variable1)
//generates the following display:
909
3
//I almost always use println.
Concatenation (putting things together):
Addition vs. concatenation
Addition:
System.out.println(5+4); //9
int variable1=10;
int variable2=12;
System.out.println (variable1+variable2); //22
Concatenation:
int variable1=9;
System.out.println(“A bag of dog food costs $“+variable1+” at Wal-Mart.”); //A bag
of dog food costs $9 at Wal-Mart. Concatenation puts different variable together
when they can’t be added as with numbers. Note the space before the $ sign and
before “at”. Without those spaces the output would read A bag of dog food costs$9at
Wal-Mart.
//You can concatenate string and characters
char initialCharacter=’z’;
String washington = “Cherry tree”;
String franklin = “Ambassador”;
System.out.println(initialCharacter+franklin+franklin+Washington+franklin+initial
Character); //outputs: zAmbassadorAmbassadorCherry treeAmbassadorz
Receiving input from the user through the keyboard:
//You have to prepare the program to receive input. This is done by importing the
scanner into the program before anything else. You then have to declare the name
of your scanner within the program. Your program structure will look like this if
you intend to receive input from a user through the keyboard.
import java.util.Scanner;
public class name
{
public static void main (String [] args)
{
Scanner name=new Scanner(System.in);
Body of your program
}} //close the initial curly brackets.
//note the capitalization of the first line and the line beginning with Scanner. Also
note that the first line ends with a semi-colon. Name can be replaced by whatever
you want to call your scanner throughout the program. Keyboard or scan are
conventional names.
Let’s say you named your scanner “scan”. How do you use it? 1. Prompt the user for
some data (whatever they type goes into the input stream). 2. Pull data from the
input stream using your scanner. Here is a sample program.
import java.util.Scanner;
public class daysOfTheWeek
{
public static void main (String [] args)
{
Scanner name=new Scanner(System.in);
//declare some variables.
int yourFavoriteNumber = 0; //Declare it as zero to begin. This value will be
replaced.
String yourName = “”//variable yourName is declared as whatever is inside the
quotes. It’s empty for now.
Double priceOfLastPurchase = 0;
//1.prompt user for input.
System.out.println(“Please type your favorite number.”);
//2. Scan in the user’s input.
yourFavoriteNumber=scan.nextInt();
//repeat
System.out.println(“Please type your name.”);
yourName=scan.next();
System.out.println(“Please type how much you paid for your last purchase.”);
priceOfLastPurchase=scan.nextDouble();
//display the information
System.out.println(“Your name is “+yourName+” your favorite number is
“+yourFavoriteNumber+” and you spent $“+priceOfLastPurchase+” on your last
purchase.”);
}} //close the initial curly brackets.
//Note that you have to declare that you are scanning the proper data type from the
input stream. If the number 8 is in the data stream, you want to use scan.nextInt().
If it’s a decimal value use scan.nextDouble(); If a string use scan.next(); or
scan.nextLine(); You cannot technically scan in a character ( no such thing as
scan.nextChar();) but you can scan in a string that is only one character long. This is
an important distinction because you won’t be able to use character operations on
the scanned string without changing it to a character.
//note that scan in scan.next…(); is only the name of your scanner. It would be
keyboard.next…(); if you had named your scanner keyboard.
//If “the big black dog” was in the input stream, scan.next(); would only pull the
word “the”. Scan.nextLine(); would pull the whole string “the big black dog.”. Next
goes to the first space. NextLine goes to the enter key.
Strings and Characters:
// a through z and capital A through Z have Unicode values corresponding to them.
I don’t remember them but you can look them up. These values can be used to
compare characters to see which are “larger”. I don’t know much about this but it
may be useful. You can do d>a for example and it would return true. More of a side
note than anything.
The index system: the index begins with zero. Index refers to the position of a
character within a string. Spaces and punctuation occupy index values.
String string1= “The doctor”;
These are the index values for string1
T
h
e
0
1
2
3
d
o
c
t
o
r
4
5
6
7
8
9
You can display the character at an index value:
System.out.println(string1.charAt(index value))
Replace index value with 0 through 9 to print the desired character. Replacing it
with 8 displays o for example.
You can also use the charAt() method to declare a character variable:
char variable1=string1.charAt(4); // variable1 would be the character d.
Determine the length of a string:
int size = String1.length(); //Will return 10 because that’s how many spaces the
string occupies. Note that the length of the string isn’t 9 which is the maximum
index value.
You can determine if a character is uppercase, lower case, a digit, or a space using
the following character methods:
Character.isUpperCase(variable1);
Character.isLowerCase(variable1);
Character.isDigit(variable1);
Character.isWhiteSpace(variable1);
//the return Boolean values. It is either true or false that a character has the given
characteristics.
It is possible to determine if a character in a string at a certain postion has the
desired characteristic using the charAt() method. Note that variable1 above is the
name of a character variable which represents some character.
Character.isWhiteSpace(string1.charAt(9));
It’s also possible to take a part of a string using the substring method.
String string1=”The doctor”;
string1.substring(1,8); // pulls the character from index 1 to index 8 (he doct).
There are libraries of character and string functions. Google them for more methods
of manipulation. These are the main ones I am familiar with.
Math functions:
Basic math operations represented in code:
int total=0;
int count= 3;
total = count+9; //This command sums 9 and count and makes it the new value of
total. Total in now equal to 12 and will be for the rest of the program unless it is
manipulated again.
int sum=0;
sum=sum+3; //adds 3 to the initial value of sum (0) and makes that the new value
of sum.
Shorthand code for this operation is:
Sum+=3;
You can do the same shorthand for subtraction, multiplication, and division.
y-=4; expands to y=y-4
y*=4; expands to y=y*4
y/=4; expands to y=y/4
Be wary of integer division! 4/5 is .8 but .8 as an integer is zero!
int x=4;
int y=5;
x/y; //end result is zero. One way to avoid this is to use a single double value which
will force the result to be a double value.
double x=4;
int y=5;
x/y; // end result is .8
Incrementing: increases a value by 1.
int number=0;
number++; //number is still zero at this point but will have a value of 1 henceforth.
If the variable “number” is used again, it will have a value of 1. This is a postincrement
int number=0;
++number; //immediately increase number by one. Number now equals 1. This is
pre-incrementation.
Decrementing: reducing a value by 1. Follows the same pattern as incrimination.
int number=0;
number--; // variable “number” will from now on be -1. Post-decrement.
int number=0;
--number; // number is immediately -1 and stays -1 for future calculations. Predecrement.
Math.pow(x,y); //x^y. Note that the carrot key does not raise a number to another
number in java. You have to use the Math.pow(x,y); method.
Math.PI;//3.14….
There are libraries of math functions as well. I don’t know many of them.
About Boolean logic:
You can use Boolean logic to compare strings and to compare numbers.
The operators are as follows:
== equals
!= does not equal
|| or
&& and
< <= less than and less than or equal to
> >= greater than and greater than or equal to.
See how these are used in the following programs.
Decision-making:
Decision-making is made up of selection (if/else and switch case) and repetition
(loops).
Objective: receive input from the user. If the number is greater than zero, say it was
a positive number.
System.out.println(“enter a number.”);//prompts user for input.
int input=scan.nextInt();//pulls input number from input stream and assigns it as
the value of an integer variable named input.
If(input>0)
{
System.out.println(“The number you typed is a positive number.”);
}
Objective: receive input from the user. If the number is greater than zero, say it was
a positive number. If less than zero, indicate input was negative.
System.out.println(“enter a number.”);//prompts user for input.
int input=scan.nextInt();//pulls input number from input stream and assigns it as
the value of an integer variable named input.
If(input>0)//if statement. No semi-colon. Surround then statement with {}.
{
System.out.println(“The number you typed is a positive number.”);
}
if(input<0)
{
System.out.println(“The number you typed is a negative number.”);
}
//instead of writing an if statement for the negative numbers, you can simply use
“else” to indicate everything other than the condition input>0 will display the
number input was negative.
System.out.println(“enter a number.”);
int input=scan.nextInt();
the value of an integer variable named input.
If(input>0)
{
System.out.println(“The number you typed is a positive number.”);
}
else
{
System.out.println(“The number you typed is a negative number.”);
}
This is a basic if-else statement. More complicated are nested if-else statements.
Basically selections within selections.
System.out.println(“enter a number.”);
int input=scan.nextInt();
the value of an integer variable named input.
If(input>0)
{
if(input==4)
{
System.out.println(“You typed Jon Gonzalez’s favorite number.”);
}
if(input>=5&&input<=100)
{
System.out.println(“Your number is between 5 and 100”);
}
if(input>1000)
{
System.out.println(“Your number is too large.”);
}
if ((input>0&&input<4))&&(input>100&&input<1000)
{
if(input==1329)
{
Sytstem.out.println(“You picked the magic number.”);
}
else
{
System.out.println(“Your number is positive.”);
}
}
else
{
System.out.println(“The number you typed is a negative number.”);
}
You can make very complicated nested if-else statements although they may not be
very efficient.
The switch case method can sometimes be easier. You define a variable whose
outcomes will vary and based on the outcome the program will execute a certain
command. It looks like this:
import java.util.Scanner;
import java.text.DecimalFormat; //import a decimal format
public class Lab4
{
public static void main(String [] args)
{
Scanner scan=new Scanner(System.in);
DecimalFormat fmt=new DecimalFormat (".00"); // declare and name your
decimal format. This format is named fmt and goes out to two decimals. Note the
capitalization.
int choice=0;//declare the variable that will be the switch with different
outcomes.
double radius=0, squareSideLength=0, triangleBase=0, triangleHeight=0;
//initialize variables that will be used in calculations. Declare them as zero. These
values will be replaced by the values scanned in.
System.out.println("\t\tArea Calculator");
System.out.println("***************************************************************
**********");
System.out.println("\nChoose the shape which you would like to calculate the
area of or exit the program.");
System.out.println("\t1 -- square");
System.out.println("\t2 -- circle");
System.out.println("\t3 -- right triangle");
System.out.println("\t4 -- exit program");
// \t is a tab space. Use it to change how the display looks to the user. Line up
columns with \t. \n goes to the next line as println would. \” prints out quotation
marks. \t, \n, and \” must be typed within quotes otherwise it doesn’t compile.
Needs (“
“) surrounding it.
choice=scan.nextInt(); // variable choice is made to be either 1,2,3,4, or an
incorrect number that the user entered.
switch(choice) // declare that the variable choice is the switch with multiple
outcomes.
{
case 1: // if choice is 1, do the following within the curly brackets.
{
System.out.println("Enter the side length of the square:");
squareSideLength=scan.nextDouble();
double areaSquare= Math.pow(squareSideLength,2); //Math class exponential
System.out.println("The area of the square is "+fmt.format(areaSquare)+" square
units.");// // apply decimal format to a variable.
break; // Ends the switch case method. Makes it so the program does not check
if choice equals 2,3,4, or another number. Increases efficiency by having breaks.
}
case 2: // do the following if choice equals 2.
{
System.out.println("Enter the length of the circle's radius:");
radius=scan.nextDouble();
double areaCircle= Math.PI*(Math.pow(radius,2)); // Math class functions.
System.out.println("The area of the circle is "+fmt.format(areaCircle)+" square
units.");// // apply decimal format to a variable.
break; //stop checking for values for choice. Don’t go through the cases again.
}
case 3: //do this if choice equals 3.
{
System.out.println("Enter the base and height of the right trangle (base
height):");
triangleBase=scan.nextDouble();
triangleHeight=scan.nextDouble();
final double TRIANGLE_CONSTANT= .5;
double areaRightTriangle=
(TRIANGLE_CONSTANT*triangleBase*triangleHeight);
System.out.println("The area of the triangle is
"+fmt.format(areaRightTriangle)+" square units."); // apply decimal format to a
variable.
break;
}
case 4:
{
System.out.println("Program ended.");
System.exit(0); // This is the command to end a program. This is what you asked
before that I couldn’t remember. It doesn’t come up often.
break;
}
default: System.out.println("You have not entered an appropriate integer value to
run the program successfully.\nPlease rerun the program and type either 1,2,3, or
4."); //if user types anything other than 1,2,3, or 4 do this. Makes program user
friendly.
break;
}
}}
Another if-else program:
import java.util.Scanner;
public class RockPaperScissors
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Player 1: Choose rock, scissors, or paper:");
String player1 = scan.next().toLowerCase(); //standardizes inputs so they are
lower case so that you don’t compare Rock and rock and be told they are different.
System.out.println("Player 2: Choose rock, scissors, or paper:");
String player2 = scan.next().toLowerCase();
//tie scenario
if (player1.equals(player2)) // string1.equals(string2) all characters must match
exactly. If they do, the resulting Boolean value is “true” and the program executes
the command that follows this if statement.
System.out.println("TIE!");
//player1 =rock
else if ((player1.startsWith("rock"))&&(player2.startsWith("paper")))
//.startsWith and .equals are interchangeable here. Just another nice thing to learn.
System.out.println("Player 2 wins!");
else if ((player1.startsWith("rock")&&(player2.startsWith("scissors")))) //make
sure the string content is in parentheses.
System.out.println("PLayer 1 wins!");
//player1 =paper
else if ((player1.startsWith("paper"))&&(player2.startsWith("rock")))
//compares two Boolean outcomes, if they are both true, execute the following
statement.
System.out.println("Player 1 wins!");
else if ((player1.startsWith("paper"))&&(player2.startsWith("scissors"))) // you
could probably run the program without the elses and only have if statements
System.out.println("Player 2 wins!");
//player1 =scissors
else if ((player1.startsWith("scissors"))&&(player2.startsWith("paper")))
System.out.println("Player 1 wins!");
else if ((player1.startsWith("scissors"))&&(player2.startsWith("rock")))
System.out.println("Player 2 wins!");
//improper keystroke
else
System.out.println("Your choice was not recognized. Run the program again
using rock, paper, or scissors.");
}}
//Note that you don’t need curly brackets surrounding the contents of an if else
statement as we did here:
if(input=4)
{
System.out.println(“You typed Jon Gonzalez’s favorite number.”);
}
The curly brackets aren’t necessary unless you have more than one command to be
executed but can be used to keep the program organized. They are optional when
there is only one statement. Note also that semi-colons do to follow if, else, or
switch case statements.
Repetition:
Allows you to complete tasks that would normally take many, many steps.
3 types of loops: while loops, for loops, and do-while loops. While is the most
intuitive, for loops are the most compact, and do-while are used infrequently. While
loops continue to do a command while a designated condition is met.
int i=0;
while (i<=5)//do the following while i is less than or equal to 5. Like if-else
statements this statement does not end in a semi-colon. Groups the commands to
be executed in curly brackets.
{
i=i+1; //variable i increases by one.
System.out.println(i+” “); //print the value of i and a space next to it.
}
Initially i is zero and meets the condition of being less than 5. So, the commands are
executed. i is increased by 1 and printed. Now i is one and continues to meet the
conditions of the while loop. The commands are executed again. i becomes to and is
printed next to the previous value of i. This continues until i is not less than 5. The
final output is 1 2 3 4 5.
This kind of loop is counter-controlled. i is a counter because it is manipulated
each time the loop runs and the condition that the loop will run is based upon the
value of the counter.
A different kind of while loop is the sentinel-controlled while loop.
import java.util.Scanner;
iublic class sentinelExample
{
public static void main (String [] args)
{
Scanner scan = new Scanner (System.in);
int sum = 0;
System.out.println(“type an integer. You will be prompted to type more integers.
They will be summed. When you want to stop summing the numbers, type -0”);
int input=scan.nextInt(); //Notice that you can create a variable at the same time
you scan. It isn’t necessary to create it beforehand.
while(input!=-0) //this is the sentinel. The program is watching for an input of -0.
If -0 is the input the while loop will end. Until then, the loop will run so long as the
condition input does not equal -0 is met.
{
sum=sum+input; //alternately sum+=input;
System.out.println(“type another integer. -0 to end the program.”);
input=can.nextInt();
}
System.out.println(“the sum of the inputted values is “+sum);
//This program will continue summing the values you input until you input -0.
Then it will display the sum.
Here is a program that uses loops and selection statements. This program checks to
see if a user-entered string reads the same backwards and forwards.
import java.util.Scanner;
public class palindromeChecker
{
public static void main (String [] args)
{
Scanner scan=new Scanner (System.in);
String input="", reverse=""; //initialize some strings
System.out.println ("Please type your phrase:");
input=scan.nextLine();
int i=input.length()-1; // this generates the index value of the final character of
the input string. If the string is 30 characters long, i=29 and represents the final
character of the string.
while(i>=0) //0 is index value of the string’s first character. There are no
characters below an index value of zero so the loop should stop.
{
reverse+=input.charAt(i); //we begin constructing the string backwards by
declaring “reverse” to be a string starting at the final index value of the input string
and ending with the first character of the index string.
i--; // reduces the index value by one. The loops runs over and over until the first
character from the input string is added to the new string “reverse” which is the
input string backwards.
}
if(input.equalsIgnoreCase(reverse))// if “input” is the same as “reverse” it’s a
palindrome.
System.out.println ("Your phrase is a palindrome.");
else
System.out.println ("Your phrase is not a palindrome.");
}}
This is a counter-controlled loop.
For loops:
For loops are condensed while loops that names all of the parameters of the loop at
once.
int sum=0;
for(int i=0; i<=10; i++) // note where semi-colons are used.
{
sum=sum+i;
}
System.out.println(“The sum is “+sum);
Breaking down the for loop: (int i=0; i<=10; i++)
(int i=0; i<=10; i++) //declares the initial value of the counter.
(int i=0; i<=10; i++) //continues the loop so long as condition is true. Similar to the
while() condition.
(int i=0; i<=10; i++) //command executed at the end of the loop after all other
commands are executed. If it still meets the for condition, the loop runs again.
This program counts the upper case characters, lower case characters, digits, and
words in a string entered by the user. It utilizes a for loop and character methods.
import java.util.Scanner;
public class stringCharacteristics
{
public static void main (String [] args)
{
Scanner scan=new Scanner(System.in);
System.out.println("phrase:");
String phrase = scan.nextLine();
int capitals=0;
int lowers=0;
int digits=0;
int words=1; //begin at 1 because spaces will be counted but that would fail to
count the word before the first space.
for (int i=0; i<phrase.length(); i++) //this condition means only characters at index
values that are actually defined in the string are analyzed. If the string is 10
characters long, only index values 0-9 will be analyzed. Will begin at index value 0
and increase by one each time the loop runs. When i equals 10, the loops won’t run
and the program will proceed to the System.out.println(); statements below.
{
if (Character.isUpperCase(phrase.charAt(i)))
capitals++;// increases the count of capital letters if the above condition is met by
the character at a given index value.
if (Character.isLowerCase(phrase.charAt(i)))
lowers++;
if (Character.isDigit(phrase.charAt(i)))
digits++;
if (phrase.charAt(i) == ' ') //alternately (Character.isWhiteSpace(phrase.charAt(i))
would work here.
words++;
}
System.out.println("Phrase has "+capitals+" upper case letters.");
System.out.println("Phrase has "+lowers+" lower case letters.");
System.out.println("Phrase has "+digits+" digits.");
System.out.println("Phrase has "+words+" words.");
}}
Reading data from files and writing data to files:
This program is similar to the above program but takes the phrases to be analyzed
from a file and prints the results into a new file. Reading and writing data requires
new syntax that we haven’t seen before.
import java.io.File; //needed to read data
import java.io.PrintWriter; //needed to write data
import java.io.FileNotFoundException; // imports the ability to keep the program
from crashing if the input file is not found.
import java.util.Scanner;
public class Assignment3b
{
public static void main (String [] args) throws FileNotFoundException //keeps the
program from crashing if the input file is not found.
{
File infile= new File("hw3input.txt"); //declare input file. hw3input.txt is the
name of the file to be read from. If this file is not in the same directory as this
programs .java file, you will have to list the directory location within the quotations.
Scanner in = new Scanner(infile); //declare scanner for the input file
PrintWriter out= new PrintWriter("hw3output.txt"); //declare output file named
hw3output.txt.
//declare data counters. Similar to the previous program
int capitals=0;
int lowers=0;
int digits=0;
int words=1;
out.println ("\n\t\t *****String Analysis Report*****\n\n"); //creates a header in
the output file. Done for presentation. Note that it’s out.println rather than
System.out.println.
while(in.hasNextLine()) // checks input file to see if there is a line of text. Allows
program to count data for files that have more than 1 line of text. So long as the file
has a line of text, that line's upper case characters, lower case characters, digits and
words will be counted and displayed. When the file has no new lines of data, the
loop will stop.
{
String inputText = in.nextLine(); // determines that the line of text from the
input is the string that will have its data counted.
//resets data counters for each new line of text.
capitals=0;
lowers=0;
digits=0;
words=1;
for (int i=0; i<inputText.length(); i++) // for loop that analyzes the data for each
line of text from the input file as long as there is text in the input file.
{
if (Character.isUpperCase(inputText.charAt(i)))
capitals++;
if (Character.isLowerCase(inputText.charAt(i)))
lowers++;
if (Character.isDigit(inputText.charAt(i)))
digits++;
if (inputText.charAt(i) == ' ')
words++;
}
out.println(inputText+":\n**********************************"); //writes each
string that is analyzed to the outputfile. *’s are used for formatting only.
out.println(capitals+" upper case letters.");
out.println(lowers+" lower case letters.");
out.println(digits+" digits.");
out.println(words+" words.\n");
}
out.println ("\nReference hw3input.txt"); //tells readers where the data came
from.
in.close();
out.close();
//erases hw3input.txt as the location of input files and hw3output.txt as the output
files for future java programs. These are cleared periodically but it is good to do it
manually so that the input files and output files don’t remain as those declared
above for a future program that reads and writes files.
}}
Arrays:
Arrays are data structures that hold many numbers organized by index numbers. An
array could look like this:
10
0
-123
1
10,989
2
0
3
41
4
-43
5
2
6
Arrays can be double arrays or integer arrays. There are several ways to make
arrays.
int [] numbers = new int [7];
//creates an integer array named “numbers” that is 7 index values long.
Another method that is better in the long run is to declare the size of the array as a
constant:
Final int LENGTH = 7;
Int [] numbers = new int [LENGTH]
//This is better in the long run so that you can change the length in the first line and
it will change for every instance that you use the length in the rest of the program.
Instead of having the length a constant, you can declare the length by typing the
length on the keyboard.
int length=scan.nextInt();
double [] numbers = new double [length];
//creates a double array named “numbers” that is whatever length you declare it to
be.
You can declare all of the values of an array as well:
int [] numbers = new int {1,2,353,63,13,53};
The same can be done with Strings:
String [] numbers = new int {1,2,353,63,13,53};
To assign a value to an index space of an array you can use the following. (for an
array named “numbers”.
Numbers[0]=10;
10
0
1
2
3
11
1
12
2
13
3
Numbers[1]=11;
Numbers[2]=12;
Numbers[3]=13;
10
0
This is inefficient is you are dealing with a large array. Use loops to quickly assign
values to arrays.
This program creates an array with 10 index spaces and fills thpose spaces with 10
inputs from the keyboard.
import java.util.Scanner;
public class arrays
{
public static void main (String [] args)
{
Scanner scan = new Scanner (System.in);
final int LENGTH = 10;
int [] arrayName = new int [LENGTH]; // creates a blank integer array of length 10
named arrayName.
System.out.println(“type 10 integers separated by space”);
for(int i=0; i<LENGTH; i++)
{
int input = scan.nextInt();
arrayName[i]=input;
}
now the array is occupied at each index value.
You can print a the value that occupies an index value with the following code:
System.out.println(arrayName[3]); //replace 3 with whatever index value you
want.
You can print, sum, or average the values in the array using loops.
Note that printing the array (System.out.println(arrayName);) gives you the
memory location in your computer of the array. This doesn’t print out the values at
each index location. You would need loops to print the values in the array.
If an index location doesn’t have a value and you try to access it, you will crash the
program. Fill up your array completely if you want to do anything with it.
You can count the amount of positive, negative and zero values in an array using the
following loop:
import java.util.Scanner;
public class arrays
{
public static void main (String [] args)
{
Scanner scan = new Scanner (System.in);
int positive=0, negative=0,zeros=0; // it was not addressed earlier, but you can
declare multiple variables of the same data type using this syntax.
final int LENGTH = 10;
int [] arrayName = new int [LENGTH]; // creates a blank integer array of length 10
named arrayName.
System.out.println(“type 10 integers separated by space”);
for(int i=0; i<LENGTH; i++)
{
int input = scan.nextInt();
arrayName[i]=input;
}
//the above loop assigns values to the array based upon your input. From here, a
new loop counts the positive and negative values in the array.
for( int i=0; i<LENGTH; i++)
{
if(arrayName[i]<0)
{
negative++;
}
if(arrayName[i]>0)
{
positive++;
}
if (arrayName[i]==0)
{
zeros++;
}}
System.out.println( “The array has “+positive+” positive values, “+negative+”
negative values, and “+zeros+” zeros.”);
}}
the command “arrayName.length” gives the length of an array and may be used
within a for loop to give the condition for how many times an operation should
happen.
for(int i=0; i<=arrayName.Length-1;i++)
It may be useful to find the maximum or minimum values in arrays.
This code snippet finds the value of the maximum or minimum value and the
location of that minimum or maximum in an array:
int [] arrayName = new int [20];
int maximumIndex=0;
int maximum= arrayName[0]; //declare the maximum (or minimum) as the first
value in the array.
for(i=1;i<20;i++)//create a for loop that compares every value in the array to the
max value
{
if (arrayName[i]>max); //if the value is greater than the max it becomes the new
max.
{
max=arrayName[i];
maxIndex=i; //when the maximum value is determined, the index location of that
value is found.
}}
It’s also possible to search arrays for a desired value using loops.
for(i=0;i<array.length; i++)
{
if (array[i]=9)
{
System.out.println(“the array contains the value you searched for at index value
“+i);
break;
}}
It’s possible to make an array which you can change the size of by adding or
removing data. This type of array is called an array list.
The code for an array list looks a little different:
ArrayList <String> name = new ArrayList <String>();
name.add(“Cindy”);//adds the string “Cindy” to the last index position that is open.
name.set(i,”Harry”);//replaces the string at index i with string “Harry”
name.add(i, “Jones”);//adds string “Jones” in at index i and moves the strings that
come after index i up one index value.
name.remove(i);//removes string at i.