This document contains code for a Java program that defines a Computer class. The Computer class stores information about computers available from a dealer, including company name, RAM size, hard disk capacity, processor speed, processor make, price, and quantity. The main method creates an array of Computer objects and takes user input to populate the object fields, validating the quantity and price fields. A method is also included to display the details of a single Computer object.
The art of reverse engineering flash exploitsPriyanka Aash
"Adobe Flash is one of the battlegrounds of exploit and mitigation methods. As most of the Flash exploits demonstrate native memory layer exploit technique, it is valuable to understand the memory layout and behavior of Adobe Flash Player. We developed fine-grained debugging tactics to observe memory exploit technique and the way to interpret them effectively. This eventually helps defenders to understand new exploit techniques that are used for current targets quickly. This information is also valuable in deciding which area should defenders focus on for mitigation and code fixes. Adobe Flash Player was one of the major attack targets in 2015. We observed at least 17 effective zero-days or 1-day attacks in the wild. Flash is not just used by exploit kits like Angler, it has also been commonly used for advanced persistent threat (APT) attacks. The bug class ranges from simple heap overflows, uninitialized memory to type confusion and use-after-free. At Microsoft, understanding exploits in-the-wild is a continuous process. Flash exploit is one of the hardest to reverse-engineer. It often involves multi-layer obfuscation, and by default, is highly obfuscated and has non-decompilable codes. The challenge with Flash exploit comes from the lack of tools for static and dynamic analysis. Exploits are written with ActionScript programming language and obfuscated in bytecode level using commercial-grade obfuscation tools. Understanding highly obfuscated logic and non-decompilable AVM bytecode is a big challenge. Especially, the lack of usable debuggers for Flash file itself is a huge hurdle for exploit reverse engineers. It is just like debugging PE binaries without using Windbg or Olly debugger. The ability of the researcher is highly limited.
With this presentation, I want to deliver two things: 1. The tactics and debugging technique that can be used to reverse engineer exploits. This includes using existing toolsets and combining them in an effective way. 2. The detailed exploit code reverse engineering examples that can help you understand what's the current and past status of attack and mitigation war. You might have heard of Vector corruption, ByteArray corruption and other JIT manipulation technique. Technical details will be discussed on how the exploits are using these and how the vendor defended against these."
(Source: Black Hat USA 2016, Las Vegas)
How to Become a Thought Leader in Your NicheLeslie Samuel
Are bloggers thought leaders? Here are some tips on how you can become one. Provide great value, put awesome content out there on a regular basis, and help others.
The art of reverse engineering flash exploitsPriyanka Aash
"Adobe Flash is one of the battlegrounds of exploit and mitigation methods. As most of the Flash exploits demonstrate native memory layer exploit technique, it is valuable to understand the memory layout and behavior of Adobe Flash Player. We developed fine-grained debugging tactics to observe memory exploit technique and the way to interpret them effectively. This eventually helps defenders to understand new exploit techniques that are used for current targets quickly. This information is also valuable in deciding which area should defenders focus on for mitigation and code fixes. Adobe Flash Player was one of the major attack targets in 2015. We observed at least 17 effective zero-days or 1-day attacks in the wild. Flash is not just used by exploit kits like Angler, it has also been commonly used for advanced persistent threat (APT) attacks. The bug class ranges from simple heap overflows, uninitialized memory to type confusion and use-after-free. At Microsoft, understanding exploits in-the-wild is a continuous process. Flash exploit is one of the hardest to reverse-engineer. It often involves multi-layer obfuscation, and by default, is highly obfuscated and has non-decompilable codes. The challenge with Flash exploit comes from the lack of tools for static and dynamic analysis. Exploits are written with ActionScript programming language and obfuscated in bytecode level using commercial-grade obfuscation tools. Understanding highly obfuscated logic and non-decompilable AVM bytecode is a big challenge. Especially, the lack of usable debuggers for Flash file itself is a huge hurdle for exploit reverse engineers. It is just like debugging PE binaries without using Windbg or Olly debugger. The ability of the researcher is highly limited.
With this presentation, I want to deliver two things: 1. The tactics and debugging technique that can be used to reverse engineer exploits. This includes using existing toolsets and combining them in an effective way. 2. The detailed exploit code reverse engineering examples that can help you understand what's the current and past status of attack and mitigation war. You might have heard of Vector corruption, ByteArray corruption and other JIT manipulation technique. Technical details will be discussed on how the exploits are using these and how the vendor defended against these."
(Source: Black Hat USA 2016, Las Vegas)
How to Become a Thought Leader in Your NicheLeslie Samuel
Are bloggers thought leaders? Here are some tips on how you can become one. Provide great value, put awesome content out there on a regular basis, and help others.
Nous entendons aujourd’hui parler de Deep Learning un peu partout : reconnaissance d’images, de sons, génération de textes, etc. Suite aux récentes annonces sur Android Neural Network API et TensorFlowLite et à la release du framework CoreML d’Apple, tout nous pousse vers le “on-device intelligence”.
Bien que les techniques et frameworks soient en train de se démocratiser, il reste difficile d’en voir les applications concrètes en entreprise, et encore moins sur des applications mobiles. Nous avons donc décidé de construire un Proof Of Concept pour relever les défis du domaine.
A travers une application mobile à but éducatif, utilisant du Deep Learning pour de la reconnaissance d’objets, nous aborderons les impacts de ce type de modèles sur les smartphones, l’architecture pour l’entraînement et le déploiement de modèles sur un service Cloud, ainsi que la construction de l’application mobile avec les dernières nouveautés annoncées.
Step-by-step Development of an Application for the Java Card Connected PlatformEric Vétillard
A JavaOne presentation that describes the Java Card Connected development model, based on a practical example.
Beyond Java Card Connected, could be interesting for people who want to develop small embedded Web servers.
Poche chiacchiere e tanto codice per cercare rendere la nostra vita di
sviluppatori più divertente.
Parleremo di JAX-RS, le annotazioni, l'MVC che mette a disposizione e
l'integrazione di Jersey con Guice.
Useremo AOP per gestire log, transazioni e con l'aiuto di Infinispan
limiteremo le chamate concorrenti sul nostro cluster.
How to write clean & testable code without losing your mindAndreas Czakaj
If you create software that is to be developed continuously over several years you'll need a sustainable approach to code quality.
In our early days of AEM development, however, we used to struggle with code that is rigid, hard to test and full of LOG.debug calls.
In this talk I will share some development best practices we have found that really work in actual AEM based software, e.g. to achieve 100% code coverage and provide high confidence in the code base.
Spoiler alert: no new libraries, frameworks or tools are required - once you know the ideas, plain old TDD and the S.O.L.I.D. principles of Clean Code will do the trick.
by Andreas Czakaj, mensemedia Gesellschaft für Neue Medien mbH
Presented at the adaptTo() 2017 conference in Berlin (https://adapt.to/2017/en/schedule/how-to-write-clean---testable-code-without-losing-your-mind.html).
Presentation video can be found on YouTube (https://www.youtube.com/watch?v=JbJw5oN_zL4)
NexGen Solutions for cloud platforms, powered by GenQAIVijayananda Mohire
This is our next generation solutions powered by emerging technologies like AI, quantum computing, Blockchain, quantum cryptography etc. We have various offers that can help improved productivity, help automate and improve ease of doing business. We offer cloud based solutions and have a Hub to interface major cloud platforms.
Nous entendons aujourd’hui parler de Deep Learning un peu partout : reconnaissance d’images, de sons, génération de textes, etc. Suite aux récentes annonces sur Android Neural Network API et TensorFlowLite et à la release du framework CoreML d’Apple, tout nous pousse vers le “on-device intelligence”.
Bien que les techniques et frameworks soient en train de se démocratiser, il reste difficile d’en voir les applications concrètes en entreprise, et encore moins sur des applications mobiles. Nous avons donc décidé de construire un Proof Of Concept pour relever les défis du domaine.
A travers une application mobile à but éducatif, utilisant du Deep Learning pour de la reconnaissance d’objets, nous aborderons les impacts de ce type de modèles sur les smartphones, l’architecture pour l’entraînement et le déploiement de modèles sur un service Cloud, ainsi que la construction de l’application mobile avec les dernières nouveautés annoncées.
Step-by-step Development of an Application for the Java Card Connected PlatformEric Vétillard
A JavaOne presentation that describes the Java Card Connected development model, based on a practical example.
Beyond Java Card Connected, could be interesting for people who want to develop small embedded Web servers.
Poche chiacchiere e tanto codice per cercare rendere la nostra vita di
sviluppatori più divertente.
Parleremo di JAX-RS, le annotazioni, l'MVC che mette a disposizione e
l'integrazione di Jersey con Guice.
Useremo AOP per gestire log, transazioni e con l'aiuto di Infinispan
limiteremo le chamate concorrenti sul nostro cluster.
How to write clean & testable code without losing your mindAndreas Czakaj
If you create software that is to be developed continuously over several years you'll need a sustainable approach to code quality.
In our early days of AEM development, however, we used to struggle with code that is rigid, hard to test and full of LOG.debug calls.
In this talk I will share some development best practices we have found that really work in actual AEM based software, e.g. to achieve 100% code coverage and provide high confidence in the code base.
Spoiler alert: no new libraries, frameworks or tools are required - once you know the ideas, plain old TDD and the S.O.L.I.D. principles of Clean Code will do the trick.
by Andreas Czakaj, mensemedia Gesellschaft für Neue Medien mbH
Presented at the adaptTo() 2017 conference in Berlin (https://adapt.to/2017/en/schedule/how-to-write-clean---testable-code-without-losing-your-mind.html).
Presentation video can be found on YouTube (https://www.youtube.com/watch?v=JbJw5oN_zL4)
NexGen Solutions for cloud platforms, powered by GenQAIVijayananda Mohire
This is our next generation solutions powered by emerging technologies like AI, quantum computing, Blockchain, quantum cryptography etc. We have various offers that can help improved productivity, help automate and improve ease of doing business. We offer cloud based solutions and have a Hub to interface major cloud platforms.
This is our project work at our startup for Data Science. This is part of our internal training and focused on data management for AI, ML and Generative AI apps
This is our contributions to the Data Science projects, as developed in our startup. These are part of partner trainings and in-house design and development and testing of the course material and concepts in Data Science and Engineering. It covers Data ingestion, data wrangling, feature engineering, data analysis, data storage, data extraction, querying data, formatting and visualizing data for various dashboards.Data is prepared for accurate ML model predictions and Generative AI apps
Considering the need and demand for high quality digital platforms that can help clients to get the most of the newer technology, we have proposed an IT Hub that allows for rapid on boarding of clients to various modules on a need basis, allowing them to subscribe to modules they need only. We have various modules.
This document offers a high level overview of our IT Hub that offers various modules allowing for clients to onboard faster and get the benefits of a large set of vendor products, tools, IDE related to AI, Quantum and Generative AI technologies.
This is my hands-on projects in quantum technologies. These are few of the key projects that I worked with that demonstrates my skills in using various concepts, tools, IDE and deriving the solutions by using quantum principles like superposition, and entanglement along with quantum circuits in realizing the concepts
This is my journey taken from year 2012 on wards, after graduation in my MS with major in AI. I have taken various certification courses, trainings, hands-on labs; few key ones are from Google, and Microsoft.
Agricultural and allied industries play a vital role in the progress of a nation and sustainable economic growth. Farmers play a vital role in this progress. Their hard work and efforts need to be praised and possibly offer them various tools and digital assets that can automate some of their various repetitive tasks such as back office operations, crop monitoring, and post-harvesting routines that might divert the attention of farmers from their core job.
We, at Bhadale IT have developed various products and services that are revolutionary and can offer effective solutions with our industrial partnerships with digital technology leaders like Intel and Microsoft. We have drafted this solution brief to illustrate our products and service offerings for the agricultural industry. We can tailor make highly customized solutions to meet individual project and farmer needs that can include use of various technologies like artificial intelligence, machine learning, data science and related machinery like drones and geo-spatial datasets and various information that can offer precise farming techniques and use of technology in improving production, improvised use of fertilizers, organic farming and reduced crop loss due to rodents, insects and regional diseases.
The focus of this solution is for farmers to adopt and migrate to digital cloud platform to Microsoft Azure that can boost quality and quantity of crop production and improve their supply chain and offer faster and mature downstream business operations.
This is our cloud offerings based on our partnership and relationship with Intel and Microsoft. We offer highly optimized Intel motherboards, memory, and software stack that is best suited for Azure cloud platform and can handle various types of models (IaaS, PaaS, SaaS) and Azure workloads in the public or private cloud.
Explore the fundamentals of GitHub Copilot and its potential to enhance productivity and foster innovation for both individual developers and businesses. Discover how to implement it within your organization and unleash its power for your own projects.
In this learning path, you'll:
Gain a comprehensive understanding of the distinctions between GitHub Copilot for Individuals, GitHub Copilot for Business, and GitHub Copilot X.
Explore various use cases for GitHub Copilot for Business, including real-life examples showcasing how customers have leveraged it to boost their productivity.
Receive step-by-step instructions on enabling GitHub Copilot for Individuals and GitHub Copilot for Business, ensuring a seamless integration into your workflows.
Practical ChatGPT From Use Cases to Prompt Engineering & Ethical ImplicationsVijayananda Mohire
This journey provides learners with a thorough exploration of ChatGPT, starting with an introduction to large language models and their capabilities, the series progresses through practical applications, advanced techniques, industry impacts, and important ethical considerations. Each course aims to equip learners with an in-depth understanding of the model, its functionality, and its wide-ranging applications.
Red Hat Enterprise Linux (RHEL) and Hybrid Cloud Infrastructure. Products that are developed for multi-cloud hybrid platform enabling seamless integration and portability of workloads across Red Hat and partner Infrastructure, public and private clouds.
Learners will be exposed to the foundations of Red Hat, Red Hat Enterprise Linux (RHEL) portfolio including Hybrid Cloud Infrastructure, how to identify target customers, distinguish Red Hat solutions from the competition, review key use cases, align to the sales conversation framework for positioning the solutions, and much more!
Upon completing this learning path, learners will receive the Red Hat Sales Specialist - Red Hat Enterprise Linux accreditation and be prepared to advance to the Red Hat Sales Specialist - Red Hat Enterprise Linux II learning path
This is my annual learning at Red Hat related to accreditation and courses at Red Hat partner training portal.
Learners will be exposed to the foundations of Red Hat, Red Hat Enterprise Linux (RHEL) portfolio including Hybrid Cloud Infrastructure, how to identify target customers, distinguish Red Hat solutions from the competition, review key use cases, align to the sales conversation framework for positioning the solutions, and much more!
Generative AI is a cutting-edge technology that will transform nearly every business function, ranging from content creation and product design, to improving customer experience and marketing new ideas. While the benefits of Generative AI are immense, the technology has its limitations and poses some ethical considerations. In this Journey, learners of all levels will develop a shared understanding of what Generative AI is, the guardrails for use and identify of how to use, build and experiment with the technology in a responsible manner. Learners will also develop skills for leading through this disruption with empathy, while cultivating the human skills to sustain the transformation
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...Juraj Vysvader
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I didn't get rich from it but it did have 63K downloads (powered possible tens of thousands of websites).
Enhancing Research Orchestration Capabilities at ORNL.pdfGlobus
Cross-facility research orchestration comes with ever-changing constraints regarding the availability and suitability of various compute and data resources. In short, a flexible data and processing fabric is needed to enable the dynamic redirection of data and compute tasks throughout the lifecycle of an experiment. In this talk, we illustrate how we easily leveraged Globus services to instrument the ACE research testbed at the Oak Ridge Leadership Computing Facility with flexible data and task orchestration capabilities.
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxrickgrimesss22
Discover the essential features to incorporate in your Winzo clone app to boost business growth, enhance user engagement, and drive revenue. Learn how to create a compelling gaming experience that stands out in the competitive market.
Do you want Software for your Business? Visit Deuglo
Deuglo has top Software Developers in India. They are experts in software development and help design and create custom Software solutions.
Deuglo follows seven steps methods for delivering their services to their customers. They called it the Software development life cycle process (SDLC).
Requirement — Collecting the Requirements is the first Phase in the SSLC process.
Feasibility Study — after completing the requirement process they move to the design phase.
Design — in this phase, they start designing the software.
Coding — when designing is completed, the developers start coding for the software.
Testing — in this phase when the coding of the software is done the testing team will start testing.
Installation — after completion of testing, the application opens to the live server and launches!
Maintenance — after completing the software development, customers start using the software.
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisGlobus
JASMIN is the UK’s high-performance data analysis platform for environmental science, operated by STFC on behalf of the UK Natural Environment Research Council (NERC). In addition to its role in hosting the CEDA Archive (NERC’s long-term repository for climate, atmospheric science & Earth observation data in the UK), JASMIN provides a collaborative platform to a community of around 2,000 scientists in the UK and beyond, providing nearly 400 environmental science projects with working space, compute resources and tools to facilitate their work. High-performance data transfer into and out of JASMIN has always been a key feature, with many scientists bringing model outputs from supercomputers elsewhere in the UK, to analyse against observational or other model data in the CEDA Archive. A growing number of JASMIN users are now realising the benefits of using the Globus service to provide reliable and efficient data movement and other tasks in this and other contexts. Further use cases involve long-distance (intercontinental) transfers to and from JASMIN, and collecting results from a mobile atmospheric radar system, pushing data to JASMIN via a lightweight Globus deployment. We provide details of how Globus fits into our current infrastructure, our experience of the recent migration to GCSv5.4, and of our interest in developing use of the wider ecosystem of Globus services for the benefit of our user community.
Essentials of Automations: The Art of Triggers and Actions in FMESafe Software
In this second installment of our Essentials of Automations webinar series, we’ll explore the landscape of triggers and actions, guiding you through the nuances of authoring and adapting workspaces for seamless automations. Gain an understanding of the full spectrum of triggers and actions available in FME, empowering you to enhance your workspaces for efficient automation.
We’ll kick things off by showcasing the most commonly used event-based triggers, introducing you to various automation workflows like manual triggers, schedules, directory watchers, and more. Plus, see how these elements play out in real scenarios.
Whether you’re tweaking your current setup or building from the ground up, this session will arm you with the tools and insights needed to transform your FME usage into a powerhouse of productivity. Join us to discover effective strategies that simplify complex processes, enhancing your productivity and transforming your data management practices with FME. Let’s turn complexity into clarity and make your workspaces work wonders!
Quarkus Hidden and Forbidden ExtensionsMax Andersen
Quarkus has a vast extension ecosystem and is known for its subsonic and subatomic feature set. Some of these features are not as well known, and some extensions are less talked about, but that does not make them less interesting - quite the opposite.
Come join this talk to see some tips and tricks for using Quarkus and some of the lesser known features, extensions and development techniques.
E-commerce Application Development Company.pdfHornet Dynamics
Your business can reach new heights with our assistance as we design solutions that are specifically appropriate for your goals and vision. Our eCommerce application solutions can digitally coordinate all retail operations processes to meet the demands of the marketplace while maintaining business continuity.
Large Language Models and the End of ProgrammingMatt Welsh
Talk by Matt Welsh at Craft Conference 2024 on the impact that Large Language Models will have on the future of software development. In this talk, I discuss the ways in which LLMs will impact the software industry, from replacing human software developers with AI, to replacing conventional software with models that perform reasoning, computation, and problem-solving.
OpenMetadata Community Meeting - 5th June 2024OpenMetadata
The OpenMetadata Community Meeting was held on June 5th, 2024. In this meeting, we discussed about the data quality capabilities that are integrated with the Incident Manager, providing a complete solution to handle your data observability needs. Watch the end-to-end demo of the data quality features.
* How to run your own data quality framework
* What is the performance impact of running data quality frameworks
* How to run the test cases in your own ETL pipelines
* How the Incident Manager is integrated
* Get notified with alerts when test cases fail
Watch the meeting recording here - https://www.youtube.com/watch?v=UbNOje0kf6E
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Globus
Large Language Models (LLMs) are currently the center of attention in the tech world, particularly for their potential to advance research. In this presentation, we'll explore a straightforward and effective method for quickly initiating inference runs on supercomputers using the vLLM tool with Globus Compute, specifically on the Polaris system at ALCF. We'll begin by briefly discussing the popularity and applications of LLMs in various fields. Following this, we will introduce the vLLM tool, and explain how it integrates with Globus Compute to efficiently manage LLM operations on Polaris. Attendees will learn the practical aspects of setting up and remotely triggering LLMs from local machines, focusing on ease of use and efficiency. This talk is ideal for researchers and practitioners looking to leverage the power of LLMs in their work, offering a clear guide to harnessing supercomputing resources for quick and effective LLM inference.
Unleash Unlimited Potential with One-Time Purchase
BoxLang is more than just a language; it's a community. By choosing a Visionary License, you're not just investing in your success, you're actively contributing to the ongoing development and support of BoxLang.
Atelier - Innover avec l’IA Générative et les graphes de connaissancesNeo4j
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Allez au-delà du battage médiatique autour de l’IA et découvrez des techniques pratiques pour utiliser l’IA de manière responsable à travers les données de votre organisation. Explorez comment utiliser les graphes de connaissances pour augmenter la précision, la transparence et la capacité d’explication dans les systèmes d’IA générative. Vous partirez avec une expérience pratique combinant les relations entre les données et les LLM pour apporter du contexte spécifique à votre domaine et améliorer votre raisonnement.
Amenez votre ordinateur portable et nous vous guiderons sur la mise en place de votre propre pile d’IA générative, en vous fournissant des exemples pratiques et codés pour démarrer en quelques minutes.
Code reviews are vital for ensuring good code quality. They serve as one of our last lines of defense against bugs and subpar code reaching production.
Yet, they often turn into annoying tasks riddled with frustration, hostility, unclear feedback and lack of standards. How can we improve this crucial process?
In this session we will cover:
- The Art of Effective Code Reviews
- Streamlining the Review Process
- Elevating Reviews with Automated Tools
By the end of this presentation, you'll have the knowledge on how to organize and improve your code review proces
Software Engineering, Software Consulting, Tech Lead, Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Transaction, Spring MVC, OpenShift Cloud Platform, Kafka, REST, SOAP, LLD & HLD.
First Steps with Globus Compute Multi-User EndpointsGlobus
In this presentation we will share our experiences around getting started with the Globus Compute multi-user endpoint. Working with the Pharmacology group at the University of Auckland, we have previously written an application using Globus Compute that can offload computationally expensive steps in the researcher's workflows, which they wish to manage from their familiar Windows environments, onto the NeSI (New Zealand eScience Infrastructure) cluster. Some of the challenges we have encountered were that each researcher had to set up and manage their own single-user globus compute endpoint and that the workloads had varying resource requirements (CPUs, memory and wall time) between different runs. We hope that the multi-user endpoint will help to address these challenges and share an update on our progress here.
First Steps with Globus Compute Multi-User Endpoints
Java Programming Projects
1. Java Projects
Submitted in partial fulfilment of the requirements for the degree of
Post Graduate Diploma in Information Technology
by
Vijayananda D Mohire
(Registration No.200508208)
Information Technology Department
Symbiosis Bhavan,
1065 B, Gokhale Cross
Road, Model Colony, Pune – 411016,
Maharashtra, India
(2007)
6. 6
Question 1
Create a class Computer that stores information about different types of
Computers available with the dealer. The information to be stored about a single
computer is,
- Company Name
- RAM size.
- Hard Disk Capacity.
- Processor Speed.
- Processor Make.
- Price .
- Quantity of the Computers.
This class contains following methods,
- Constructor method that assigns user input values to above
mentioned variables.
- main ( ) method that creates array of 4 objects of Computer
class and that takes input for all above details from the user and
calls method to check validity of Quantity and Price values.
If all values are valid then create the objects and display the details
for all 4 toys.
- Method that checks validity of quantity and price.
If the quantity is 0 or negative then method should throw user defined
exception with appropriate message and come out of program.
Similarly if the price is 0 or negative then it should throw user defined
exception with appropriate message and come out of program.
- Method that displays all details about a single instance of Computer in the
following Format.
Computer Name : IBM
RAM Size : 512 MB
Processor Make : Intel
Processor speed : 300
Quantity : 50
Total Price of Computers : 150,0000/-
7. 7
Answer 1
Code:
--------------------------------Computer.java----------------------------
package newcomputer;
import java.awt.Frame;
import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import newcomputer.LabelledItemPanel;
import newcomputer.CustomerDialog;
import newcomputer.CustomerData;
/**
* Define Computer class
* @author Vijayananda D Mohire
*/
public class Computer {
/** Class Variables to hold the Computer Name
*/
String Company_Name;
/** Class Variables to hold the RAM Size
*/
String RAM_size;
/** Class Variables to hold the Hard Disk Capacity
*/
String HardDisk_Capacity;
/** Class Variables to hold the processor speed
*/
String Processor_Speed;
/** Class Variables to hold the Processor Make
*/
String Processor_Make;
/** Class Variables to hold the price
8. 8
*/
String Price;
/** Class Variables to hold the Quantity of Computers
*/
String Quantity_of_the_Computers;
/** Creates a new instance of Computer */
public Computer() {
}
/**
* Overloaded Constructor,inputs the Dialog data
* @param ComputerData Holds Computer Data
*/
public Computer(CustomerData ComputerData) {
Company_Name = ComputerData.myCompanyName;
RAM_size = ComputerData.myRamSize ;
HardDisk_Capacity =ComputerData.myHardDiskCap;
Processor_Speed =ComputerData.myProcessorSpeed;
Processor_Make =ComputerData.myprocessorMake;
Price = ComputerData.myPrice;
Quantity_of_the_Computers =ComputerData.myQty;
}
/**
* Main
* @param args Input args
*/
public static void main(String[] args)
{
Computer [] Comps = new Computer[3]; // array to hold data after validation
int i=0;
CustomerDialog dialog4 = new CustomerDialog();
// Obtain the required 4 types of Computer details, use of do while loop
9. 9
do
{
CustomerDialog dialog = new CustomerDialog();
dialog.pack();
// Present it to a User1
dialog.show();
// TODO : Check why Dialog is not coming out when cancel is clicked
// Get the data or quit if user Cancel
if(!dialog.hasUserCancelled())
{
CustomerData customerData = dialog.getCustomerData();
try{
// Validate for each Computer instance entry and show error message if any.
boolean ValidFlag = dialog.isValidData();
if(ValidFlag)
{
//Pass on the Dialog data to Constructor input, create Computer class for that
Computer instance
Comps[i] = new Computer(customerData);
i++;
}
else {
Comps[0] = null;
Comps[1] = null;
Comps[2]= null;
System.exit(0);
}
}
catch(Exception err)
{
10. 10
dialog.ShowErr(err);
}
}
if(dialog.hasUserCancelled())
break;
}
while(i < 3);
if(i>=3)
PrintData(Comps, dialog4);
//Release object memory for garbage collection.
Comps[0] = null;
Comps[1] = null;
Comps[2]= null;
System.exit(0);
}
/**
* Prints the Computer details
* @param Comps Array of Computers
* @param dialog3 Pass the class variable
*/
public static void PrintData(Computer [] Comps,CustomerDialog dialog3 )
{
dialog3.PrintData(Comps);
}
}
-------------------------------CustomerData.java-------------------------------
package newcomputer;
/**
* This class is a simple data structure for holding Customer data.
* @author Vijayananda D Mohire
11. 11
*/
public class CustomerData
{
/** Class Variables to hold the Computer Name
*/
public String myCompanyName;
/** Class Variables to hold the RAM Size
*/
public String myRamSize;
/** Class Variables to hold the HArd Disk Capacity
*/
public String myHardDiskCap;
/** Class Variables to hold the processor speed
*/
public String myProcessorSpeed;
/** Class Variables to hold the Processor Make
*/
public String myprocessorMake;
/** Class Variables to hold the price
*/
public String myPrice;
/** Class Variables to hold the Quantity of Computers
*/
public String myQty;
}
---------------------------------CustomerDialog.java----------------------------------
package newcomputer;
/**
*
* @author Vijayananda.Mohire
*/
import java.awt.Frame;
import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
12. 12
import javax.swing.JTextArea;
import javax.swing.JTextField;
import newcomputer.LabelledItemPanel;
import javax.swing.*;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
/**
* This class demonstrates the usage of the StandardDialog class.
*/
public class CustomerDialog extends StandardDialog {
// Constants
/** Text Area Variables to hold the Company Name
*/
private JTextArea myCompanyName = new JTextArea(3, 20);
/** Text Field Variables to hold the RAMSize
*/
private JTextField myRAMSize = new JTextField();
/** Text Field Variables to hold the DiskCap acity
*/
private JTextField myHardDiskCap = new JTextField();
/** Text Field Variables to hold the ProcessorSpeed
*/
private JTextField myProcessorSpeed = new JTextField();
/** Text Field Variables to hold the ProcessorMake
*/
private JTextField myProcessorMake = new JTextField();
/** Text Field Variables to hold the Price
*/
private JTextField myPrice = new JTextField();
/** Text Field Variables to hold the Quantity
*/
private JTextField myQuantity = new JTextField();
/** LabelledItemPanel Variables to hold the labels
*/
private LabelledItemPanel myContentPane = new LabelledItemPanel();
// Methods
13. 13
/**
* This method is the default constructor.
*/
public CustomerDialog() {
init();
}
/**
* This method initialises the components on the panel.
*/
private void init() {
setTitle("Computers available at Dealer Vijay ");
myContentPane.setBorder(BorderFactory.createEtchedBorder());
myContentPane.addItem("Company Name", new
JScrollPane(myCompanyName,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));
myContentPane.addItem("RAM Size", myRAMSize);
myContentPane.addItem("Hard Disk Capacity", myHardDiskCap);
myContentPane.addItem("Processor Speed", myProcessorSpeed);
myContentPane.addItem("Processor Make", myProcessorMake);
myContentPane.addItem("Price", myPrice);
myContentPane.addItem("Quantity", myQuantity);
setContentPane(myContentPane);
}
/**
* This method gets the values of the panel entry fields.
* @returns an object containing the Customer data
* @return Returns Customer data
*/
public CustomerData getCustomerData() {
CustomerData customerData = new CustomerData();
customerData.myCompanyName = this.myCompanyName.getText();
customerData.myRamSize = myRAMSize.getText();
customerData.myHardDiskCap = myHardDiskCap.getText();
14. 14
customerData.myProcessorSpeed = myProcessorSpeed.getText();
customerData.myprocessorMake = myProcessorMake.getText();
customerData.myPrice = myPrice.getText();
customerData.myQty = myQuantity.getText();
return customerData;
}
/**
* This method sets the values of the panel entry fields.
*
* @param customerData The object containing the Customer data
*/
public void setCustomerData(CustomerData customerData) {
this.myCompanyName.setText(customerData.myCompanyName);
myRAMSize.setText(customerData.myRamSize);
myHardDiskCap.setText(customerData.myHardDiskCap);
myProcessorSpeed.setText(customerData.myProcessorSpeed);
myProcessorMake.setText(customerData.myprocessorMake);
myPrice.setText(customerData.myPrice);
myQuantity.setText(customerData.myQty);
}
/**
* This method checks that the data entered is valid.
* To be valid, the following must be met:
* <LI>Customer Code field is not blank
* <LI>Name field is not blank
* @return <code>true</code> if the data is valid, otherwise
* <code>false</code>
*/
protected boolean isValidData() {
int len =0;
char ch ;
if(myPrice.getText().equals(""))
{
JOptionPane.showMessageDialog(this,
17. 17
JOptionPane.showMessageDialog(this,
"Quantity cannot be negative",
"Negative Qty",
JOptionPane.WARNING_MESSAGE);
myRAMSize.requestFocus();
return false;
}
return true;
}
/**
* This method Prints each computer details.
*
* @param Comps The object containing the Customer data
*/
protected void PrintData(Computer [] Comps) {
for( int i=0;i< Comps.length;++i) // check for Upperbound
{
StringBuilder br = new StringBuilder();
br.append("n Company Name :");
br.append(Comps[i].Company_Name);
br.append("n RAM :");
br.append(Comps[i].RAM_size);
br.append(" n HDD:");
br.append(Comps[i].HardDisk_Capacity);
br.append("n Speed :");
br.append(Comps[i].Processor_Speed);
br.append("n Make:");
br.append(Comps[i].Processor_Make);
br.append("n Price: ");
br.append(Comps[i].Price);
br.append("n Qty :");
br.append(Comps[i].Quantity_of_the_Computers);
18. 18
JOptionPane.showMessageDialog(this,br.toString(),"Computer Output",
JOptionPane.INFORMATION_MESSAGE);
}
}
/**
* This method shows errors.
*
* @param err The variable containing the error details
*/
public void ShowErr(Exception err)
{
JOptionPane.showMessageDialog(this,
err,
"System Error",
JOptionPane.WARNING_MESSAGE);
}
}
-------------------------------------LabelledItemPanel.java---------------------------------
package newcomputer;
/**
*
* @author Vijayananda.Mohire
*/
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
* This class provides a panel for laying out labelled elements neatly with
* all the labels and elements aligned down the screen.
*
* @author Vijayananda.Mohire
*/
19. 19
public class LabelledItemPanel extends JPanel
{
/** The row to add the next labelled item to */
private int myNextItemRow = 0;
/**
* This method is the default constructor.
*/
public LabelledItemPanel()
{
init();
}
/**
* This method initialises the panel and layout manager.
*/
private void init()
{
setLayout(new GridBagLayout());
// Create a blank label to use as a vertical fill so that the
// label/item pairs are aligned to the top of the panel and are not
// grouped in the centre if the parent component is taller than
// the preferred size of the panel.
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 99;
constraints.insets = new Insets(10, 0, 0, 0);
constraints.weighty = 1.0;
constraints.fill = GridBagConstraints.VERTICAL;
JLabel verticalFillLabel = new JLabel();
add(verticalFillLabel, constraints);
}
/**
* This method adds a labelled item to the panel. The item is added to
* the row below the last item added.
*
20. 20
* @param labelText The label text for the item.
* @param item The item to be added.
*/
public void addItem(String labelText, JComponent item)
{
// Create the label and its constraints
JLabel label = new JLabel(labelText);
GridBagConstraints labelConstraints = new GridBagConstraints();
labelConstraints.gridx = 0;
labelConstraints.gridy = myNextItemRow;
labelConstraints.insets = new Insets(10, 10, 0, 0);
labelConstraints.anchor = GridBagConstraints.NORTHEAST;
labelConstraints.fill = GridBagConstraints.NONE;
add(label, labelConstraints);
// Add the component with its constraints
GridBagConstraints itemConstraints = new GridBagConstraints();
itemConstraints.gridx = 1;
itemConstraints.gridy = myNextItemRow;
itemConstraints.insets = new Insets(10, 10, 0, 10);
itemConstraints.weightx = 1.0;
itemConstraints.anchor = GridBagConstraints.WEST;
itemConstraints.fill = GridBagConstraints.HORIZONTAL;
add(item, itemConstraints);
myNextItemRow++;
}
}
-------------------------------StandardDialog.java--------------------------------
package newcomputer;
import java.awt.BorderLayout;
import java.awt.Container;
21. 21
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
/**
*This class provides a Custom Dailog for laying the controls
* @author Vijayananda.Mohire
*/
public class StandardDialog extends JDialog
{
// Constants
/** The spacing between components in pixels */
private static final int COMPONENT_SPACING = 10;
// Attributes
/** Flag indicating if the "Cancel" button was pressed to close dialog */
private boolean myIsDialogCancelled = true;
/** The content pane for holding user components */
private Container myUserContentPane;
// Methods
/**
* This method is the default constructor.
*/
public StandardDialog()
{
init();
}
22. 22
/**
* This method creates a StandardDialog with the given parent frame
* and title.
* *
* @param parent The parent frame for the dialog.
* @param title The title to display in the dialog.
*/
public StandardDialog(Frame parent, String title)
{
super(parent, title);
init();
}
/**
* This method creates a StandardDialog with the given parent dialog
* and title.
* *
* @param parent The parent dialog for the dialog.
* @param title The title to display in the dialog.
*/
public StandardDialog(Dialog parent, String title)
{
super(parent, title);
init();
}
/**
* This method sets up the default attributes of the dialog and
* the content pane.
*/
private void init()
{
setModal(true);
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
// Setup the internal content pane to hold the user content pane
// and the standard button panel
JPanel internalContentPane = new JPanel();
23. 23
internalContentPane.setLayout(
new BorderLayout(COMPONENT_SPACING, COMPONENT_SPACING));
internalContentPane.setBorder(
BorderFactory.createEmptyBorder(COMPONENT_SPACING,
COMPONENT_SPACING, COMPONENT_SPACING, COMPONENT_SPACING));
// Create the standard button panel with "Ok" and "Cancel"
Action okAction = new AbstractAction("Ok")
{
public void actionPerformed(ActionEvent actionEvent)
{
if(isValidData())
{
myIsDialogCancelled = false;
dispose();
}
}
};
Action cancelAction = new AbstractAction("Cancel")
{
public void actionPerformed(ActionEvent actionEvent)
{
myIsDialogCancelled = true;
dispose();
}
};
JPanel buttonPanel = new JPanel();
buttonPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
buttonPanel.add(new JButton(okAction));
buttonPanel.add(new JButton(cancelAction));
internalContentPane.add(buttonPanel, BorderLayout.SOUTH);
24. 24
// Initialise the user content pane with a JPanel
setContentPane(new JPanel(new BorderLayout()));
super.setContentPane(internalContentPane);
// Finally, add a listener for the window close button.
// Process this event the same as the "Cancel" button.
WindowAdapter windowAdapter = new WindowAdapter()
{
public void windowClosing(WindowEvent windowEvent)
{
myIsDialogCancelled = true;
dispose();
}
};
addWindowListener(windowAdapter);
}
/**
* This method gets the content pane for adding components.
* Components should not be added directly to the dialog.
* @return the content pane for the dialog.
*/
public Container getContentPane()
{
return myUserContentPane;
}
/**
* This method sets the content pane for adding components.
* Components should not be added directly to the dialog.
*
* @param contentPane The content pane for the dialog.
*/
public void setContentPane(Container contentPane)
{
25. 25
myUserContentPane = contentPane;
super.getContentPane().add(myUserContentPane, BorderLayout.CENTER);
}
/**
* This method returns true if the User cancelled
* the dialog otherwise false. The dialog is cancelled
* if the "Cancel" button is pressed or the "Close" window button is
* pressed, or the "Escape" key is pressed. In other words, if the
* User has caused the dialog to close by any method other than by
* pressing the "Ok" button, this method will return true.
* @return Returns bool value
*/
public boolean hasUserCancelled()
{
return myIsDialogCancelled;
}
/**
* This method is used to validate the current dialog box.
* @return a boolean indicating if the data is valid.
*true> indicates that all of the fields were validated
* correctly and false indicates the validation failed
*/
protected boolean isValidData()
{
return true;
}
}
-----------------------------------------------------------------------------------------------------
27. 27
Checks validity of quantity and price
Evaluator’s Comments if any:
Question 2
Write a Java program to create simple Calculator for 4 basic Math operations,
Addition, Subtraction, Multiplication and Division.
The calculator should simulate the look of handheld calculator containing the
following:
1. One textbox for displaying the input as well as output value.
2. Buttons for representing numbers from 0 to 9.
3. Buttons for representing mathematical operations .
Use suitable additional Swing components if required. Write proper code for
making this calculator operational.
Students are expected to handle the related events like button click.
28. 28
Answer 2
Code:
package calculator;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
/**
*
* @author Vijayananda.Mohire
*/
public class Calculator extends JFrame implements ActionListener{
// Variables
final int MAX_INPUT_LENGTH = 20;
final int INPUT_MODE = 0;
final int RESULT_MODE = 1;
final int ERROR_MODE = 2;
int displayMode;
29. 29
boolean clearOnNextDigit, percent;
double lastNumber;
String lastOperator;
private JMenu jmenuFile, jmenuHelp;
private JMenuItem jmenuitemExit, jmenuitemAbout;
private JLabel jlbOutput;
private JButton jbnButtons[];
private JPanel jplMaster, jplBackSpace, jplControl;
/*
* Font(String name, int style, int size)
Creates a new Font from the specified name, style and point size.
*/
Font f12 = new Font("Times New Roman", 0, 12);
Font f121 = new Font("Times New Roman", 1, 12);
// Constructor
public Calculator()
{
/* Set Up the JMenuBar.
* Have Provided All JMenu's with Mnemonics
* Have Provided some JMenuItem components with Keyboard
Accelerators
*/
jmenuFile = new JMenu("File");
jmenuFile.setFont(f121);
jmenuFile.setMnemonic(KeyEvent.VK_F);
jmenuitemExit = new JMenuItem("Exit");
jmenuitemExit.setFont(f12);
jmenuitemExit.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_X,ActionEvent.CTRL_MASK));
jmenuFile.add(jmenuitemExit);
jmenuHelp = new JMenu("Help");
jmenuHelp.setFont(f121);
jmenuHelp.setMnemonic(KeyEvent.VK_H);
30. 30
jmenuitemAbout = new JMenuItem("About Calculator");
jmenuitemAbout.setFont(f12);
jmenuHelp.add(jmenuitemAbout);
JMenuBar mb = new JMenuBar();
mb.add(jmenuFile);
mb.add(jmenuHelp);
setJMenuBar(mb);
//Set frame layout manager
setBackground(Color.gray);
jplMaster = new JPanel();
jlbOutput = new JLabel("0");
jlbOutput.setHorizontalTextPosition(JLabel.RIGHT);
jlbOutput.setBackground(Color.WHITE);
jlbOutput.setOpaque(true);
// Add components to frame
getContentPane().add(jlbOutput, BorderLayout.NORTH);
jbnButtons = new JButton[23];
// GridLayout(int rows, int cols, int hgap, int vgap)
JPanel jplButtons = new JPanel(); // container for Jbuttons
// Create numeric Jbuttons
for (int i=0; i<=9; i++)
{
// set each Jbutton label to the value of index
jbnButtons[i] = new JButton(String.valueOf(i));
}
// Create operator Jbuttons
jbnButtons[10] = new JButton("+/-");
jbnButtons[11] = new JButton(".");
jbnButtons[12] = new JButton("=");
jbnButtons[13] = new JButton("/");
31. 31
jbnButtons[14] = new JButton("*");
jbnButtons[15] = new JButton("-");
jbnButtons[16] = new JButton("+");
jbnButtons[17] = new JButton("sqrt");
jbnButtons[18] = new JButton("1/x");
jbnButtons[19] = new JButton("%");
jplBackSpace = new JPanel();
jplBackSpace.setLayout(new GridLayout(1, 1, 2, 2));
jbnButtons[20] = new JButton("Backspace");
jplBackSpace.add(jbnButtons[20]);
jplControl = new JPanel();
jplControl.setLayout(new GridLayout(1, 2, 2 ,2));
jbnButtons[21] = new JButton(" CE ");
jbnButtons[22] = new JButton("C");
jplControl.add(jbnButtons[21]);
jplControl.add(jbnButtons[22]);
// Setting all Numbered JButton's to Blue. The rest to Red
for (int i=0; i<jbnButtons.length; i++) {
jbnButtons[i].setFont(f12);
if (i<10)
jbnButtons[i].setForeground(Color.blue);
else
jbnButtons[i].setForeground(Color.red);
}
// Set panel layout manager for a 4 by 5 grid
jplButtons.setLayout(new GridLayout(4, 5, 2, 2));
//Add buttons to keypad panel starting at top left
// First row
for(int i=7; i<=9; i++) {
jplButtons.add(jbnButtons[i]);
32. 32
}
// add button / and sqrt
jplButtons.add(jbnButtons[13]);
jplButtons.add(jbnButtons[17]);
// Second row
for(int i=4; i<=6; i++)
{
jplButtons.add(jbnButtons[i]);
}
// add button * and x^2
jplButtons.add(jbnButtons[14]);
jplButtons.add(jbnButtons[18]);
// Third row
for( int i=1; i<=3; i++)
{
jplButtons.add(jbnButtons[i]);
}
//adds button - and %
jplButtons.add(jbnButtons[15]);
jplButtons.add(jbnButtons[19]);
//Fourth Row
// add 0, +/-, ., +, and =
jplButtons.add(jbnButtons[0]);
jplButtons.add(jbnButtons[10]);
jplButtons.add(jbnButtons[11]);
jplButtons.add(jbnButtons[16]);
jplButtons.add(jbnButtons[12]);
jplMaster.setLayout(new BorderLayout());
jplMaster.add(jplBackSpace, BorderLayout.WEST);
jplMaster.add(jplControl, BorderLayout.EAST);
jplMaster.add(jplButtons, BorderLayout.SOUTH);
// Add components to frame
getContentPane().add(jplMaster, BorderLayout.SOUTH);
33. 33
requestFocus();
//activate ActionListener
for (int i=0; i<jbnButtons.length; i++){
jbnButtons[i].addActionListener(this);
}
jmenuitemAbout.addActionListener(this);
jmenuitemExit.addActionListener(this);
clearAll();
//add WindowListener for closing frame and ending program
addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e)
{
System.exit(0);
}
}
);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} //End of Contructor Calculator
// Perform action
public void actionPerformed(ActionEvent e){
double result = 0;
if(e.getSource() == jmenuitemAbout){
JDialog dlgAbout = new CustomABOUTDialog(this, "About Java
Swing Calculator", true);
dlgAbout.setVisible(true);
}else if(e.getSource() == jmenuitemExit){
System.exit(0);
}
// Search for the button pressed until end of array or key found
for (int i=0; i<jbnButtons.length; i++)
{
if(e.getSource() == jbnButtons[i])
{
34. 34
switch(i)
{
case 0:
addDigitToDisplay(i);
break;
case 1:
addDigitToDisplay(i);
break;
case 2:
addDigitToDisplay(i);
break;
case 3:
addDigitToDisplay(i);
break;
case 4:
addDigitToDisplay(i);
break;
case 5:
addDigitToDisplay(i);
break;
case 6:
addDigitToDisplay(i);
break;
case 7:
addDigitToDisplay(i);
break;
case 8:
addDigitToDisplay(i);
break;
case 9:
addDigitToDisplay(i);
break;
35. 35
case 10: // +/-
processSignChange();
break;
case 11: // decimal point
addDecimalPoint();
break;
case 12: // =
processEquals();
break;
case 13: // divide
processOperator("/");
break;
case 14: // *
processOperator("*");
break;
case 15: // -
processOperator("-");
break;
case 16: // +
processOperator("+");
break;
case 17: // sqrt
if (displayMode != ERROR_MODE)
{
try
{
if (getDisplayString().indexOf("-") == 0)
displayError("Invalid input for function!");
result = Math.sqrt(getNumberInDisplay());
displayResult(result);
}
catch(Exception ex)
36. 36
{
displayError("Invalid input for
function!");
displayMode = ERROR_MODE;
}
}
break;
case 18: // 1/x
if (displayMode != ERROR_MODE){
try
{
if (getNumberInDisplay() == 0)
displayError("Cannot divide by zero!");
result = 1 / getNumberInDisplay();
displayResult(result);
}
catch(Exception ex){
displayError("Cannot divide by zero!");
displayMode = ERROR_MODE;
}
}
break;
case 19: // %
if (displayMode != ERROR_MODE){
try {
result = getNumberInDisplay() / 100;
displayResult(result);
}
catch(Exception ex){
displayError("Invalid input for function!");
displayMode = ERROR_MODE;
}
}
break;
case 20: // backspace
if (displayMode != ERROR_MODE){
37. 37
setDisplayString(getDisplayString().substring(0,
getDisplayString().length() - 1));
if (getDisplayString().length() < 1)
setDisplayString("0");
}
break;
case 21: // CE
clearExisting();
break;
case 22: // C
clearAll();
break;
}
}
}
}
void setDisplayString(String s){
jlbOutput.setText(s);
}
String getDisplayString (){
return jlbOutput.getText();
}
void addDigitToDisplay(int digit){
if (clearOnNextDigit)
setDisplayString("");
String inputString = getDisplayString();
if (inputString.indexOf("0") == 0){
inputString = inputString.substring(1);
}
if ((!inputString.equals("0") || digit > 0) && inputString.length() <
38. 38
MAX_INPUT_LENGTH){
setDisplayString(inputString + digit);
}
displayMode = INPUT_MODE;
clearOnNextDigit = false;
}
void addDecimalPoint(){
displayMode = INPUT_MODE;
if (clearOnNextDigit)
setDisplayString("");
String inputString = getDisplayString();
// If the input string already contains a decimal point, don't
// do anything to it.
if (inputString.indexOf(".") < 0)
setDisplayString(new String(inputString + "."));
}
void processSignChange(){
if (displayMode == INPUT_MODE)
{
String input = getDisplayString();
if (input.length() > 0 && !input.equals("0"))
{
if (input.indexOf("-") == 0)
setDisplayString(input.substring(1));
else
setDisplayString("-" + input);
}
}
else if (displayMode == RESULT_MODE)
{
double numberInDisplay = getNumberInDisplay();