Array prblem...Need Help..
Assuming the user can only type letters. Thispart of my program is supposed to accept user input and set that user input to the elements in the array.The problem isi can't figure out how to make the array accept user input as it's elements.(I need to use arrays)
[code
import javax.swing.JOptionPane;
import java.awt.*;
import javax.swing.JOptionPane;
public class d6
public static void main (String[] args)
String answer[] = new int [JOptionPane.showInputDialog(null, "User Input")];
for (int i=0;i<answer.length;i++)
System.out.println("The User Input Was:"+answer);
this counts how many words were typed in by the user. (assuming that input consists entirely of letters, whitespace,periods, and commas.)
Problem 1
Example 1
-User Input = I say hi.
-Output= The WordCount is 3 Words.
Example 2
----User Input= I say hi
Output =The WordCount is 2 words
i may need more if statements because the problem is that it only increments WordCount if the user types a space a comma or a period so if the user does none of these things at the end of the input string the wordcount is wrong in the end product.
I'll be in this forum to further clarify my problem if necessary.
import javax.swing.JOptionPane;
import java.awt.*;
public class d6
public static void main (String[] args)
char[] answer = JOptionPane.showInputDialog(null, "User Input").toCharArray();
System.out.println("The User Input Was: ");
for (int i=0;i<answer.length;i++)
System.out.println(answer);
int WordCount=0;
for (int j=0;j<answer.length;j++)
if (answer[j]==(' '))
System.out.print("");
WordCount+=1;
else if
(answer[j]==(','))
System.out.print("");
WordCount+=1;
else if
(answer[j]==('.'))
System.out.print("");
WordCount+=1;
System.out.println("The WordCount is: "+WordCount);
Similar Messages
-
2D array problem, need help
hi,
i have a txt file, with a bunch of lines in it that go like this:
CSF.434.001.LEC
CSF.434.101.TUT
MATH.348.001.LEC
MATH.448.101.TUT
and so on...
For example if there are 4 lines in this text, i want to create a 4x4 matrix and store each data seperately.
i want to extract CSF into matrix[1][1], 434 into matrix[1][2], 001 in matrix[1][3], and finally LEC in matrix[1][4],
and it follows, matrix[2][1] is CSF .....
so basically the period denotes seperation. I have been challenging this problem for 2 hrs now, but no success.
any help in regards to how to extract this file into pieces of data in a matrix would be greatly appeciated....thanks again
how i stated it:
try
BufferedReader inFile = new BufferedReader(new FileReader("schedule.txt"));
for(int t=0; t<size; t++)
String[] extractor = new String[t][4];
for(int i=0; i<4; i++)
extractor[t] = ?????
inFile.readToken();
inFile.close();
catch(IOException ioe)
System.out.println("Error reading from file!");First, create a program that can read the entire file a line at a time.
Here's an example:
http://javaalmanac.com/egs/java.io/ReadLinesFromFile.htmlThen once that's working, add the String.split() method to break a line into pieces at the periods. (It creates a String array with each piece of the string in a separate array element.)
This method is described in the API documentation for the java.lang.String class. -
Stuck with array's NEED HELP!!!
I have been working at this for two hours now and I need a someone else's opinion other than my own. I need to create a method that finds the row index of the row which contains the largest number divisible evenly by 6. and the column index of the column with the smallest sum. all in one method.
This is what I have so far.
public static int sum(int[][]arr, int numRow)
int[][] s;
s = new int[0][10];
int u = 0, largestevenindex = 0, largesteven = -99999, product = 0, sum = 0, i, j;
for(i=0;i<numRow;i++)
for(j=0;j<arr.length;j++)
if(arr[i][j]%6==0 && arr[i][j]>largesteven) //To find the the row index of the largest number divisible by 6.
largesteven = arr[i][j];
largestevenindex = i;
System.out.println(largesteven);
System.out.println(largestevenindex);
for(u=0;u<arr[i].length;u++) //I think I have to create another table and place the sums of the colums and then compare. Is there an easier way?
s[0] = s[0][u]+arr[i][j];
System.out.println(s[0][u]);
return largestevenindex;
This is the test file23 45 10 77 19 13 16
52 34 71 19 88 65 3
12 1 57 16 4 36 17
9 22 31 27 8 25 12
56 77 88 22 33 44 99
6 21 16 89 4 37 48
25 17 8 9 64 72 81
95 26 5 73 18 92 66
99 12 45 72 19 77 43
11 71 26 34 81 7 45
16 2 34 68 67 7 51
19 52 4 56 51 95 12
57 4 7 9 2 1 3
Anyone have any tips for my code, or another way to do this. Thanks.Your right flounder, I forget to add we are suppose to just find the product of the two index(smallest sum cloum index and largest row index divisible by 6)
public static int sum(int[][]arr, int numRow)
int[][] s;
s = new int[0][10];
int u = 0, largestevenindex = 0, largesteven = -99999, product = 0, sum = 0, i, j;
for(i=0;i<numRow;i++)
for(j=0;j<arr.length;j++)
if(arr[i][j]%6==0 && arr[i][j]>largesteven)
largesteven = arr[i][j];
largestevenindex = i;
return largestevenindex;
This gets the row index of the highest number divisible by 6. How do I go about finding the colum index that has the smallest sum. any hints or clues. It has to be apart of this method, though. -
I need help with event structure.
I am trying to feed the index of the array, the index number can vary from 0 to 7.
Based on the logic ouput of a comparison, the index buffer should increment
or decrement every time the output of comparsion changes(event change). I guess I need to use event structure?
(My event code doesn't execute when there is an event at its input /comparator changes its boolean state.
Anyone coded on similar lines? Any ideas appreciated.
Thanks in advance!You don't need an Event Structure, a simple State Machine would be more appropriate.
There are many examples of State Machines within this forum.
RayR -
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? -
Hi, I need help. I have several groups of data for input, and need to use them later in the same or different code. When I key in the input data, the code will ask the number of data group first, then in each group, there will be 6 data to key in, each has a specific variable name. The number of group and the data for each group will vary at each time running the code. The data group needs to be numbered sequently. After having all groups of data, these data will be sent to another sub VI to read. This sub VI needs to know each group number and each data of a group.
I think I should create a 2-D array to read these data in a do loop, but I can't let my do loop read data in each time. Then when I sent the data out, the next sub VI was confused by the sequence of the data group and the sequence of data in each group. Can someone help me or give me some example how to do it? Thank you very much for your help.
Message Edited by ccyang on 06-06-2006 10:37 AMFrom what I understand of your explanation, an event structure might be
the way to go (LV 6+ I think). Events could be based off of
keypresses in a particular control (a 2D array like you mentioned), and
once input in that particular field is complete, the user presses say
the 'enter' key, and you can use the "VKey" of the event data node to
determine which key is pressed (i.e. VKey = enter?). From there,
you would continue to the next portion of data entry or processing of
entered information.
Hope this helps. -
Need Help with simple array program!
Hi, I have just recently started how to use arrays[] in Java and I'm a bit confused and need help designing a program.
What this program does, it reads in a range of letters specified by the user. The user then enters the letters (a, b or c) and stores these characters into an array, which the array's length is equal to the input range the user would enter at the start of the program. The program is then meant to find how many times (a,b and c) appears in the array and the Index it first appears at, then prints these results.
Here is my Code for the program, hopefully this would make sense of what my program is suppose to do.
import B102.*;
class Letters
static int GetSize()
int size = 0;
boolean err = true;
while(err == true)
Screen.out.println("How Many Letters would you like to read in?");
size = Keybd.in.readInt();
err = Keybd.in.fail();
Keybd.in.clearError();
if(size <= 0)
err = true;
Screen.out.println("Invalid Input");
return(size);
static char[] ReadInput(int size)
char input;
char[] letter = new char[size];
for(int start = 1; start <= size; start++)
System.out.println("Please enter a letter (a, b or c) ("+size+" max), enter # to stop:");
input = Keybd.in.readChar();
while((input != 'a') && (input != 'b') && (input != 'c') && (input != '#'))
Screen.out.println("Invalid Input");
System.out.println("Please enter a letter (a, b or c) ("+size+" max, enter # to stop:");
input = Keybd.in.readChar();
while(input == '#')
start == size;
break;
for(int i = 0; i < letter.length; i++)
letter[i] = input;
return(letter);
static int CountA(char[] letter)
int acount = 0;
for(int i = 0; i < letter.length; i++)
if(letter[i] == 'a')
acount++;
return(acount);
static int CountB(char[] letter)
int bcount = 0;
for(int i = 0; i < letter.length; i++)
if(letter[i] == 'b')
bcount++;
return(bcount);
static int CountC(char[] letter)
int ccount = 0;
for(int i = 0; i < letter.length; i++)
if(letter[i] == 'c')
ccount++;
return(ccount);
static int SearchA(char[] letter)
int ia;
for(ia = 0; ia < letter.length; ia++)
if(letter[ia] == 'a')
return(ia);
return(ia);
static int SearchB(char[] letter)
int ib;
for(ib = 0; ib < letter.length; ib++)
if(letter[ib] == 'b')
return(ib);
return(ib);
static int SearchC(char[] letter)
int ic;
for(ic = 0; ic < letter.length; ic++)
if(letter[ic] == 'c')
return(ic);
return(ic);
static void PrintResult(char[] letter, int acount, int bcount, int ccount, int ia, int ib, int ic)
if(ia <= 1)
System.out.println("There are "+acount+" a's found, first appearing at index "+ia);
else
System.out.println("There are no a's found");
if(ib <= 1)
System.out.println("There are "+bcount+" b's found, first appearing at index "+ib);
else
System.out.println("There are no b's found");
if(ic <= 1)
System.out.println("There are "+ccount+" c's found, first appearing at index "+ic);
else
System.out.println("There are no c's found");
return;
public static void main(String args[])
int size;
char[] letter;
int acount;
int bcount;
int ccount;
int ia;
int ib;
int ic;
size = GetSize();
letter = ReadInput(size);
acount = CountA(letter);
bcount = CountB(letter);
ccount = CountC(letter);
ia = SearchA(letter);
ib = SearchB(letter);
ic = SearchC(letter);
PrintResult(letter, acount, bcount, ccount, ia, ib, ic);
return;
} Some errors i get with my program are:
When reading in the letters to store into the array, I get the last letter I entered placed into the entire array. Also I believe my code to find the Index is incorrect.
Example Testing: How many letters would you like to read? 3
Enter letter (a, b or c) (# to quit): a
Enter letter (a, b or c) (# to quit): b
Enter letter (a, b or c) (# to quit): c
It prints "There are no a's'" (there should be 1 a at index 0)
"There are no b's" (there should be 1 b at index 1)
and "There are 3 c's, first appearing at index 0" ( there should be 1 c at index 2)
The last thing is that my code for when the user enters "#" that the input of letters would stop and the program would then continue over to the counting and searching part for the letters, my I believe is correct but I get the same problem as stated above where the program takes the character "#" and stores it into the entire array.
Example Testing:How many letters would you like to read? 3
Enter letter (a, b or c) (# to quit): a
Enter letter (a, b or c) (# to quit): #
It prints "There are no a's'" (should have been 1 a at index 0)
"There are no b's"
and "There are no c's"
Can someone please help me??? or does anyone have a program simular to this they have done and would'nt mind showing me how it works?
Thanks
lou87.Without thinking too much...something like this
for(int start = 0; start < size; start++) {
System.out.println("Please enter a letter (a, b or c) ("+size+" max), enter # to stop:");
input = Keybd.in.readChar();
while((input != 'a') && (input != 'b') && (input != 'c') && (input != '#')) {
Screen.out.println("Invalid Input");
System.out.println("Please enter a letter (a, b or c) ("+size+" max, enter # to stop:");
input = Keybd.in.readChar();
if(input == '#') {
break;
letter[start] = input;
}you dont even need to do start = size; coz with the break you go out of the for loop. -
I need help with this portion of my program, it's supposed to loop through the array and pull out the highest inputted score, currently it's only outputting what is in studentScoreTF[0].
private class HighScoreButtonHandler implements ActionListener
public void actionPerformed(ActionEvent e)
double highScore = 0;
int endScore = 0;
double finalScore = 0;
String tempHigh;
String tempScore;
for(int score = 0; score < studentScoreTF.length; score++)
tempHigh = studentScoreTF[score].getText();
tempScore = studentScoreTF[endScore].getText();
if(tempHigh.length() < tempScore.length())
highScore++;
finalScore = Double.parseDouble(tempScore);
JOptionPane.showMessageDialog(null, "Highest Class Score is: " + finalScore);This is another part of the program, it's supposed to loop through the student names array and pull out the the names of the students with the highest score, again it's only outputting what's in studentName[0].
private class StudentsButtonHandler implements ActionListener
public void actionPerformed(ActionEvent e)
int a = 0;
int b = 0;
int c = 0;
double fini = 0;
String name;
String score;
String finale;
String finalName = new String();
name = studentNameTF[a].getText();
score = studentScoreTF.getText();
finale = studentScoreTF[c].getText();
if(score.length() < finale.length())
fini++;
name = finalName + finale;
JOptionPane.showMessageDialog(null, "Student(s) with the highest score: " + name);
} Any help would be appreciated, this is getting frustrating and I'm starting to get a headache from it, lol.
Edited by: SammyP on Oct 29, 2009 4:18 PM
Edited by: SammyP on Oct 29, 2009 4:19 PMHeres a working example:
class Compare {
public int getHighest(int[] set) {
int high = set[0];
for(int i = 0; i < set.length; i++) {
if(set[i] > high) {
high = set;
return high; -
Need help in text field with 2D array
text field with 2D array
Hi
I need help to represent (i) in from field and (j) in to field
I and j are 2D an array indices.
This code are not complated
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
//declaring class
public class test3 extends Applet implements ActionListener
{ //declaring the TextField
private TextField fromField ,toField;
//declaring an array
int weight[][];
int m = 99; // m is infinity
int N; // Set of Nodes
int d; // distance
int i; // source Node
int j; // destition Node
//declaring values of text field
private int from = i; // start Node
private int to = j; // end node
public void init()
setBackground(Color.white);
setForeground(Color.red);
//giving labels
Label TITLE2,TITLE1;
TITLE1 = new Label("from:");
add(TITLE1);
fromField = new TextField(5);
add(fromField);
// register listener using void add actionListener
fromField.addActionListener(this);
TITLE2 = new Label("to");
add(TITLE2);
toField = new TextField(5);
add(toField);
// register listener using void add actionListener
toField.addActionListener(this);
// event handler methods
public void actionPerformed(ActionEvent event) {
//declaring textfield
from=Integer.parseInt(fromField.getText());
to=Integer.parseInt(toField.getText());
weight =new int[7][7];
weight[1][1] = 0; weight[2][1]= 2;
weight[1][2]= 2; weight[2][2]= 0;
weight[1][3]= 5; weight[2][3]= 3;
weight[1][4]= 1; weight[2][4]= 2;
weight[1][5]= 99; weight[2][5]= 99;
weight[1][6]= 99; weight[2][6]= 99;
weight[3][1]= 5;
weight[3][2]= 3;
weight[3][3]= 0;
weight[3][4]= 3;
weight[3][5]= 1;
weight[3][6]= 5;
for (int i=1; i<7; ++i) {
for (int j=1; j<7; ++j)all your base are belong to us
-
Re: Beginner needs help using a array of class objects, and quick
Dear Cynthiaw,
I just read your Beginner needs help using a array of class objects, and quick of Dec 7, 2006 9:25 PM . I really like your nice example.
I also want to put a question on the forum and display the source code of my classe in a pretty way as you did : with colors, indentation, ... But how ? In html, I assume. How did you generate the html code of your three classes ? By help of your IDE ? NetBeans ? References ?
I already posted my question with six source code classes ... in text mode --> Awful : See "Polymorphism did you say ?"
Is there a way to discard and replace a post (with html source code) in the Sun forum ?
Thanks for your help.
Chavadachavada wrote:
Dear Cynthiaw,
I just read your Beginner needs help using a array of class objects, and quick of Dec 7, 2006 9:25 PM . I really like your nice example.You think she's still around almost a year later?
I also want to put a question on the forum and display the source code of my classe in a pretty way as you did : with colors, indentation, ... But how ?Just use [code] and [/code] around it, or use the CODE button
[code]
public class Foo() {
* This is the bar method
public void bar() {
// do stuff
}[/code] -
I need help on displaying parallel arrays
I have created 3 one dimentional arrays and need to pass that array to a method and within the method the program should be able to accept an input from the user. The input should be matched with an array subscript value. I after, I need to display only the array subscript values of the matching input and the subscript values of 2 more parallel arrays
I need to be able to display only the values of the matching subscripts
like be able to display the subscript [3]which is a match with the input and the subscript [3] from the other 2 arrays.
Can someone please help me?I have created 3 one dimentional arrays and need to
pass that array to a method and within the method the
program should be able to accept an input from the
user. one array, or all arrays? either way do you have problems in passing them into a method? if so are you famililar with parameter passing and java syntax?
The input should be matched with an array
subscript value. traverse the subscript and do this:
for(int i=0; i<=myarray.length; i++)
if (myarray[i] = intergerPassed)
//do whatever
//eg. System.out.println("matched on "+i);
//or System.out.println("other arrays have values at this subscript"+ myarray2[i]+" and "+myarray3);
I after, I need to display only the
array subscript values of the matching input and the
subscript values of 2 more parallel arrays
I need to be able to display only the values of the
matching subscripts
like be able to display the subscript [3]which is a
match with the input and the subscript [3] from the
other 2 arrays.
Can someone please help me? -
Need help pulling data from an outside file into my array. Please help =)
Hi,
I need help adapting my array to read the interest rates from an outside file. Here is my code and the outside file I wrote. Please help. Oh, the array in question is on line 259, inside of my calculation() method.
Thanks...
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.text.NumberFormat;
import java.text.DecimalFormat;
import java.io.*;
import javax.swing.JOptionPane;
public class Workshop5 extends JFrame implements ActionListener
//declare gui components
//declare labels
JPanel contentPane = new JPanel();
JPanel graphPane = new JPanel();
JLabel instructionLabel = new JLabel();
JLabel amountLabel = new JLabel();
JLabel orLabel = new JLabel();
JLabel comboBoxLabel = new JLabel();
JLabel termLabel = new JLabel();
JLabel rateLabel = new JLabel();
JLabel calcLabel = new JLabel();
JLabel paymentLabel = new JLabel();
JLabel tableLabel = new JLabel();
//declare font object
Font labelFont = new Font("Tahoma", Font.PLAIN, 16);
//declare text fields
JTextField amountField = new JTextField(20);
JTextField termField = new JTextField(20);
JTextField rateField = new JTextField(20);
JTextField paymentField= new JTextField(20);
//declare combo box for loan selection
JComboBox comboBox = new JComboBox();
//declare button group and radio buttons
ButtonGroup buttonGroup = new ButtonGroup();
JRadioButton enterRadioButton = new JRadioButton("Enter amount, term, & rate", true);
JRadioButton selectRadioButton = new JRadioButton("Select a preset term/rate loan", false);
//declare button objects
JButton clearButton = new JButton();
JButton calcButton = new JButton();
JButton quitButton = new JButton();
//declare text area for amortization
JTextArea amortTextArea = new JTextArea();
JTextArea testTextArea = new JTextArea();
//declare scroll bar for amortization table
JScrollPane scrollPane = new JScrollPane(amortTextArea,ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
public Workshop5()
instructionLabel.setText("Choose one of the following payment calculation options:");
instructionLabel.setFont(new Font("Tahoma",Font.PLAIN,16));
//adds both buttons to button group
buttonGroup.add(enterRadioButton);
buttonGroup.add(selectRadioButton);
enterRadioButton.setFont(labelFont);
enterRadioButton.setBackground(Color.WHITE);
enterRadioButton.setContentAreaFilled(false);
enterRadioButton.addActionListener(this); //adds action listener to enter radio button
orLabel.setText("OR");
orLabel.setFont(new Font("Tahoma",Font.BOLD,18));
selectRadioButton.setFont(labelFont);
selectRadioButton.setBackground(Color.WHITE);
selectRadioButton.setContentAreaFilled(false);
selectRadioButton.addActionListener(this); //adds action listener to select radio button
amountLabel.setText("Enter mortgage amount");
amountLabel.setFont(new Font("Tahoma", Font.PLAIN,16));
amountField.requestFocusInWindow();
termLabel.setText("Enter term length in years:");
termLabel.setFont(new Font("Tahoma", Font.PLAIN,14));
rateLabel.setText("Enter interest rate:");
rateLabel.setFont(new Font("Tahoma", Font.PLAIN,14));
comboBoxLabel.setText("Select a loan:");
comboBoxLabel.setFont(new Font("Tahoma", Font.PLAIN,14));
comboBox.setBackground(new Color(255,255,255));
comboBox.setFont(new Font("Tahoma", Font.PLAIN, 14));
comboBox.setEnabled(false);
ComboBox();
calcLabel.setText("Press Calculate button to determine monthly payment.");
calcLabel.setFont(new Font("Tahoma", Font.PLAIN, 16));
calcButton.setText("Calculate");
calcButton.setFont(new Font("Tahoma", Font.BOLD, 14));
calcButton.addActionListener(this);
//define monthly payment label
paymentLabel.setText("Monthly payment:");
paymentLabel.setFont(new Font("Tahoma", Font.PLAIN, 16));
//define monthly payment text field
paymentField.setFont(new Font("Tahoma", Font.BOLD,16));
paymentField.setBackground(new Color(255,255,255));
paymentField.setEditable(false);
//define clear button
clearButton.setText("Clear");
clearButton.setFont(new Font("Tahoma", Font.BOLD,14));
clearButton.addActionListener(this);
//define quit button
quitButton.setText("Quit");
quitButton.setFont(new Font("Tahoma", Font.BOLD,14));
quitButton.addActionListener(this);
tableLabel.setText("Amoritization Table");
tableLabel.setFont(new Font("Tahoma", Font.BOLD, 16));
graphPane.setBackground(Color.WHITE);
//add components to content
getContentPane().add(contentPane);
contentPane.setLayout(null);
addComponent(contentPane, instructionLabel, 80,10,450,26);
addComponent(contentPane, enterRadioButton, 30,40,220,30);
addComponent(contentPane, orLabel, 280,40,100,30);
addComponent(contentPane, selectRadioButton, 335,40,350,30);
addComponent(contentPane, amountLabel, 100,80,220,26);
addComponent(contentPane, amountField, 300,80,150,26);
addComponent(contentPane, termLabel, 15,125,200,30);
addComponent(contentPane, termField, 195,125,125,30);
addComponent(contentPane, rateLabel, 62,160,200,30);
addComponent(contentPane, rateField, 195,165,125,30);
addComponent(contentPane, comboBoxLabel, 400,125,200,26);
addComponent(contentPane, comboBox, 400,155,150,30);
addComponent(contentPane, calcLabel, 100,200,400,30);
addComponent(contentPane, calcButton, 250,240,100,30);
addComponent(contentPane, paymentLabel, 150,285,200,30);
addComponent(contentPane, paymentField, 300,285,100,30);
addComponent(contentPane, clearButton, 100,330,100,30);
addComponent(contentPane, quitButton, 400,330,100,30);
addComponent(contentPane, tableLabel, 200,370,300,26);
addComponent(contentPane, scrollPane, 10,400,450,360);
addComponent(contentPane, graphPane, 475,400,305,360);
//add window listener to close window when user presses X
addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
pack();
//method to add components
private void addComponent(Container container, Component c, int x, int y, int width, int height)
c.setBounds(x, y, width, height);
container.add(c);
//action performed method
public void actionPerformed(ActionEvent event)
Object source = event.getSource();
if (source == calcButton)
Calculate();
if (source == clearButton)
Clear();
if (source == quitButton)
Exit();
//defines active area based on user selection of mortgage calculation method
//if user chooses to enter the mortgage manually, combo box fields are inactive
if (source == enterRadioButton)
comboBox.setEnabled(false);
termField.setEnabled(true);
termField.setEditable(true);
rateField.setEnabled(true);
rateField.setEditable(true);
amountField.setText("");
amountField.requestFocusInWindow();
termField.setText("");
rateField.setText("");
paymentField.setText("");
amortTextArea.setText("");
//if user chooses to select from a preset mortgage, rate and term fields are inactive
if (source == selectRadioButton)
comboBox.setEnabled(true);
termField.setEnabled(false);
termField.setEditable(false);
rateField.setEnabled(false);
rateField.setEditable(false);
amountField.setText("");
amountField.requestFocusInWindow();
termField.setText("");
rateField.setText("");
paymentField.setText("");
amortTextArea.setText("");
}//end of action performed method
//combo box method
public void ComboBox()
String[] LoanArray = {" 7 years at 5.35 %", " 15 years at 5.50 %", " 30 years at 5.75 %"};
for (int i = 0; i < LoanArray.length; i++)
comboBox.addItem(LoanArray);
}//end combo box method
//calculation method
void Calculate()
//resets fields
paymentField.setText("");
amortTextArea.setText("");
//calculation variables
NumberFormat currency = NumberFormat.getCurrencyInstance();
int [] termArray = {7, 15, 30}; //array of years
double [] yearlyInterestArray = {5.35, 5.5, 5.75}; //array of interest
int totalMonths = 0; //total months
double Loan = 0.0; //amount of loan
double MonthlyInterest = 0.0; //monthly interest rate
double Payment = 0.0; //calculate payment
double monthlyPayment = 0.0; //calculate monthly payment
double Interest = 0.0; //variable for Interest Array input
int Term = 0; //variable for Term Array input
double NewMonthlyInterest = 0.0; //new interest amount
double NewLoan = 0.0; //new loan amount
double Reduction = 0.0; //principle reduction
//validate input
try
Loan = Double.parseDouble(amountField.getText());
catch (NumberFormatException e)
JOptionPane.showMessageDialog(null,"Invalid Entry. Please enter valid loan amount.", "Error", JOptionPane.WARNING_MESSAGE);
//resets input fields after error message
amountField.setText("");
amountField.requestFocusInWindow();
//if select button is chosen
if (selectRadioButton.isSelected())
int index = comboBox.getSelectedIndex();
Term = termArray[index];
Interest = yearlyInterestArray[index];
//if user chooses to enter mortgage information
else
if (enterRadioButton.isSelected())
//validates input
try
Term = Integer.parseInt(termField.getText());
catch (NumberFormatException e)
JOptionPane.showMessageDialog(null,"Invalid entry. Please enter valid term length in years.", "Error",JOptionPane.WARNING_MESSAGE);
//clears fields after error message
termField.setText("");
termField.requestFocusInWindow();
try
Interest = Double.parseDouble(rateField.getText());
catch (NumberFormatException e)
JOptionPane.showMessageDialog(null,"Invalid entry. Please enter valid rate (without percent symbol).","Error",JOptionPane.WARNING_MESSAGE);
//clears fields after error message
rateField.setText("");
rateField.requestFocusInWindow();
//perform calculations
if (Loan > 0)
Loan = Double.parseDouble(amountField.getText());
MonthlyInterest = (Interest / 12)/100;
totalMonths = Term * 12;
monthlyPayment = Loan * MonthlyInterest *(Math.pow((1 + MonthlyInterest), totalMonths)/(Math.pow((1 + MonthlyInterest), totalMonths)-1));
paymentField.setText("" + currency.format(monthlyPayment));
//send information to amortization text area
amortTextArea.append("Number\t");
amortTextArea.append(" Amount\t");
amortTextArea.append("Interest\t");
amortTextArea.append("Principle\t");
amortTextArea.append("Balance\n");
NewLoan = Loan;
for (int i = 1; i <= totalMonths; i++)
NewMonthlyInterest = MonthlyInterest * NewLoan;
Reduction = monthlyPayment - NewMonthlyInterest;
NewLoan = NewLoan - Reduction;
amortTextArea.append(" " + i +"\t");
amortTextArea.append(" " + currency.format(monthlyPayment) + "\t");
amortTextArea.append(" " + currency.format(NewMonthlyInterest)+ "\t");
amortTextArea.append(" " + currency.format(Reduction) + "\t");
amortTextArea.append(" " + currency.format(NewLoan) + "\n");
//resets fields if loan amount is less than zero
if((Loan <= 0 || Term <= 0 || Interest <= 0))
paymentField.setText("");
amortTextArea.setText("");
}//end calcualtion method
//clear method
void Clear()
amountField.setText("");
amountField.requestFocusInWindow();
termField.setText("");
rateField.setText("");
paymentField.setText("");
amortTextArea.setText("");
}//end of clear method
//main method
public static void main(String args[])
Workshop5 f = new Workshop5();
f.setTitle("Carol's Mortgage Calculator");
f.setBounds(200,100,800,800);
f.setResizable(false);
f.setVisible(true);
}//end of main method
//exit method
void Exit()
System.exit(0);
}//end of exit method
}//program end
My data file is called: "InterestData.dat" and only contains the following text:
5.35, 5.5, 5.75Ok, now I am getting this error message:
cannot resolve symbol method lenght()
Please help me out here, this is due tomorrow and I've been killing myself on it...
attaching program with revised code included, see beginning of calculation method line 250:
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.* ;
import java.text.NumberFormat;
import java.text.DecimalFormat;
import java.io.*;
import javax.swing.JOptionPane;
public class Workshop5 extends JFrame implements ActionListener
//declare gui components
//declare labels
JPanel contentPane = new JPanel();
JPanel graphPane = new JPanel();
JLabel instructionLabel = new JLabel();
JLabel amountLabel = new JLabel();
JLabel orLabel = new JLabel();
JLabel comboBoxLabel = new JLabel();
JLabel termLabel = new JLabel();
JLabel rateLabel = new JLabel();
JLabel calcLabel = new JLabel();
JLabel paymentLabel = new JLabel();
JLabel tableLabel = new JLabel();
//declare font object
Font labelFont = new Font("Tahoma", Font.PLAIN, 16);
//declare text fields
JTextField amountField = new JTextField(20);
JTextField termField = new JTextField(20);
JTextField rateField = new JTextField(20);
JTextField paymentField= new JTextField(20);
//declare combo box for loan selection
JComboBox comboBox = new JComboBox();
//declare button group and radio buttons
ButtonGroup buttonGroup = new ButtonGroup();
JRadioButton enterRadioButton = new JRadioButton("Enter amount, term, & rate", true);
JRadioButton selectRadioButton = new JRadioButton("Select a preset term/rate loan", false);
//declare button objects
JButton clearButton = new JButton();
JButton calcButton = new JButton();
JButton quitButton = new JButton();
//declare text area for amortization
JTextArea amortTextArea = new JTextArea();
JTextArea testTextArea = new JTextArea();
//declare scroll bar for amortization table
JScrollPane scrollPane = new JScrollPane(amortTextArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
public Workshop5()
instructionLabel.setText("Choose one of the following payment calculation options:");
instructionLabel.setFont(new Font("Tahoma",Font.PLAIN,16));
//adds both buttons to button group
buttonGroup.add(enterRadioButton);
buttonGroup.add (selectRadioButton);
enterRadioButton.setFont(labelFont);
enterRadioButton.setBackground(Color.WHITE);
enterRadioButton.setContentAreaFilled(false);
enterRadioButton.addActionListener(this); //adds action listener to enter radio button
orLabel.setText("OR");
orLabel.setFont(new Font("Tahoma",Font.BOLD,18));
selectRadioButton.setFont(labelFont);
selectRadioButton.setBackground(Color.WHITE);
selectRadioButton.setContentAreaFilled(false);
selectRadioButton.addActionListener (this); //adds action listener to select radio button
amountLabel.setText("Enter mortgage amount");
amountLabel.setFont(new Font("Tahoma", Font.PLAIN,16));
amountField.requestFocusInWindow();
termLabel.setText("Enter term length in years:");
termLabel.setFont(new Font("Tahoma", Font.PLAIN,14));
rateLabel.setText("Enter interest rate:");
rateLabel.setFont(new Font("Tahoma", Font.PLAIN,14));
comboBoxLabel.setText("Select a loan:");
comboBoxLabel.setFont(new Font("Tahoma", Font.PLAIN,14));
comboBox.setBackground(new Color(255,255,255));
comboBox.setFont(new Font("Tahoma", Font.PLAIN, 14));
comboBox.setEnabled(false);
ComboBox();
calcLabel.setText("Press Calculate button to determine monthly payment.");
calcLabel.setFont(new Font("Tahoma", Font.PLAIN, 16));
calcButton.setText("Calculate");
calcButton.setFont(new Font("Tahoma", Font.BOLD, 14));
calcButton.setBackground(new Color(202,255,112));
calcButton.addActionListener(this);
//define monthly payment label
paymentLabel.setText("Monthly payment:");
paymentLabel.setFont(new Font("Tahoma", Font.PLAIN, 16));
//define monthly payment text field
paymentField.setFont (new Font("Tahoma", Font.BOLD,16));
paymentField.setBackground(new Color(255,255,255));
paymentField.setEditable(false);
//define clear button
clearButton.setText("Clear");
clearButton.setFont(new Font("Tahoma", Font.BOLD,14));
clearButton.setBackground(new Color(202,255,112));
clearButton.addActionListener(this);
//define quit button
quitButton.setText("Quit");
quitButton.setFont(new Font("Tahoma", Font.BOLD,14));
quitButton.setBackground(new Color(202,255,112));
quitButton.addActionListener(this);
//define label for amortization table
tableLabel.setText ("Amoritization Table");
tableLabel.setFont(new Font("Tahoma", Font.BOLD, 16));
graphPane.setBackground(Color.WHITE);
//add components to content
getContentPane().add(contentPane);
contentPane.setLayout(null);
addComponent(contentPane, instructionLabel, 80,10,450,26);
addComponent(contentPane, enterRadioButton, 30,40,220,30);
addComponent(contentPane, orLabel, 280,40,100,30);
addComponent(contentPane, selectRadioButton, 335,40,350,30);
addComponent(contentPane, amountLabel, 100,80,220,26);
addComponent(contentPane, amountField, 300,80,150,26);
addComponent(contentPane, termLabel, 15,125,200,30);
addComponent(contentPane, termField, 195,125,125,30);
addComponent(contentPane, rateLabel, 62,160,200,30);
addComponent(contentPane, rateField, 195,165,125,30);
addComponent(contentPane, comboBoxLabel, 400,125,200,26);
addComponent(contentPane, comboBox, 400,155,150,30);
addComponent(contentPane, calcLabel, 100,200,400,30);
addComponent(contentPane, calcButton, 250,240,100,30);
addComponent(contentPane, paymentLabel, 150,285,200,30);
addComponent(contentPane, paymentField, 300,285,100,30);
addComponent(contentPane, clearButton, 100,330,100,30);
addComponent(contentPane, quitButton, 400,330,100,30);
addComponent(contentPane, tableLabel, 200,370,300,26);
addComponent(contentPane, scrollPane, 10,400,450,360);
addComponent(contentPane, graphPane, 475,400,305,360);
//add window listener to close window when user presses X
addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
pack();
//method to add components
private void addComponent(Container container, Component c, int x, int y, int width, int height)
c.setBounds(x, y, width, height);
container.add(c);
//action performed method
public void actionPerformed(ActionEvent event)
Object source = event.getSource();
if (source == calcButton)
Calculate();
if (source == clearButton)
Clear();
if (source == quitButton)
Exit();
//defines active area based on user selection of mortgage calculation method
//if user chooses to enter the mortgage manually, combo box fields are inactive
if (source == enterRadioButton)
comboBox.setEnabled(false);
termField.setEnabled(true);
termField.setEditable(true);
rateField.setEnabled(true);
rateField.setEditable(true);
amountField.setText ("");
amountField.requestFocusInWindow();
termField.setText("");
rateField.setText("");
paymentField.setText ("");
amortTextArea.setText("");
//if user chooses to select from a preset mortgage, rate and term fields are inactive
if (source == selectRadioButton)
comboBox.setEnabled(true);
termField.setEnabled(false);
termField.setEditable(false);
rateField.setEnabled (false);
rateField.setEditable(false);
amountField.setText("");
amountField.requestFocusInWindow();
termField.setText ("");
rateField.setText("");
paymentField.setText("");
amortTextArea.setText("");
}//end of action performed method
//combo box method
public void ComboBox()
String[] LoanArray = {" 7 years at 5.35 %", " 15 years at 5.50 %", " 30 years at 5.75 %"};
for (int i = 0; i < LoanArray.length; i++)
comboBox.addItem(LoanArray);
}//end combo box method
//calculation method
void Calculate()
//resets fields
paymentField.setText("");
amortTextArea.setText("");
//calculation variables
NumberFormat currency = NumberFormat.getCurrencyInstance();
//declare input stream object
InputStream istream;
//create a file object to refer to the outside file
File interestData = new File("InterestFile.dat");
//assign instream to the new file object
istream = new FileInputStream(interestData);
try
StringBuffer sb = new StringBuffer();
BufferedReader in = new BufferedReader(new FileReader(interestData));
String line = "";
while((line = in.readLine()) != null)
sb.append(line);
in.close();
String fileData = sb.toString();
String[] splitData = fileData.split(", ");
double [] yearlyInterestArray = new double[splitData.length()];
for(int j = 0; j < splitData.length(); j++)
yearlyInterestArray[j] = new Double(splitData[j]).doubleValue();
catch (IOException e)
JOptionPane.showMessageDialog(null, "File does not exist." + e.getMessage());
int [] termArray = {7, 15, 30}; //array of years
double [] yearlyInterestArray = { 5.35, 5.5, 5.75}; //array of interest
int totalMonths = 0; //total months
double Loan = 0.0; //amount of loan
double MonthlyInterest = 0.0; //monthly interest rate
double Payment = 0.0; //calculate payment
double monthlyPayment = 0.0; //calculate monthly payment
double Interest = 0.0; //variable for Interest Array input
int Term = 0; //variable for Term Array input
double NewMonthlyInterest = 0.0; //new interest amount
double NewLoan = 0.0; //new loan amount
double Reduction = 0.0; //principle reduction
//validate input
try
Loan = Double.parseDouble(amountField.getText());
catch (NumberFormatException e)
JOptionPane.showMessageDialog(null,"Invalid Entry. Please enter valid loan amount.", "Error", JOptionPane.WARNING_MESSAGE);
//resets input fields after error message
amountField.setText("");
amountField.requestFocusInWindow ();
//if select button is chosen
if (selectRadioButton.isSelected())
int index = comboBox.getSelectedIndex ();
Term = termArray[index];
Interest = yearlyInterestArray[index];
//if user chooses to enter mortgage information
else
if (enterRadioButton.isSelected())
//validates input
try
Term = Integer.parseInt(termField.getText());
catch (NumberFormatException e)
JOptionPane.showMessageDialog(null,"Invalid entry. Please enter valid term length in years.", "Error",JOptionPane.WARNING_MESSAGE);
//clears fields after error message
termField.setText("");
termField.requestFocusInWindow();
try
Interest = Double.parseDouble(rateField.getText());
catch (NumberFormatException e)
JOptionPane.showMessageDialog(null,"Invalid entry. Please enter valid rate (without percent symbol).","Error",JOptionPane.WARNING_MESSAGE);
//clears fields after error message
rateField.setText("");
rateField.requestFocusInWindow();
//perform calculations
if (Loan > 0)
Loan = Double.parseDouble(amountField.getText ());
MonthlyInterest = (Interest / 12)/100;
totalMonths = Term * 12;
monthlyPayment = Loan * MonthlyInterest *(Math.pow ((1 + MonthlyInterest), totalMonths)/(Math.pow((1 + MonthlyInterest), totalMonths)-1));
paymentField.setText("" + currency.format(monthlyPayment));
//send information to amortization text area
amortTextArea.append("Number\t");
amortTextArea.append(" Amount\t");
amortTextArea.append("Interest\t");
amortTextArea.append("Principle\t");
amortTextArea.append("Balance\n");
NewLoan = Loan;
for (int i = 1; i <= totalMonths; i++)
NewMonthlyInterest = MonthlyInterest * NewLoan;
Reduction = monthlyPayment - NewMonthlyInterest;
NewLoan = NewLoan - Reduction;
amortTextArea.append(" " + i +"\t");
amortTextArea.append (" " + currency.format(monthlyPayment) + "\t");
amortTextArea.append(" " + currency.format(NewMonthlyInterest)+ "\t");
amortTextArea.append(" " + currency.format(Reduction) + "\t");
amortTextArea.append(" " + currency.format(NewLoan) + "\n");
//resets fields if loan amount is less than zero
if((Loan <= 0 || Term <= 0 || Interest <= 0))
paymentField.setText("");
amortTextArea.setText("");
}//end calcualtion method
//clear method
void Clear()
amountField.setText("");
amountField.requestFocusInWindow();
termField.setText("");
rateField.setText("");
paymentField.setText("");
amortTextArea.setText("");
}//end of clear method
//main method
public static void main(String args[])
Workshop5 f = new Workshop5();
f.setTitle("Carol's Mortgage Calculator");
f.setBounds(200,100,800,800);
f.setResizable(false);
f.setVisible(true);
}//end of main method
//exit method
void Exit()
System.exit(0);
}//end of exit method
}//program end -
Hi everybody
Need help in merging array of strong edges (coordinates).
Already using array in 'if else' but have problem in merging those sequence values into two arrays of x and y coordinates (it will take all coordinates in image).
Any ideas?
Thanks.
mySiti
for (int i = 0; i < width; i++) { //for width
for (int j = 0; j < height; j++) { //for height
Color c = pic.get(i, j);
int r = c.getRed();
int g = c.getGreen();
int b = c.getBlue();
int finalEdgeR=0, finalEdgeG=0, finalEdgeB=0;
int notEdgeR, notEdgeG, notEdgeB;
int [] StrongEdgeCoordX = new int ;
int [] StrongEdgeCoordY = new int [j];
if(r>=50 && r<=255)
finalEdgeR=r;
System.out.println("--------------------------------");
System.out.println("coordinate of this pixel '"+i+"'");
System.out.println("coordinate of this pixel '"+j+"'");
System.out.println("StrongEdgeCoordX '"+i+"'");
System.out.println("StrongEdgeCoordY '"+j+"'");
System.out.println("edge red '"+finalEdgeR+"'");
else if (r>=0 && r<50) notEdgeR=0;
if(g>=50 && g<=255)
finalEdgeG=g;
System.out.println("edge green '"+finalEdgeG+"'");
else if (g>=0 && g<50) notEdgeG=0;
if(b>=50 && b<=255)
finalEdgeB=b;
System.out.println("edge blue '"+finalEdgeB+"'");
else if (b>=0 && b<50) notEdgeB=0;hi, i have here a codes but i dont know on how to print the value that stored in array C;
heres the sample code;
// your array a and b
int[] a, b;
// you fill them
a = ...;
b = ...;
// now you merge them
int cSize = a.length + b.length;
int[] c = new int[cSize];
// pos of the c array
int count = 0;
int i = 0;
for(i = 0; i < a.length; i++){
c[count++] = a;
for(i = 0; i < b.length; i++){
c[count++] = b[i]; -
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 -
Hey guys, I'm a beginner programmer and I'm having a bit of a tough time with arrays. I could really use some help!
What I'm trying to do is roll one die and then record the rolls.
Here is my sample I/O:
How many times should I roll a die?
-> 8
rolling 8 times
2, 1, 5, 6, 2, 3, 6, 5
number of 1's: 1
number of 2's: 2
and so on....
Here is my incomplete code at this moment:
//CountDieFaces.java
import java.util.Scanner;
import java.io.*;
import library.Gamble;
public class CountDieFaces
//prompt for and read in: number of times user wants to roll one die
//simulate rolling a die that many times, counting how many times each face 1 thru 6 comes up
//print out: each roll
//AND the total number of times each face occured and the percentage of the time each face occured.
Scanner scan = new Scanner(System.in);
int[] faceCount= {0,0,0,0,0,0,0};
int dice;
System.out.println("How many times would you like to roll the die?");
int dieCount = scan.nextInt();
int dieRoll = Gamble.rollDie(); // Main calling class method
int count = 1;
while(count < dieCount)
System.out.println(faceCount[count]);
count++;
}Here is the gamble library:
//Gamble.java
package library;
public class Gamble
// returns 1, 2, 3, 4, 5, or 6
public static int rollDie()
int dieRoll = (int)(Math.random()*6)+1;
return dieRoll;
}and here are the errors I have so far:
----jGRASP exec: javac -g CountDieFaces.java
CountDieFaces.java:19: <identifier> expected
System.out.println("How many times would you like to roll the die?");
^
CountDieFaces.java:19: illegal start of type
System.out.println("How many times would you like to roll the die?");
^
CountDieFaces.java:25: illegal start of type
while(count < dieCount)
^
CountDieFaces.java:25: > expected
while(count < dieCount)
^
CountDieFaces.java:25: ')' expected
while(count < dieCount)
^
CountDieFaces.java:26: ';' expected
^
CountDieFaces.java:27: illegal start of type
System.out.println(faceCount[count]);
^
CountDieFaces.java:27: ';' expected
System.out.println(faceCount[count]);
^
CountDieFaces.java:27: invalid method declaration; return type required
System.out.println(faceCount[count]);
^
CountDieFaces.java:27: ']' expected
System.out.println(faceCount[count]);
^
CountDieFaces.java:27: ')' expected
System.out.println(faceCount[count]);
I'm really confused with how a the gamble library gets put into the array, so any help is appreciated! Also if anyone could explain the errors to me, I would really appreciate it.
thanks in advance,
wootens
Edited by: Wootens on Oct 18, 2010 8:55 PMD'oh!
Thanks you guys, fixed that. Although I'm having trouble with storing the die roll in the array. Any suggestions?
java.io.*;
public class CountDieFaces
//prompt for and read in: number of times user wants to roll one die
//simulate rolling a die that many times, counting how many times each face 1 thru 6 comes up
//print out: each roll
//AND the total number of times each face occured and the percentage of the time each face occured.
public static void main(String[] args)
Scanner scan = new Scanner(System.in);
int[] faceCount= {0,0,0,0,0,0};
int dice;
System.out.println("How many times would you like to roll the die?");
int dieCount = scan.nextInt();
int dieRoll = rollDie(); // Main calling class method
int count = 0;
while(count < dieCount)
System.out.println(faceCount[dieRoll]);
count++;
public static int rollDie()
int dieRoll = (int)(Math.random()*6)+1;
return dieRoll;
}Wootens -
Newbie needs help with Flex app
Hi there. I am very new to Flex and also fairly new to
programming although I do have a little experience.
I am trying to create an app which stores code snippets or
common text I tend to use every day in my documents and emails.
So basically I need help on a design level. I can refer to
the developer's manual for exact instructions for commands, but I
need to know what to code first.
The app will consist of:
-a tree directory structure where I can create groups.
-There will be a basic text editor where I input all my data,
basic text formatting options (font, bullets etc) would be a bonus.
-A search function
-Finally it will ideally allow multiple client apps write to
a central database file over a network
Can anyone suggest how I should approach such a project?
Or are there any tutorials / source files which demonstrate
each bullet point?
thanks.Hey jono,
I'm new too. But I think I might know the right components.
If you google any of these + flex 3 you should get some
decent documentation
tree - advanced dataGrid component
basic text editor - rich text editor component
search function - well, you're gonna need to read up on
arrays, and arraycollection. Once you get that stuff working, you
can write up a function to search for a string in an array.
network functionality - HTTPService, you can dump the
datagrid into a database, and have it load the database when you
open up the application.
Give these things a shot, tutorials / sources will come with
the google searches.
Maybe you are looking for
-
My Ipod Touch won't let me download apps or log in
I just got it and it won't let me download apps. I even made another ID. It keeps saying "Password or Apple ID is incorrect" or it will say "cannot connect to ITunes" and if it doesn't say either one of these it says "An Unknown Error occured" I rest
-
Is there any way to open an iMovie HD file with iMovie 4?
Subject said it all. My daughter did her iMovie homework on our home computer. When she took the iMovie HD file to school it wouldn't open with their older version of iMovie. Any suggestions? Thanks, lw
-
At the same time I stopped getting any thumbnails in Iphoto, when I open a picture in Photoshop, the image quality is now very poor. I get a 3X5 photo at 72 dpi, when it used to be 22X17 at 72 dpi. File size is now point 1 MB, when it used to 3.5 MB.
-
Trying to setup RAID with 2 80GB Western D and K7N2 Mainboard.
Thank you for looking at my problem in advance. Here is my problem. When I go to the fastTrak setup it only shows 1 hard drive. I have both Wetern Digital 80gb hard drives connected to one IDE cable going to the ID3 connector on the MB. These drives
-
Bug in editing percentages of template?
I opened the Grade Book template in Numbers and am trying to enter in percentages over the dummy text ones. If I type in "50" for a percentage, I get 5000%. If I type in "5", I get 500%. Is this a bug, or am I doing something wrong?