Newbie Seeking Help With Array Output!
Hey all, I'm new here, so here goes nothing! :) I'm in my first programming class at college, and we need to output multiple arrays. We're using JTextAreas and I'm not sure how I should go about this, but this is what I have so far:
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Application1
public Application1()
String name[]={"Mary","John","William","Debbie","Ralph"};
int temp[]={34,24,78,65,45,100,90,97,56,89,78,98,74,90,98,24,45,76,89,54,12,20,22,55,6};
int [][]scores=new int[8][8];
float []avg=new float[5];
char []lettergrade={'F','F','F','F','F'}; //Initialized at "F" and replaced by their actual grade
String out="";
move_score(temp,scores);
tot_hi_low(scores);
average(scores,avg,lettergrade); //Calculates Average and Letter Grade
graph(scores,avg);
JTextArea outarea=new JTextArea(8,8); //Output
out+="Name\t"+"Test1\t"+"Test2\t"+"Test3\t"+"Test4\t"+"Final\t"+"Total\t"+"High\t"+"Low\t"+scores;
outarea.setText(out);
JOptionPane.showMessageDialog(null,outarea);
public void move_score(int temporary[],int sc[][])
int c=0;
for(int a=0;a<=4;a++) //Moves values of "temp" into 2D array "scores"
for(int b=0;b<=4;b++)
sc[a]=temporary[c];
c++;
public void tot_hi_low(int [][]score)
int d=100; //Low Variable
int e=-1; //High Variable
for(int r=0;r<=4;r++)
for(int c=0;c<=4;c++)
score[r][5]+=score[r][c]; //Total for Columns
score[5][r]+=score[c][r]; //Total for Rows
if(score[r][c]>e) //High for Columns
e=score[r][c];
score[r][6]=e;
if(score[c][r]>e) //High for Rows
e=score[c][r];
score[6][r]=e;
if(score[r][c]<d) //Low for Columns
d=score[r][c];
score[r][7]=d;
if(score[c][r]<d) //Low for Rows
d=score[c][r];
score[7][r]=d;
public void average(int [][]score,float []avg,char []grade){
int l=800;
for(int a=0;a<=4;a++)
for(int b=0;b<=3;b++)
if(score[a][b]<l)
l=score[a][b];
avg[a]=(score[a][5]-l+score[a][4])/5.0f;
if(avg[a]>=60) //Assigns Letter Grades
grade[a]='D';
if(avg[a]>=70)
grade[a]='C';
if(avg[a]>=80)
grade[a]='B';
if(avg[a]>=90)
grade[a]='A';
public void graph(int [][]score,float []average){
//DECLARE EVERYTHING HERE
//DECLARE ARRAYS
public static void main(String args[]){
Application1 app=new Application1();
System.exit(0);
Ah sorry about that; like I said I'm fresh off the 'coding' boat. What I meant to ask in my original post is: "Could someone show me an example of how I could get arrays into output?" I am definately not looking for someone to do my work for me, but I am at a dead end, and would appreciate any examples or even tips! Here is what I have:
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Application1
public Application1()
String name[]={"Mary","John","William","Debbie","Ralph"};
int temp[]={34,24,78,65,45,100,90,97,56,89,78,98,74,90,98,24,45,76,89,54,12,20,22,55,6};
int [][]scores=new int[8][8];
float []avg=new float[5];
char []lettergrade={'F','F','F','F','F'}; //Initialized at "F" and replaced by their actual grade
String out="";
move_score(temp,scores);
tot_hi_low(scores);
average(scores,avg,lettergrade); //Calculates Average and Letter Grade
graph(scores,avg);
JTextArea outarea=new JTextArea(8,8); //Output
out+="Name\t"+"Test1\t"+"Test2\t"+"Test3\t"+"Test4\t"+"Final\t"+"Total\t"+"High\t"+"Low\n"+scores;
outarea.setText(out);
JOptionPane.showMessageDialog(null,outarea);
public void move_score(int temporary[],int sc[][])
int c=0;
for(int a=0;a<=4;a++) //Moves values of "temp" into 2D array "scores"
for(int b=0;b<=4;b++)
sc[a]=temporary[c];
c++;
public void tot_hi_low(int [][]score)
int d=100; //Low Variable
int e=-1; //High Variable
for(int r=0;r<=4;r++)
for(int c=0;c<=4;c++)
score[r][5]+=score[r][c]; //Total for Columns
score[5][r]+=score[c][r]; //Total for Rows
if(score[r][c]>e) //High for Columns
e=score[r][c];
score[r][6]=e;
if(score[c][r]>e) //High for Rows
e=score[c][r];
score[6][r]=e;
if(score[r][c]<d) //Low for Columns
d=score[r][c];
score[r][7]=d;
if(score[c][r]><d) //Low for Rows
d=score[c][r];
score[7][r]=d;
public void average(int [][]score,float []avg,char []grade){
int l=800;
for(int a=0;a<=4;a++)
for(int b=0;b<=3;b++)
if(score[a]><l)
l=score[a];
avg[a]=(score[a][5]-l+score[a][4])/5.0f;
if(avg[a]>=60) //Assigns Letter Grades
grade[a]='D';
if(avg[a]>=70)
grade[a]='C';
if(avg[a]>=80)
grade[a]='B';
if(avg[a]>=90)
grade[a]='A';
public void graph(int [][]score,float []average){
public static void main(String args[]){
Application1 app=new Application1();
System.exit(0);
}I want to get my scores array into my JTextArea, but the array isn't displaying as I intended it to. Any help would be incredibly useful!
Similar Messages
-
Help with DIgital Output Array with 6062E DAQ CARD...
Good morning, folks... I need some help with digital output of the 6062E PCMCIA card... I can output 1 line without problems... I need to control a 4066 with my digital outputs... I am doing this without greater problems... but there's something... I need that when one of my outputs is high, the others become low, unchangeably... so I tried to use an array to control my output and I couldn't do that... some errors showed up... can you help me please? Maybe there's any errors at my software, then I thank you if you help me... the vi is anexed...
Best Regards...
Attachments:
Untitled 3.vi 20 KBSee below for one of many methods. Change the "lines" string for your setup.
Also, please explore the Examples that ship with LabVIEW, and read your card's manual.
Richard -
hi,
i need some help with this piece of code. wat would it output to the screen?
int [] theArray = { 1,2,3,4,5};
for (int i = 1; i < 5; i++)
System.out.print(theArray * i + "; ");
would it output 1 * 1;
2 * 2;...
thanx
devinOk...
1] Your index into the array is off by 1 - remember that array indexing starts from 0.
2] You cannot multiply an array object. The contents? fine , go ahead but NOT the array
so your output should be something like:
operator * cannot be applied to int[] :d
try
int[] theArray = {0,1,2,3,4,5};
for(int i = 1;i<6;i++)
System.out.print(theArray*i+";");
giving you an output of 1;4;9;16;n...
if you were looking for the output stated change
System.out.print(theArray*i+";");
to
System.out.print(theArray[i]+"*"+i+";");done... -
I really need some help with the following two methods:
- A method fillArray() that accepts an integer array as a parameter and fills the array with random integers. I am encouraged to use Math.random()
- A method printArray() that accepts an integer array as a parameter and outputs every element of the array to the standard output device. I am encouraged to use print instead of println in order to save paper.
Thanks so much for your help.public class Test {
public static void main (String[] args){
int[] intArray = new int[20];
fillArray(intArray);
printArray(intArray);
public static void fillArray (int[] intArray){
for (int i = 0; i < intArray.length; i++) {
intArray[i] = (int) (Math.random()*1000);
public static void printArray (int[] intArray){
for (int i = 0; i < intArray.length; i++) {
int i1 = intArray;
System.out.print(i1+",");
System.out.println(""); -
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 -
Seeking Help with Album Image Issues in iPod Classic
Hi folks -
I have a new 160 iPod Classic and have two album image-related issues I'd appreciate some help with.
In the case of several albums where I'd associated my own art with them in iTunes, the formatting appeared off in my iPod due to the vertical/horizontal proportions. So I corrected the images, replaced the images via iTunes, and re-synced. All of the old images were replaced - except for two. Is there any way to get my iPod to recognize the change to these two images, as it did for all the others?
Secondly, my "The Allman Brothers Band Live at Fillmore East" album was appearing twice in both the Cover Flow and Album list. That was strange, except that after the latest sync it now appears six times! It's only in one place in iTunes, and not erroneously set as a compilation or anything. This is the only album displaying this behavior...
Thanks for any suggestions or advice!
Frank
Message was edited by: frank3siYes my e-mail address is [email protected]
Thank you for your kind attention to my problem. I am looking for one on one brief consultation with my laptop in Cincinnati. If not then I will compose a clear question with VI.
These manuals are well known to me NI Visions Concepts ManualIMAQ Vision for LaVIEW User ManuelNI-IMAQ for USB Cameras My problem is moving to the next step of Create an array of USB imagePerform math on array Display results Sincerely,Tom Lohre cell 513-236-1704, [email protected] http://tomlohre.com/images/lafley.jpgAG Lafley, Chairman & CEO of Proctor & Gamble http://tomlohre.com/lafley.htm A.G. Lafley enjoyed hearing of Tom's painting robot and thought it played well to his new book: "The Game-Changer: How You Can Drive Revenue and Profit Growth With Innovation." http://tomlohre.com/newart.htm
Tom Lohre artist/scientist
Has a operating painting robot using RoboLab/RCX
Developing a LabView/ NXT robot that analyzes an image for aesthetic quality. -
Help with Cisco Output Interpreter tool!!
Hi All,
I am experiencing a problem with Cisco Output Interpreter tool.
While the tool is working fine and displaying the "CONFIGURATION COMMAND REFERENCE NOTIFICATIONS (if any)" very effectively but I am unable to use the hyperlink to get an understanding about a particular command.
When I click on a particular command(hyperlink) it pops up another window and the below error is displayed.
Not Found
The requested URL /cgi-bin/Support/Cmdlookup/ios-command-lookup.pl was not found on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
Anyone else had/have this particular error. Could you please help me with this.
Apologies if this topic does not belong to this group.
Thanks in advance
SamNoone to help me on this?
-
Need Help with Array.sort and compare
Hi
I have a big problem, i try to make a java class, where i can open a file and add new words, and to sort them in a right order
Ok everthing works fine, but i get a problem with lower and upper cases.
So i need a comparator, i tried everything but i just dont understand it.
How do i use this with Array.sort??
I hope someone can help meOkay, you want to ignore case when sorting.
There are two possibilities: Truly ignore case, so that any of the following are possible, and which one you'll actually get is undefined, and may vary depending on, say, which order the words are entered in the first place:
English english German german
english English german German
English english german German
english English German german
The second possibility is that you do consider case, but it's of lower priority--it's only considered if the letters are the same. This allows only the first two orderings above.
Either way, you need to write a comparator, and call an Arrays.sort method that takes both array and Comparator.
The first situation is simpler. Just get an all upper or lower case copy of the strings, and then compare thosepublic int compare(Object o1, Object o2) {
String s1 = ((String)o1).toUpper();
String s2 = ((String)o1).toUpper();
return s1.compareTo(s2);
} You'll need to add your own null check if you need one.
For the second way, your comparator will need to iterate over each pair of characters. If the characters are equal, ignoring case, then you compare them based on case. You pick whether upper is greater or less than lower.
Of course, the need to do this assumes that such a method doesn't alrady exist. I don't know of one, but I haven't looked. -
Seeking help with software upgrade questions for my PowerBook G4
I am seeking help/advice for a very low tech guy. I upgraded my PowerBook G4 (ancient I know but I have trouble with our thow away society), to Leopard 10.5.2. However, my iDVD no longer works. I plan on upgrading to iLife'08, but based on the system requirements, I am not certain all of the features (i.e. iMovie'08) will work on my older processor. Before I upgrade to iLife, can anyone tell me if I should do it and if they will work on my all the features will work on my PowerBook G4?
Many prefer iLife'06 to '08, but we went from '05 to '08.
You are correct in that iMovie'08 will not run on your Book, but when you install iLife'08 you are given the opportunity to download iMovie'06 for free.
I can't vouch for it fixing your iDVD however.
Joe -
MSI P67A-C45 (B3) Newb needs Help with connections..
Hi all..
First time posting here, but have been in the shadows for quite a while..
Anyway, i decided to finally take the plunge, and build my own PC, and now i'm beginning to hit a few bumps.
I have a couple of questions that i would like some help with, if possible to reassure myself i may be in the right direction..
I bought THIS PSU and was hoping someone could tell me where the Blue connectors (one labelled CP and one labelled U1) Connect to?
Is it into JPWR2? And does it/do they only connect in the correct way? (Do i remove the plastic cap and attach both?
and i bought THIS VIDEO/GRAPHICS CARD and i'm guessing the RED "PCI express" and "SLI ready" connect to that somehow (Haven't opened box yet for card)
Again, wondering is there a certain way for them to connect.
Also, from my chassis, the "AC '97" and "HDA" connectors go to JAUD (I guess), does it matter which one? (I currently have "HDA" connected)
I have i5 2500k already on board. (If that makes a difference).Quote from: Ben_Cartwright on 26-May-11, 22:05:35
Do the Audio plugs go into JAUD? and does it matter which one?
Yep, connect the front panel audio to the JAUD. If you need the pin layout, it says in the manual. I would say the HDA connector is the one to connect.
Quote from: Ben_Cartwright on 26-May-11, 22:05:35
Any recommendations for testing it all, before i plug it in, and press the power?
Should i (Can i) test individual parts first?
Thanks again.
Check all power connections, seating of the RAM and add-on cards, check the HSF is plugged into the fan header, and obvious things like that.
As for testing, enter the BIOS and make sure the CPU isn't running too hot. Set up the RAM with the required timings and voltage, and test with >>Memtest86<< for several hours. No point starting the Windows installation if say your RAM has errors, since it will corrupt files during the install, if it installs at all. -
A little bit of help with arrays
Hi guyz
I have a problem regarding reading and processing element of an array. I have a "Reference Base Generator" and for example I generate a sine wave. Then I use "Get waveform components" to get the data from the graphic, after this i have a 1-D array of data (right?) at the output of the "Get waveform component' bloc. I need to read every element, process it and then send it as a value further to a function input. So, how can i get every element of that array and send it further ?
I hope I was clear with my problem.
It would be great if you could provide me with some help.
Thanks alot,
Andrei_L.
Solved!
Go to Solution.And just for completeness sake:
There are only two ways to tell somebody thanks: Kudos and Marked Solutions
Unofficial Forum Rules and Guidelines
Attachments:
Example_VI_BD.png 24 KB -
Hello, I have the following query that I'm running in Oracle SQL Developer 1.2.1
WITH group_by_4_column_results AS
(SELECT m_atschunk.employee AS employee,
SUM(CASE
WHEN
M_ATSCHUNK.rolloffDaysCount = '108545043' AND m_atschunk.infractiondate BETWEEN SYSDATE - 365 AND SYSDATE THEN 1 ELSE 0 END) as rolloffs,
M_ATSCHUNK.INFRACTIONDATE + 365 as infractionDate
FROM M_ATSCHUNK
group by employee, infractionDate, rolloffDaysCount
SELECT g4.*,
SUM (rolloffs) OVER (PARTITION BY employee) AS total_rolloffs
FROM group_by_4_column_results g4
It will output the key elements of what I need. But where it sums up the 'total_rolloffs', I need to add that number back into the infractiondate column. Any help would be greatly appreciated.
CREATE TABLE M_ATSCHUNK
(EMPLOYEE varchar(50),
ROLLOFFDAYSCOUNT varchar(3),
INFRACTIONDATE date)
INSERT INTO M_ATSCHUNK (EMPLOYEE, ROLLINGOFFDAYSCOUNT, INFRACTIONDATE)
VALUES ('PHIL','YES', (to_date('2010/01/01 08:00:00', 'yyyy/mm/dd hh24:mi:ss'))),
VALUES ('PHIL','YES', (to_date('2010/01/02 08:00:00', 'yyyy/mm/dd hh24:mi:ss'))),
VALUES ('PHIL','YES', (to_date('2010/01/03 08:00:00', 'yyyy/mm/dd hh24:mi:ss'))),
VALUES ('PHIL','YES', (to_date('2010/01/04 08:00:00', 'yyyy/mm/dd hh24:mi:ss'))),
VALUES ('PHIL','YES', (to_date('2010/01/05 08:00:00', 'yyyy/mm/dd hh24:mi:ss'))),
VALUES ('PHIL','NO', (to_date('2010/02/01 08:00:00', 'yyyy/mm/dd hh24:mi:ss'))),
VALUES ('PHIL','NO', (to_date('2010/03/01 08:00:00', 'yyyy/mm/dd hh24:mi:ss'))),
VALUES ('NIKI','YES', (to_date('2010/01/01 08:00:00', 'yyyy/mm/dd hh24:mi:ss'))),
VALUES ('NIKI','YES', (to_date('2010/01/01 08:00:00', 'yyyy/mm/dd hh24:mi:ss'))),
VALUES ('NIKI','YES', (to_date('2010/01/01 08:00:00', 'yyyy/mm/dd hh24:mi:ss'))),
VALUES ('NIKI','NO', (to_date('2010/01/01 08:00:00', 'yyyy/mm/dd hh24:mi:ss'))),
VALUES ('NIKI','NO', (to_date('2010/01/01 08:00:00', 'yyyy/mm/dd hh24:mi:ss'))),
VALUES ('NIKI','NO', (to_date('2010/01/01 08:00:00', 'yyyy/mm/dd hh24:mi:ss'))),
VALUES ('NIKI','NO', (to_date('2010/01/01 08:00:00', 'yyyy/mm/dd hh24:mi:ss')))Phil3061 wrote:
I need to add that number back into the infractiondate column.Well, in general you need to use UPDATE or better MERGE. Howebver, your data sample does not show any rollofs:
SQL> SELECT * FROM M_ATSCHUNK;
EMPLOYEE ROL INFRACTIO
PHIL YES 01-JAN-10
PHIL YES 02-JAN-10
PHIL YES 03-JAN-10
PHIL YES 04-JAN-10
PHIL YES 05-JAN-10
PHIL NO 01-FEB-10
PHIL NO 01-MAR-10
NIKI YES 01-JAN-10
NIKI YES 01-JAN-10
NIKI YES 01-JAN-10
NIKI NO 01-JAN-10
EMPLOYEE ROL INFRACTIO
NIKI NO 01-JAN-10
NIKI NO 01-JAN-10
NIKI NO 01-JAN-10
14 rows selected.
SQL> WITH group_by_4_column_results AS
2 (SELECT m_atschunk.employee AS employee,
3 SUM(CASE
4 WHEN
5 M_ATSCHUNK.rolloffDaysCount = '108545043' AND m_atschunk.infractiondate BETWEEN SYSDATE - 365 AND SYSDATE THEN 1 ELSE 0 END) as
rolloffs,
6 M_ATSCHUNK.INFRACTIONDATE + 365 as infractionDate
7 FROM M_ATSCHUNK
8 group by employee, infractionDate, rolloffDaysCount
9 )
10 SELECT g4.*,
11 SUM (rolloffs) OVER (PARTITION BY employee) AS total_rolloffs
12 FROM group_by_4_column_results g4
13 /
EMPLOYEE ROLLOFFS INFRACTIO TOTAL_ROLLOFFS
NIKI 0 01-JAN-11 0
NIKI 0 01-JAN-11 0
PHIL 0 01-JAN-11 0
PHIL 0 02-JAN-11 0
PHIL 0 03-JAN-11 0
PHIL 0 04-JAN-11 0
PHIL 0 05-JAN-11 0
PHIL 0 01-FEB-11 0
PHIL 0 01-MAR-11 0
9 rows selected.
SQL> So adjust data sample and based on it tell us what are the expected results.
SY. -
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. -
Help with sound output via HDMI
My sound output via HDMI suddenly stopped worked to my TV set. I've reset the PRAM and the SMC. When I go to sound control panel for sound output, the setting is on Headphones. When I try to change it to SV420XVT1A (the tv) it immediately jumps back to headphone. I also tried a different HDMI cable to a different HDMI port on the tv. This just started after the Mac Mini had been turned off for a week. I'm using Lion and it's an 8GB Intel Core 2 Duo. Any suggestions?
I actually discovered this answer about 5 minutes after I posted the question. Thanks a lot for your help!! Funny thing is that it had worked all along with something plugged in the headphone jack but suddenly stopped working. Again, thanks!
-
Newbie needing help with code numbers and if-else
I'm 100% new to any kind of programming and in my 4th week of an Intro to Java class. It's also an on-line class so my helpful resources are quite limited. I have spent close to 10 hours on my class project working out P-code and the java code itself, but I'm having some difficulty because the project seems to be much more advanced that the examples in the book that appear to only be partly directly related to this assignment. I have finally come to a point where I am unable to fix the mistakes that still show up. I'm not trying to get anyone to do my assignment for me, I'm only trying to get some help on what I'm missing. I want to learn, not cheat.
Okay, I have an assignment that, in a nutshell, is a cash register. JOptionPane prompts the user to enter a product code that represents a product with a specific price. Another box asks for the quanity then displays the cost, tax and then the total amount plus tax, formatted in dollars and cents. It then repeats until a sentinel of "999" is entered, and then another box displays the total items sold for the day, amount of merchandise sold, tax charged, and the total amount acquired for the day. If a non-valid code is entered, I should prompt the user to try again.
I have this down to 6 errors, with one of the errors being the same error 5 times. Here are the errors:
C:\PROGRA~1\XINOXS~1\JCREAT~1\MyProjects\Sales.java:50: 'else' without 'if'
else //if invalid code entered, output message
^
C:\PROGRA~1\XINOXS~1\JCREAT~1\MyProjects\Sales.java:39: unexpected type
required: variable
found : value
100 = 2.98;
^
C:\PROGRA~1\XINOXS~1\JCREAT~1\MyProjects\Sales.java:41: unexpected type
required: variable
found : value
200 = 4.50;
^
C:\PROGRA~1\XINOXS~1\JCREAT~1\MyProjects\Sales.java:43: unexpected type
required: variable
found : value
300 = 6.79;
^
C:\PROGRA~1\XINOXS~1\JCREAT~1\MyProjects\Sales.java:45: unexpected type
required: variable
found : value
400 = 5.29;
^
C:\PROGRA~1\XINOXS~1\JCREAT~1\MyProjects\Sales.java:47: unexpected type
required: variable
found : value
500 = 7.20;
^
And finally, here is my code. Please be gentle with the criticism. I've really put a lot into it and would appreciate any help. Thanks in advance.
import java.text.NumberFormat; // class for numeric formating from page 178
import javax.swing.JOptionPane; // class for JOptionOPane
public class Sales {
//main method begins execution ofJava Application
public static void main( String args[] )
double quantity; // total of items purchased
double tax; // total of tax
double value; // total cost of all items before tax
double total; // total of items including tax
double totValue; // daily value counter
double totTax; // daily tax counter
double totTotal; // daily total amount collected (+tax) counter
double item; //
String input; // user-entered value
String output; // output string
String itemString; // item code entered by user
String quantityString; // quantity entered by user
// initialization phase
quantity = 0; // initialize counter for items purchased
// get first code from user
itemString = JOptionPane.showInputDialog(
"Enter item code:" );
// convert itemString to double
item = Double.parseDouble ( itemString );
// loop until sentinel value read from user
while ( item != 999 ) {
// converting code to amount using if statements
if ( item == 100 )
100 = 2.98;
if ( item == 200 )
200 = 4.50;
if ( item == 300 )
300 = 6.79;
if ( item == 400 )
400 = 5.29;
if ( item == 500 )
500 = 7.20;
else //if invalid code entered, output message
JOptionPane.showMessageDialog( null, "Invalid code entered, please try again!",
"Item Code", JOptionPane.INFORMATION_MESSAGE );
} // end if
} // end while
// get quantity of item user
itemString = JOptionPane.showInputDialog(
"Enter quantity:" );
// convert quantityString to int
quantity = Double.parseDouble ( quantityString );
// add quantity to quantity
quantity = quantity + quantity;
// calculation time! value
value = quantity * item;
// calc tax
tax = value * .07;
// calc total
total = tax + value;
//add totals to counter
totValue = totValue + value;
totTax = totTax + tax;
totTotal = totTotal + total;
// display the results of purchase
JOptionPane.showMessageDialog( null, "Amount: " + value +
"\nTax: " + tax + "\nTotal: " + total, "Sale", JOptionPane.INFORMATION_MESSAGE );
// get next code from user
itemString = JOptionPane.showInputDialog(
"Enter item code:" );
// If sentinel value reached
if ( item == 999 ) {
// display the daily totals
JOptionPane.showMessageDialog( null, "Total amount of items sold today: " + quantity +
"\nValue of ites sold today: " + totValue + "\nTotal tax collected today: " + totTax +
"\nTotal Amount collected today: " + totTotal, "Totals", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 ); // terminate application
} // end sentinel
} // end message
} // end class SalesHere you go. I haven't tested this but it does compile. I've put in a 'few helpful hints'.
import java.text.NumberFormat; // class for numeric formating from page 178
import javax.swing.JOptionPane; // class for JOptionOPane
public class TestTextFind {
//main method begins execution ofJava Application
public static void main( String args[] )
double quantity; // total of items purchased
double tax; // total of tax
double value; // total cost of all items before tax
double total; // total of items including tax
// double totValue; // daily value counter
// double totTax; // daily tax counter
// double totTotal; // daily total amount collected (+tax) counter
// Always initialise your numbers unless you have a good reason not too
double totValue = 0; // daily value counter
double totTax = 0; // daily tax counter
double totTotal = 0; // daily total amount collected (+tax) counter
double itemCode;
double item = 0;
String itemCodeString; // item code entered by user
String quantityString; // quantity entered by user
// initialization phase
quantity = 0; // initialize counter for items purchased
// get first code from user
itemCodeString = JOptionPane.showInputDialog("Enter item code:" );
// convert itemString to double
itemCode = Double.parseDouble ( itemCodeString );
// loop until sentinel value read from user
while ( itemCode != 999 ) {
* 1. variable item mightnot have been initialised
* You had item and itemCode the wrong way round.
* You are supposed to be checking itemCode but setting the value
* for item
// converting code to amount using if statements
if ( item == 100 )
{itemCode = 2.98;}
else if ( item == 200 )
{itemCode = 4.50;}
else if ( item == 300 )
{itemCode = 6.79;}
else if ( item == 400 )
{itemCode = 5.29;}
else if ( item == 500 )
{itemCode = 7.20;}
else {//if invalid code entered, output message
JOptionPane.showMessageDialog( null, "Invalid code entered, please try again!",
"Item Code", JOptionPane.INFORMATION_MESSAGE );
} // end if
} // end while
// get quantity of item user
itemCodeString = JOptionPane.showInputDialog("Enter quantity:" );
* 2.
* You have declared quantityString here but you never give it a value.
* I think this should be itemCodeString shouldnt it???
* Or should you change itemCodeString above to quantityString?
// convert quantityString to int
// quantity = Double.parseDouble ( quantityString ); // old code
quantity = Double.parseDouble ( itemCodeString );
// add quantity to quantity
quantity = quantity + quantity;
// calculation time! value
value = quantity * itemCode;
// calc tax
tax = value * .07;
// calc total
total = tax + value;
//add totals to counter
* 3. 4. and 5.
* With the following you have not assigned the 'total' variables a value
* so in effect you are saying eg. "total = null + 10". Thats why an error is
* raised. If you look at your declaration i have assigned them an initial
* value of 0.
totValue = totValue + value;
totTax = totTax + tax;
totTotal = totTotal + total;
// display the results of purchase
JOptionPane.showMessageDialog( null, "Amount: " + value +
"\nTax: " + tax + "\nTotal: " + total, "Sale", JOptionPane.INFORMATION_MESSAGE );
// get next code from user
itemCodeString = JOptionPane.showInputDialog("Enter item code:" );
// If sentinel value reached
if ( itemCode == 999 ) {
// display the daily totals
JOptionPane.showMessageDialog( null, "Total amount of items sold today: " + quantity +
"\nValue of ites sold today: " + totValue + "\nTotal tax collected today: " + totTax +
"\nTotal Amount collected today: " + totTotal, "Totals", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 ); // terminate application
} // end sentinel
} // end message
} // end class SalesRob.
Maybe you are looking for
-
Error while updating customer data through IDOC.
hi all, I am using the function module "IDOC_INPUT_DEBITOR" to update the customer master data but i was getting an error "editing was terminated".Please help to solve this problem. regards, Suresh.
-
PI 7.1 Upgrade Mount Point
Hi. Im upgrading a 7.0 PI system to 7.1, and all was going well until the system asked about the mount points. I have tried everything - the cds, the downloaded product. Nothing seems to recognise the 'SAP Kernel DVD Unicode' folders /cds. Its able t
-
Creating table using joins in subquery
can we create a table by using joins in subquery?? like this create table emp as select * from employees e,departments d where d.department_id=e.department_id can we ??
-
Bank Routing and Wire ABA Nos. in the Table BNKA
Hi, We are currently using the Payment Methods - ACH and Wire Payments for Automatic payments to the vendors. Every month we follow the process of downloading the ACH Bank Routing Nos. which are contained in the File FedACHdir.txt from the FRFS (Fede
-
Fonts in chromium/gmail blurry
i just installed some new chinese fonts, and a few other things, and now gmail in google-chrome looks all blurry. i've tried changing the settings, but nothing changes. should i just remove some of these? -rw-r--r-- 1 root root 412K Jul 23 02:29 fire