The Artima Developer Community
Sponsored Link

Java Answers Forum
i need an answer for this please

11 replies on 1 page. Most recent reply: Sep 21, 2003 11:21 AM by Matt Gerrans

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 11 replies on 1 page
khalid

Posts: 1
Nickname: rzaz
Registered: Sep, 2003

i need an answer for this please Posted: Sep 19, 2003 5:25 PM
Reply to this message Reply
Advertisement
can u guys please help me out with this problem
Q: Write a program that will read integers and find the total and average of the input values, not counting zero, your program ends with the input 0. Display the average as a floating-point number.

i will be thankfull if you guys could help me out with this problem
khalid20_20@hotmail.com


Kevin

Posts: 27
Nickname: quasi
Registered: Apr, 2003

Re: i need an answer for this please Posted: Sep 19, 2003 6:00 PM
Reply to this message Reply
Do your own homework.

Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: i need an answer for this please Posted: Sep 20, 2003 4:05 PM
Reply to this message Reply
Well, I'm supporting the move to water down the programmer population with people who have managed to get computer science degrees without writing a single line of code. After all, they are the competition, such as it is. So, here you go:

# A demonstration of reading input and transmogifying typed-in integers
# into the average value of them all, with the wonders of modern high-tech
# gizmos.
#
# Copyright 2003, Matt Gerrans.
#
# Turning in this code as homework is a violation of ethical principals,
# and punishable by severe penalties (including, but not limited to, a
# boot to the head), even if you change the variable names.
import os,sys,time
 
# Incredible technology to log uncaught exeptions to a log file with the
# same name as the script in the temp directory.
def StartLog(args):
   # First add a header to the log entry for this run:
   from os.path import basename,splitext,join,isfile,abspath
   scriptName = basename(args[0])
   logfilename = join( os.environ['temp'], splitext(scriptName)[0] ) + '.log'
   firstEntry = not isfile(logfilename)
   logfile = file( logfilename, 'a' )
   if firstEntry:
      header = '%s Log\n' % (abspath(args[0]))
      logfile.write( header )
      logfile.write( '-'*(len(header)-1) )
   logfile.write( '\n%s:\n' % time.asctime() )
   logfile.close()
   # Now rebind stderr to the log:
   sys.stderr = open( logfilename, 'a' )
 
def main(args=None):
   errorlevel = 0
 
   numbers = []
   input = raw_input('Please type a number into my homework program! ')
   while input != '0':
      try:
         numbers.append(int(input))
      except ValueError:
         print 'Try entering a number, smartypants.'
      input = raw_input('Than you sir, may I have another? ')
   if numbers:
      avg = (reduce(lambda a,b:a+b,numbers)/long(len(numbers)))
      print 'Average of those numbers is %f' % avg
   else:
      print 'You have to enter some numbers, pal.'
      errorlevel = 1
 
   return errorlevel
 
def MainWrapper(args=None):
   if args == None: args = sys.argv
   StartLog(args)
   return main(args)
   
# Entry point when run by command-line.
if __name__ == '__main__':
   sys.exit(MainWrapper(sys.argv))
 

Senthoorkumaran Punniamoorthy

Posts: 335
Nickname: senthoor
Registered: Mar, 2002

Re: i need an answer for this please Posted: Sep 20, 2003 6:44 PM
Reply to this message Reply
Hay Matt,

Wonderfull Job, but could you tell me what Language it is?

Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: i need an answer for this please Posted: Sep 20, 2003 9:05 PM
Reply to this message Reply
It is Python, strictly speaking, but you could run it with Jython, so then it would be Java, then the original poster could turn it in as Java homework. The professor will be doubly impressed, I'm sure.

Senthoorkumaran Punniamoorthy

Posts: 335
Nickname: senthoor
Registered: Mar, 2002

Re: i need an answer for this please Posted: Sep 20, 2003 9:41 PM
Reply to this message Reply
Matt,

I would like your opinion here

I am planning to invest my time in learning another language. I am in confusion as to which language I should invest my time in? Thinking about Python and Ruby at the moment, but hard to decide.... In his blog under in the link below under the heading Basic Mathematics Charles Miller talks about Ruby. What would be your opinion?

http://fishbowl.pastiche.org/archives/2003_09.html

Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: i need an answer for this please Posted: Sep 20, 2003 11:01 PM
Reply to this message Reply
When I first learned Perl it was a bit of a labor, because it just seemed to often be quiky, complicated and arbitrary. Later, whenever I wanted to write a Perl script, I could never remember the syntax and always had to find a book or reference. Or just give up and write the thing in another language. I kept thinking I should stick with it, because it was so popular and people were always touting it as so powerful. And it is. I just couldn't get comfortable with it. And of course, whenever I look Perl code, it is completely incomprehensible (even if I wrote it).

Since I was working mainly on the Windows platform and it was begining to look like WSH (Windows Script Host) was going to be "the thing" there (such as always being pre-installed, having easy access to COM automation objects and Windows Management Instrumentation), I resigned myself to JScript. Even though I learned VB in its early days (keeping abreast version 1 - 5, or so), I just couldn't stomach that synatx (in VBScript) any more than necessary (unfortunately, since the MSDN examples are predominantly VBS instead of JS, it is much more necessary than I'd like). However, JScript is very hard to write well and very hard to debug. It is also very verbose; often things that seem like pretty simple tasks take pages and pages of code.

Then I discovered Python. It was such a breeze to learn. Everything seemed to be done in a straight-forward and simple way. Often, while learning it, I'd be thinking "it sure would be nifty if it could do x, or if it worked like y" only to find that to be the case a few pages later. I loved the idea of using indentation as the demarcation of code blocks; some people complain that it seems unusual, but what's wrong with that? Most good ideas do, at first. I thought it was brilliant when I first saw it: good code is always properly indented, so why not use that information and, at the same time, enforce good indentation style in all code? Python code manages to be quite concise (like Perl) and yet very readable (unlike Perl). Python is exceptionally good at text processing, so even while I'm usually working on C++, Java, or (currently) C# projects, I still use a lot of Python for code generation, project maintenance and miscellaeous tasks.

About a year or so later, even before reading The Pragmatic Programmer, I heard about Ruby. I studied it for a while and it had some nifty features, but it was unable to unseat Python as my favorite scripting language. I like Python syntax better than Ruby (which reminds me a little of VB syntax in some ways) and Python now has such incredible library support that one of Ruby's best features is the fact that it can import Python libraries. If it were not for Python, Ruby would probably be my scripting language of choice.

Anyhow, I think that answers the question: I would recommend Python. However, I think the more you know, the better, so I would encourage you to learn both: First learn Python -- I bet it will take much less time than you expect. Then you'll have time left over to learn Ruby!

FredrikN

Posts: 22
Nickname: fredrikn
Registered: Jul, 2003

Re: i need an answer for this please Posted: Sep 20, 2003 11:12 PM
Reply to this message Reply
The answer is easy so if he can't get it from here he will get it from somewhere else.

But remember khalid, if you don't learn it yourself you will never pass the exam.


import java.io.*;
 
public class Driver
{
 
	public static void main(String[] args) throws IOException
	{
		BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
	
		System.out.println("Enter a new height on each row(0 will quit and start calculate average)");
	
		String indata = "";
		int data = 0;
		int personer = 0;
		
		while(!indata.equals("0"))
		{
			System.out.print("New height: ");
			indata = console.readLine();
			
			if(!indata.equals("0"))
			{
				data = data + Integer.parseInt(indata);
				personer++;
			}
		}
		
		System.out.println("Average height is " + (data/personer));
	
	}
 
}

FredrikN

Posts: 22
Nickname: fredrikn
Registered: Jul, 2003

Re: i need an answer for this please Posted: Sep 20, 2003 11:44 PM
Reply to this message Reply
Missed "as float" so here is the correct float version, also added some error checking

import java.io.*;
 
public class Driver
{
 
	public static void main(String[] args) throws IOException
	{
		BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
	
		System.out.println("Enter a new height on each row(0 will quit and start calculate average)");
	
		String indata = "";
		float data = 0;
		int personer = 0;
		
		while(!indata.equals("0"))
		{
			System.out.print("New height: ");
			indata = console.readLine();
			
			if(!indata.equals("0"))
			{
				try
				{
					data = data + Float.parseFloat(indata);
					personer++;
				}
				catch(NumberFormatException error)
				{
					System.out.println("Wrong input, try again");
				}
			}
		}
		
		System.out.println("Average height is " + (data/personer));
	
	}
 
}

Senthoorkumaran Punniamoorthy

Posts: 335
Nickname: senthoor
Registered: Mar, 2002

Re: i need an answer for this please Posted: Sep 21, 2003 3:51 AM
Reply to this message Reply
Thanx Matt for taking time to explain things in detail, Thats was indeed very helpful. Any recomondation for any good books for Python?

Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: i need an answer for this please Posted: Sep 21, 2003 11:12 AM
Reply to this message Reply
I first learned Python with Learning Python, by Mark Lutz and David Ascher. I think it was probably the best programming language book I've read. The only drawback now is that the current edition is out-of-date: it covers Python 1.5.2, whereas the latest version of Python is 2.3 and there have been many major improvements to the language between the two. The good news is that the second edition of the book is in the works. I don't know when it will be released. Now there are a ton of books on Python, though. They all started appearing after I had already learned Python, so I don't know which ones are best for learning Python (the Python Cookbook is pretty handy once you have learned Python, though and Python Programming on Win32 is very valuable if you are working on Windows). Have a look on Python.org and Amazon; you can probably find recommendations. Also, Python itself comes with a tutorial, so you can get started on that even before you decide on a book.

Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: i need an answer for this please Posted: Sep 21, 2003 11:21 AM
Reply to this message Reply
...Ah, it looks like Learning Python, Second Edition should be out right about now, or very soon: http://www.rmi.net/~lutz/about-lp2e.html

Flat View: This topic has 11 replies on 1 page
Topic: Integer Stacks Previous Topic   Next Topic Topic: How do i create a jar application.

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use