May I point out the following errors after glancing at your code.
1. javax.servlet is included in J2EE platform rather than J2SE. There for the package does not exist on our J2SE platform.
2. any local variables in a method should not have accessing modifier. Only the data members, that is, the attributes are indicated by accessing modifiers, such as public, friendly, protected, and private.
3. the method checkCCDetails() should be static so that the main method may call it.
tong1 22 Posting Whiz
I have checked your code, done same kind of "proof reading". Good work. Well done.
The final code you have made is printed as follows. Please test your final code again. In software development, TESTING is PROVING/EVALUATING
import java.util.*;
public class P {
public static void main(String arg[]){
String names;
Scanner console=new Scanner(System.in); // establish a input channel
System.out.println("Input palindrome");
names=console.next();
int forward = 0;
int backward=names.length()-1;
boolean found=true;
while(forward<backward) {
if(names.charAt(forward)!=names.charAt(backward)){
found=false;
break;
}
forward++;
backward--;
}
if(found)
System.out.println(" palindrome");
else
System.out.println("not palindrome");
}
}
tong1 22 Posting Whiz
java.io
Class Console
is wonderful since it lets you to access the character-based console device, if any, associated with the current Java virtual machine.
Console console=System.console();
However, the
java.util
Class Scanner
is also goog since it may carry the same job.
Scanner in = new Scanner(System.in);
I have two comments.
1. to use methods as much as possible.
2. We should define the number as double since number could be in int, float, or double. And parseDouble accepts int as double
Please test the following code to see if there is any error.
import java.io.*;
class Input {
static double average(double d[]){ // the static method returns the mean value of the double array
double sum=0.0; // the place to store the totting-up values. It was zero at very beginning
for (int i=0; i<d.length; i++) // the loop to sum up the elements of the array d
sum += d[i];
return sum/d.length; // returns the average value
}
public static void main(String[] args) {
Console console=System.console(); // establish an input channel
int size=5; // input 5 numbers altogether
double number[]=new double[size]; // define a double array to store the 5 numbers
System.out.println("enter 5 numbers");
for(int i=0;i<size;i++)
number[i]=Double.parseDouble(console.readLine()); // input number could be in the format of int or double
double ave = average(number); // call the average method to obtain the mean value of the array number
System.out.println("The numbers smaller than the mean …
tong1 22 Posting Whiz
Wikipedia
http://en.wikipedia.org/wiki/Palindrome
says that “A palindrome is a word, phrase, number or other sequence of units that can be read the same way in either direction (the adjustment of punctuation and spaces between words is generally permitted). Composing literature in palindromes is an example of constrained writing.”. From this web site you may see different types of palindrome: characters, phrases, words, Molecular biology, and so on.
Using String instance we may determine if the string (or char array) is a palindrome as we do currently.
We may define a palindromw poet (sentence) in terms of a String array, as you initially intended.. For example:
"Step on no pets"
The following code I have modified is an example showing how to determine a palindrome. I have tested. It works. Please check the code to see if there is any error or to provide comments.
import java.util.*;
public class PPP {
public static void main(String args[]) {
String pal;
boolean found=false;
int forward;
int backward;
int i;
Scanner console = new Scanner(System.in); // create an input channel
System.out.println("Input palindrome");
pal=console.next();// receive a string (char array) via DOS window
forward = 0; // the head subscript
backward=pal.length()-1;// the tail subscript
while(forward<=backward){ /*when two subscripts did not meet, or just meet , i.e. did not cross */
if(pal.charAt(forward)!=pal.charAt(backward)){ /* if the corresponding chars are not the same */
found=true; //it is not a palindrome
break; // jump out of the while loop
}
forward++; // rightward …
tong1 22 Posting Whiz
You have almost done in addition to the String array.
The partial corrected code could be :
String pal;
boolean found=false;
int forward;
int backward;
int i;
Scanner console = new Scanner(System.in);
System.out.println("Input palindrome");
pal=console.next();
forward = 0;
backward=pal.length()-1;
while(forward<=backward)
{ if(pal.charAt(forward)!=pal.charAt(backward))
found=true;
forward++;
backward--;
break;
}
You may write in your own way, and complete your work.
I am looking forward to seeing your success.
Good luck
tong1 22 Posting Whiz
palindrome is a String instance or an array of char.
You ask the client to input one instance of String rather than an array of String.
Then you should process (work) on this instance to determine if it is polindrome or not. Therefore we are dealing with one instance of String only. We will compare the first char with the last char in the string.
tong1 22 Posting Whiz
In line 3 you should define a String instance pal instead of String array.
Therefore you have to modified the following code related to the pal.
The instance "console" is created by the constructor Scanner, so the lines 10-18 should be replace by one line:
Scanner console = new Scanner(System.in);
line 21: backward=pal.length-1;
should be altered into
backward=pal.length()-1;
since pal is a String instance and length() is a memger method.
in Line 33 shoud be:
if(!found)
I hope you will be able to complete your assignment successfully.
tong1 22 Posting Whiz
My way to fufill the staticstics task is implemented via different arrays. The final result is represented via a two dimension array. The column fields are indicated by different rooms while the rows name by different indexs. The final result is shown via the 2-D array:
indD/BARU|A005|A002|A001|BSK 2/3|A106/107|B202|B208/209|A 101|A 118|A 102|A 202|
2 13 0 0 0 0 0 0 0 0 0 0 0
4 20 54 40 35 29 25 0 10 54 50 30 19
The data represented in this format may be easily converted into the format indicated by shahreza
13 for D/BARU at index 2
54 for A005 at index 4
40 for A002 at index 4
35 for A001 at index 4
….
In order to define the 2D array we may have to create two arrays showing different rooms (Elements in String type) and index (Elements in int). In these array, the elements are requested to show up once only, that is, no duplication (repeated element) is allowed. Thus, I have defined two methods in terms of polymorphism.
public static String[] singleCheck(String [] a){..} and
public static int[] singleCheck(int [] a){…}
to complete the task: to create such two arrays of non-duplicated elements: s and ind.
When executing these methods, another two methods are called in the way of polymorphism.
public static int search(String st[], String s, int n){.}, and
static int search(int st[], int …
tong1 22 Posting Whiz
dylgod, Sorry. I modified your code in a way to output: 1*2*3*4*5. Can you modify your code so that the output will be: 5! = 5*4*3*2*1 = 120
import java.util.Scanner;
public class a4q1 {
public static void main(String args[])
{
Scanner input =new Scanner (System.in);
int num,factorial=1;
String s="1";
do
{
System.out.print("Please enter a number greater than or equal to 0.\n>>");
num =input.nextInt();
}
while (num <0);
for (int i =2; i <=num ; i++){
factorial*=i;
s += "*" + i;
}
System.out.println(num + "! = " + s + "=" + factorial);
}
}
tong1 22 Posting Whiz
The border control variable for the balls’ movement is obtained from the method getHeight() of the JComponent. It returns the current height of this component. I have debugged the code by adding println()s to show how the variables are changing and how the execution flow is going. I have also observed the movements of both balls.
It is found that when resizing the frame the first component still moves within its initial region while the region where the second ball moves has changed accordingly, resulted in such a scenario where the size of the first component (the first ball) remains unchanged while the size (height) of the second component (the second ball) changes accordingly. I have also made the drawing class as an inner class to see if there is any difference. The scenario remains the same. Does the phenomenon show an deficiency in resizing a frame in Java ?
tong1 22 Posting Whiz
I have made the following program which may read the text file "data.txt" (in the format structure you have defined at your first poster) and extract the columns of coordinate values x,y,z into a new file "myfile.txt". Both files are under the same folder as the code file. I hope this program may help you in your work.
/* The class FileUtil is originally defined by
* Java source code example
* http://www.javadb.com/write-lines-of-text-to-file-using-a-printwriter
* The method writeLinesToFile(...) has been modified.
*/
import java.io.*;
import java.util.*;
class FileUtil {
public void writeLinesToFile(String filename,
String[] linesToWrite,int length,
boolean appendToFile) {
PrintWriter pw = null;
try {
if (appendToFile) {
//If the file already exists, start writing at the end of it.
pw = new PrintWriter(new FileWriter(filename, true));
}
else {
pw = new PrintWriter(new FileWriter(filename));
//this is equal to:
//pw = new PrintWriter(new FileWriter(filename, false));
}
for (int i = 0; i < length; i++) {
pw.println(linesToWrite[i]);
}
pw.flush();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
//Close the PrintWriter
if (pw != null)
pw.close();
}
}
}
public class CoorToks0 {
private static StringBuffer buffer;
private static BufferedReader input=null;
private static String st[]= new String[1000];
public static void main(String args[]) {
int count = 0;
st[count++] = new String("x\ty\tz\0");
try{
input = new BufferedReader(
new FileReader( new File("data.txt") ) );
String text;
while ( ( text = input.readLine() ) != null ) {
StringTokenizer s = new StringTokenizer(text," ");
int counter=0;
String line="";
while(s.hasMoreTokens()) {
String ss …
tong1 22 Posting Whiz
AnyBody please help!!!
tong1 22 Posting Whiz
After one minute you add the second component which is the new ball with the x coordinate of 300. Then you should immediately ask the JFrame to re-arrange the layout via the following code:
frame.validate();
Therefore, you should insert the line of code into line 84 (shortly after the
catch(Exception ex){}
that is:
public static void main(String[] args) {
JFrame frame=new JFrame();
frame.setSize(800,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
try{
frame.add( new drawpanel(10) );
Thread.sleep(3000);
frame.add(new drawpanel(300));
}catch(Exception ex){}
frame.validate();
};
It is written in Java API 1.6 as follows.
"The validate method is used to cause a container to lay out its subcomponents again. It should be invoked when this container's subcomponents are modified (added to or removed from the container, or layout-related information changed) after the container has been displayed."
tong1 22 Posting Whiz
Thank you for your advise. I have modified the code accordingly.
import javax.swing.*;
public class speedofsound {
public static void main(String[] args) {
boolean pass=false;
while(true){
String medium=JOptionPane.showInputDialog(null, "Enter 1, 2 or 3 \nPick a medium : 1 for Air, 2 for Water and 3 for Steel");
char c = (medium.length()==1)? medium.charAt(0) : 4;
switch (c) {
case '1':
System.out.println ( " You have chosen Air" );
pass = true;
break;
case '2':
System.out.println ( " You have chosen Water");
pass = true;
break;
case '3':
System.out.println (" You have chosen Steel");
pass = true;
break;
default:
System.out.println ("Invalid choice: " + medium);
}
if (pass)
break;
}
System.out.println("Bey for now.");
}
}
tong1 22 Posting Whiz
You should establish your own Java developing environment at first to test your code step by step.
I have almostly always used the text book "Java How to program" by H.M.Deitel, P.J.Deitel for years.
tong1 22 Posting Whiz
As I understand, we may use JDBC to do the job for MS Access. Java provides SQL(including updating) methods.
tong1 22 Posting Whiz
Taking the advantage of the powerful function in DOS (or unix/lynix), the following code in Java could be useful for your data extracting. The original text data file is data.txt while the extracted data are stored in the text file:OutputData.dat
import java.io.*;
import java.util.*;
public class CoorToks1 {
private static BufferedReader input;
public static void main(String args[]) {
try{
input = new BufferedReader(
new FileReader( new File(args[0]) ) );
String text;
System.out.println("x\ty\tz");
while ( ( text = input.readLine() ) != null ) {
StringTokenizer s = new StringTokenizer(text," ");
int counter=0;
while(s.hasMoreTokens()) {
String ss = s.nextToken();
counter++;
if (counter >6 && counter <10)
System.out.print(ss + "\t");
}
System.out.println();
}
}catch( IOException ioException ) {}
}
}
The command on DOS is shown as follows.
java CoorToks1 data.txt >OutputData.dat
tong1 22 Posting Whiz
The error message shows:
(1) in line 9 you call a non-existing constructor of 2 arguments. As your teacher requests, you should define "a constructor that creates a rectangle with the specified width and height" only. You did not do so. Instead you have defined a constructor with 3 arguments:width,height, and color.
(1) Similarly in line 10 you call the non-existing constructor with 2 double parameters again.
What you should do is to define (supplement) the constructor that creates a rectangle with the specified width and height only for the class Rectangle.
tong1 22 Posting Whiz
In your program the last curly brace is missing, resulting in a compiling error.
If you want to print the total number of the elements that are divisible by 5, you have to create a counter to do the job: int counter =0. When scanning the array, if an element divisible by 5 is found you have to make counter one increment: counter++. Finally you may print the value of the counter.
tong1 22 Posting Whiz
We have no need to print out the length of the array. The only data printed out in your program are the length of the array rather than the elements divisible by 5. You have no code that printins any elements in the array.
In line 8 I have replaced your “divisible.length” with “divisible” so that your program may print out all the elements divisible by 5.
The modified program is written as follows:
public class divisible {
public static void main(String args[]) {
int[] divisible;
divisible = new int[] {4,9,25,144};
for (int i=0; i<divisible.length; i++)
if (divisible[i]%5== 0)
System.out.println(divisible[i] + " ");
}
}
tong1 22 Posting Whiz
/* Could be written in the following way */
public class divisible {
public static void main(String args[]) {
int[] divisible;
int toTal=0;
divisible = new int[] {4,9,25,144};
System.out.println("The elements divisible by 5 are printed as follows:");
for (int i=0; i<divisible.length; i++)
if (divisible[i]%5== 0){
toTal++;
System.out.print(divisible[i] + " ");
}
System.out.println("\nThe total number of the elements divisible by 5 is: " + toTal);
}
}
The output is shown as follows:
The elements divisible by 5 are printed as follows:
25
The total number of the elements divisible by 5 is: 1
tong1 22 Posting Whiz
Dear khRiztin,
I do not know how to help you.
I downloaded and extracted it successfully. The size of Scribble.java is 33kb (1263 lines code). The size of the Applet is width="650" height="650".
Yes, it is a zipped file. after unzipping you should put the scribble.html and Scribble.java in the same folder.
On DOS wondow,
First command:
javac Scribble.java
It will compile it with no trouble.
Then, the second command:
appletviewer scribble.html
or use a browser to open the scribble.html
You will see the outcome, and run the applet.
tong1 22 Posting Whiz
The following code may
(1) extract the coordinate values in the 3 float columns in the file "data.txt" under the same folder, and
(2) print the extracted float data only on DOS window.
import java.io.*;
import java.util.*;
public class CoorToks {
public static StringBuffer buffer;
public static BufferedReader input;
public static void main(String args[]) {
try{
input = new BufferedReader(
new FileReader( new File("data.txt") ) );
String text;
while ( ( text = input.readLine() ) != null ) {
StringTokenizer s = new StringTokenizer(text," ");
int counter=0;
while(s.hasMoreTokens()) {
String ss = s.nextToken();
counter++;
if (counter >6 && counter <10)
System.out.print(ss + " ");
}
System.out.println();
}
}catch( IOException ioException ) {}
}
}
tong1 22 Posting Whiz
You may down load the Java Applet program Scribble.java
http://www.partow.net/projects/jpaintbrush/index.html
It works.
It is pointed out at the web site:
Free use of the Java Paint Brush is permitted under the guidelines and in accordance with the most current version of the "Common Public License."
tong1 22 Posting Whiz
Java Applet has a security rule:
To open,read,write a file in client computer is not allowed.
This is a security measure.
Java security issue can be found in the following web site:
http://groups.csail.mit.edu/mac/users/jbank/javapaper/javapaper.html
tong1 22 Posting Whiz
The nested loop can be written as follows:
import java.lang.*;
public class NumberPrinted{
public static void main(String args[]){
int n = Integer.parseInt(args[0]);
int number = 10;
for (int i = 0; i< n; i++){
for (int j=0; j<10; j++)
System.out.printf("%4d", number++);
System.out.println();
}
}
}
Using C-style "printf("%4d", a)" to print an number 'a' has the advantage in easily controlling the spaces.
On DOS window the following output may be shown:
java NumberPrinted 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49
50 51 52 53 54 55 56 57 58 59
60 61 62 63 64 65 66 67 68 69
70 71 72 73 74 75 76 77 78 79
80 81 82 83 84 85 86 87 88 89
90 91 92 93 94 95 96 97 98 99
tong1 22 Posting Whiz
Dear WargRider, NormR1, and jjhames,
I should thank very much indeed for your comments. I hope the following post, that is the answer to my first post, is helpful for jjhames.
1. How to create an int array with 10 random elements varying between 0 to 255, i.e. [0-255].
We have the static method random() of the class Math in the folder java.lang.
As shown in Java API 1.6
public static double random() which
returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range.
Hence, using the following code we may have the above-mensioned int array.
int d[] = new int[n];
for (int i=0; i<n; i++)
d[i] = (int)(Math.random()*256);
It is pointed out that the compulsive conversion (coercion) into int type will produce 255 at most when the random double value is multiplied by 256. In other word, the highest int value obtained is 255 while the lowest int value 0.
2. How to sort this array in descending order via a primitive “bubble_sort”.
Table 1. The changes in the int array after each run.
The altered array after each run
Randomly created int array 129 198 149 232 94 33 199 137 94 95
The 1st run 198 149 232 129 94 199 137 94 95 33
The 2nd run 198 232 149 129 …
tong1 22 Posting Whiz
NormR1, thank you very much for your advise.
The code with explanation is written as follows.
public class MyPoint {
private int x,y;
/* The no-argument constructor creates the instance at the coordinate origin.*/
public MyPoint(){
x=0; // assign zero to the attribute x .
y=0; // assign zero to the attribute y.
}
/*The following constructor constructs a point with specified coordinates. */
public MyPoint(int x, int y){
this.x=x;
/* x is a local variable (an argument of the constructor method) while this.x represents the attribute x of the given instance. “this” is a handle representing the given instance while ‘.’ is the handle operator */
this.y=y;
/* y is another local variable (the second argument of the constructor method) while this.x is the attribute y of the given instance. “this” is a handle representing the given instance while ‘.’ is the handle operator */
}
/* now Two get methods for data fields x and y, respectively. */
.....
}
tong1 22 Posting Whiz
/* Useful StringTokenizer */
import java.util.*;
import javax.swing.*;
public class Date0 {
public static void main(String args[]) {
String text= JOptionPane.showInputDialog(null,"Type in the data in the format'02/14/2010'");
int ymd[] = new int[3];
StringTokenizer s = new StringTokenizer(text,"/");
for (int i=0; s.hasMoreTokens(); i++)
ymd[i] = Integer.parseInt(s.nextToken());
text ="Your input is " + ymd[2] + " year " + ymd[0] + " month " + ymd[1] + " day";
JOptionPane.showMessageDialog(null,text,"Welcome to DaniWeb",
JOptionPane.INFORMATION_MESSAGE);
}
}
tong1 22 Posting Whiz
public class MyPoint {
private int x,y;
public MyPoint(){
x=0;
y=0;
}
public MyPoint(int x, int y){
this.x=x;
this.y=y;
}
/* now Two get methods for data fields x and y, respectively. */
.....
}
tong1 22 Posting Whiz
Dear NormR, you are right. The program has been modified accordingly as follows:
import javax.swing.*;
public class speedofsound {
public static void main(String[] args) {
String medium=JOptionPane.showInputDialog(null, "Enter 1, 2 or 3 \nPick a medium : 1 for Air, 2 for Water and 3 for Steel");
char c = (medium.length()==1)? medium.charAt(0) : 4;
switch (c) {
case '1':
System.out.println ( " You have chosen Air" ); break;
case '2':
System.out.println ( " You have chosen Water");break;
case '3':
System.out.println (" You have chosen Steel");break;
default:
System.out.println ("Invalid choice: " + medium);
}
}
}
tong1 22 Posting Whiz
An e-book:
Concepts of Programming Languages (7th Edition) by Robert W. Sebesta
http://www.ebookee.net/Concepts-of-Programming-Languages-7th-Edition-_35213.html
is also helpful.
tong1 22 Posting Whiz
/* The following program demonstrates how to guard
* a non-negative input in int.
* If the input is in int and also greater than -1, the valid input
* will be shown on DOS window and program terminates.
* If client inputs an value in non-int or an negative value in int, the program will
* ask the user for re-input.
**/
import java.util.*;
public class Input {
public static void main(String args[]){
int n=0;
Scanner in = new Scanner(System.in);
while(true){
try{
System.out.println("Input a non-negative integer:");
n = in.nextInt();
}catch(InputMismatchException e){
System.out.println("Your input is mismatched.");
in.next();
continue;
}
if (n<0){
System.out.println("You negative value is not valid.");
continue;
}
break;
}
System.out.printf("Your input is %d\n", n);
}
}
The output in DOS:
Input a non-negative integer:
3r3
Your input is mismatched.
Input a non-negative integer:
3.1415
Your input is mismatched.
Input a non-negative integer:
35
Your input is 35
tong1 22 Posting Whiz
The method showInputDialog used here returns an instance of the class String.
The input "123" is not valid.
The code is modified accordingly as follows:
import javax.swing.*;
public class speedofsound {
public static void main(String[] args) {
String input;
String medium;
medium= new String (JOptionPane.showInputDialog(null, "Enter 1, 2 or 3 \nPick a medium : 1 for Air, 2 for Water and 3 for Steel"));
char c = (medium.length()==1)? medium.charAt(0) : 4;
switch (c) {
case '1':
System.out.println ( " You have chosen Air" ); break;
case '2':
System.out.println ( " You have chosen Water");break;
case '3':
System.out.println (" You have chosen Steel");break;
default:
System.out.println ("Invalid choice");
}
}
}
tong1 22 Posting Whiz
Dear Jon,
Thank you very much for your comments.
Is the following modified program making sense in terms of your comments?
-----------------------
import javax.swing.*;
public class speedofsound {
public static void main(String[] args) {
String input;
String medium;
medium= new String (JOptionPane.showInputDialog(null, "Enter 1, 2 or 3 \nPick a medium : 1 for Air, 2 for Water and 3 for Steel"));
char c = medium.charAt(0);
switch (c) {
case '1':
System.out.println ( " You have chosen Air" ); break;
case '2':
System.out.println ( " You have chosen Water");break;
case '3':
System.out.println (" You have chosen Steel");break;
default:
System.out.println ("Invalid choice");
}
}
}
tong1 22 Posting Whiz
import java.io.*;
import java.util.*;
public class Profile {
public static void main (String [] args) {
String name="",user="",pass="",add="";
int ch=0, con=0;
Scanner scn = new Scanner(System.in);
while(true){
System.out.println("Enter your profile\n");
System.out.print("Name:");
name = scn.nextLine();
System.out.print("Username:");
user = scn.nextLine();
System.out.print("Address:");
pass = scn.nextLine();
while(true){ // only numeric allowed
try{
System.out.print("Mobile:");
con = scn.nextInt();
}catch ( InputMismatchException e ){
scn.nextLine();
System.out.println("You enter nos. Please retry again.\n" );
continue;
}
break;
}
System.out.println("");
System.out.println("Press 0 to redo info.");
System.out.println("Press 1 to save.");
System.out.println("Press 2 to quit w/o saving.");
System.out.print("Select a choice:");
ch = scn.nextInt(); //Read in user prompt (0, 1 or 2)
switch(ch){
case 0:
System.out.println("Editing...");
continue;
case 1:
String info= "\n"+name+";"+user+";"+add+";"+con;
try {
PrintWriter out = new PrintWriter(new FileWriter("Profile.txt",true));
out.write(info);
out.close();
System.out.println("Tks for registering.");
}catch (IOException e) { };
System.exit(0);
case 2:
System.out.println("Tks for registering.");
System.exit(0);
}
}
}
}
tong1 22 Posting Whiz
The following program shows the String instances are converted into different values in boolean, double, and int.
import java.lang.*;
public class Input{
public static void main(String args[]){
if (Boolean.parseBoolean(args[0])) {
System.out.println("The first argument is in boolean: " + Boolean.parseBoolean(args[0]));
System.out.println("The second argument is in double: " + Double.parseDouble(args[1]));
System.out.println("The third argument is in int: " + Integer.parseInt(args[2]));
}
}
}
The executing command:
Java Input true 3.1415 255
The output:
The first argument is in boolean: true
The second argument is in double: 3.1415
The third argument is in int: 255
Also see “http://www.daniweb.com/forums/thread299093.html” where the client is asked to input an integer as the size of an array in int.
-------------------
/* The following program is written to receive a size of an int array that
* assigned by random values varying between 0 to 255 [0-255].
* Then the array will be sorted in ascending order by the bubble method.
*/
import java.lang.*;
public class MainExample1 {
static void bubble_sort(int a[]){
int i,j,t, n=a.length;
boolean change;
for(i=n-1,change=true; i>0 && change ;--i)
{
change=false;
for(j=0;j<i;++j)
if(a[j]<a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
change=true;
}
}
}
public static void main(String args[]){
int n= Integer.parseInt(args[0]);
int d[] = new int[n];
for (int i=0; i<n; i++)
…
tong1 22 Posting Whiz
Thank you very much indeed for your comments.
I have created a driver program accordingly as follows.
import java.math.*;
class FactorialCalculator {
public static BigInteger compute(int num) {
if(num < 0) {
throw new IllegalArgumentException("negative number passed for factorial computation");
}
if(num < 2) {
return BigInteger.ONE;
}
BigInteger factorial = BigInteger.ONE;
while(num > 1) {
factorial = factorial.multiply(BigInteger.valueOf(num--));
}
return factorial;
}
public static void main(String args[]){
for (int i=2; i<25;i++)
System.out.println("The " + i + " ! is: "
+ compute(i));
}
}
And the following output is obtained:
The 2 ! is: 2
The 3 ! is: 6
The 4 ! is: 24
The 5 ! is: 120
The 6 ! is: 720
The 7 ! is: 5040
The 8 ! is: 40320
The 9 ! is: 362880
The 10 ! is: 3628800
The 11 ! is: 39916800
The 12 ! is: 479001600
The 13 ! is: 6227020800
The 14 ! is: 87178291200
The 15 ! is: 1307674368000
The 16 ! is: 20922789888000
The 17 ! is: 355687428096000
The 18 ! is: 6402373705728000
The 19 ! is: 121645100408832000
The 20 ! is: 2432902008176640000
The 21 ! is: 51090942171709440000
The 22 ! is: 1124000727777607680000
The 23 ! is: 25852016738884976640000
The 24 ! is: 620448401733239439360000
tong1 22 Posting Whiz
An identifier is a symbol that establishes the identity of the one bearing it.
http://dict.cn/identifier
It could also be a name of a constant.
tong1 22 Posting Whiz
As far as I know,
2. On DOS, the command “java” calls the main method only to interpret the code in the main method. When the main method is terminated (executed completely), no return value is requested. Hence the void is always requested.
3. Any arguments received when starting an interpretation of a Java program can be stored only in terms of the instances of the class String. The value of any other types, such as int, doudle, and boolean, can be created via parsing the String instances accordingly. Therefore, only the String instance is appropriated for the type of elements of the array.
tong1 22 Posting Whiz
Should we start with one bubble sort?
Can you explain why
1. the usefulness of the boolean flag "change" ?
2. why the upper limit of the embedded loop ( “ for(j=0;j<i;++j) ” )is i rather than n?
You may figure out the descending sort and other sorting methods, such as insertion and selection.
/* The following program is written to receive a size of an int array that
* assigned by random values varying between 0 to 255 [0-255].
* Then the array will be sorted in ascending order by the bubble method.
*/
import java.lang.*;
public class MainExample1 {
static void bubble_sort(int a[]){
int i,j,t, n=a.length;
boolean change;
for(i=n-1,change=true; i>0 && change ;--i)
{
change=false;
for(j=0;j<i;++j)
if(a[j]<a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
change=true;
}
}
}
public static void main(String args[]){
int n= Integer.parseInt(args[0]);
int d[] = new int[n];
for (int i=0; i<n; i++)
d[i] = (int)(Math.random()*256);
bubble_sort(d);
for (int i=0; i<d.length;i++)
System.out.print(d[i] + " ");
System.out.println();
}
}
tong1 22 Posting Whiz
- The difference is in the name of the classes.
The Java language defines the signature (format) of the only main method in a class as
public static void main(String args[]) {} meanwhile
the name of the array of String may be given differently, e.g.
public static void main(String a[]) {},
public static void main(String bargs[]) {},
public static void main(String arg[]) {},
….
The following program is taken as an example:public class MainExample1 {
public static void main(String a[]){
for(int i=0;i<a.length;i++)
System.out.println("The " + (i+1) + "arguemnt: " + a[i]);
}
}
The String array a is used to receive String arguments when the java program is started to execute in the following command on DOS:
Java MainExample1 Dani Web Web Master
The following output on DOS is shown accordingly:
The 1arguemnt: Dani
The 2arguemnt: Web
The 3arguemnt: DaniWeb
The 4arguemnt: Master
tong1 22 Posting Whiz
1. Robert W. Sevesta (2002, Concepts of programming languages, 5th edition, page 107 ) pointed out that “ a token of a language is a category of its lexemes.”
“Formal descriptions of the syntax of programming languages, for simplicity’s sake, often do not include descriptions of the lowest-level syntactic units. These small units are called lexemes.”
2. When the class Scanner in java.util.* is used, you may create a instance:
Scanner in = new Scanner(System.in);
Then using the instance in :
int n = in.nextInt();
To receive an input in int.
When the input string is not a int string, e.g. “44k4”, an InputMissmatchException is thrown:
(see the thread” How to guard the input effectively”
http://www.daniweb.com/forums/thread299076.html
);
public static void main(String args[]){
int n=0;
Scanner in = new Scanner(System.in);
while(true){
try{
System.out.println("Input a non-negative integer:");
n = in.nextInt();
}catch(InputMismatchException e){
System.out.println("Your input is mismatched.");
in.next();
continue;
}
if (n<0){
System.out.println("You negative value is not valid.");
continue;
}
break;
}
System.out.printf("Your input is %d\n", factorial(n));
}
}
tong1 22 Posting Whiz
If we use the long type to hold the factorial values, the output will be:
Factorial of 2 : 2
Factorial of 3 : 6
Factorial of 4 : 24
Factorial of 5 : 120
Factorial of 6 : 720
Factorial of 7 : 5040
Factorial of 8 : 40320
Factorial of 9 : 362880
Factorial of 10 : 3628800
Factorial of 11 : 39916800
Factorial of 12 : 479001600
Factorial of 13 : 6227020800
Factorial of 14 : 87178291200
Factorial of 15 : 1307674368000
Factorial of 16 : 20922789888000
Factorial of 17 : 355687428096000
Factorial of 18 : 6402373705728000
Factorial of 19 : 121645100408832000
Factorial of 20 : 2432902008176640000
Factorial of 21 : -4249290049419214848
The Long.MAX_VALUE is 9223372036854775807
which means, long type may hold the value of Factorial of 20 at most. It cannot hold the Factorial of 21.
tong1 22 Posting Whiz
Thank you for your attention. My intention is to remind programmer about the Integer.MAX_VALUE, i.e. the limits in representing a value in Java. I belive the above code is correct as you agree. This means that the method is not valid if it returns -1 when n>12.
The factorial of 12 is 479001600
The factorial if 13 is 6227020800
if we use int to represent the result for 13, it would be 1932053504 which is wrong.
tong1 22 Posting Whiz
/* The following programs are written to guard the input. The input is requested as an non-negative integer.Is there other method to do so? */
/* Operation on DOS window: "PositiveInt1" receives a positive integer only. */
import java.util.*;
public class PositiveInt1{
static int factorial(int n){
int fac=1;
if ((n<0) || (n>12))
return -1;
for (int i=2; i<=n;i++)
fac *=i;
return fac;
}
public static void main(String args[]){
int n=0;
Scanner in = new Scanner(System.in);
while(true){
try{
System.out.println("Input a non-negative integer:");
n = in.nextInt();
}catch(InputMismatchException e){
System.out.println("Your input is mismatched.");
in.next();
continue;
}
if (n<0){
System.out.println("You negative value is not valid.");
continue;
}
break;
}
System.out.printf("Your input is %d\n", factorial(n));
}
}
---------------------
/* via JOpationPane */
import javax.swing.*;
public class PositiveInt{
static class NonNegativeException extends Exception{
public NonNegativeException(String msg){
super(msg);
}
}
static void show(int x)throws NonNegativeException {
if (x<0)
throw new NonNegativeException("Negative integer is not valid.");
}
public static void main(String args[]){
int n=0;
while(true){
try{
String s=JOptionPane.showInputDialog(null,"Input a positive integer:");
n = Integer.parseInt(s);
show(n);
}catch(NumberFormatException e){
System.out.println();
JOptionPane.showMessageDialog( null, "Your input is mismatched. Try again.", "Warning ",JOptionPane.WARNING_MESSAGE);
continue;
}catch(NonNegativeException e){
JOptionPane.showMessageDialog( null, e.getMessage(), "Warning ",JOptionPane.WARNING_MESSAGE);
continue;
}
break;
}
JOptionPane.showMessageDialog(null,"Your input: "+n,"Welcome to DANIWEB", JOptionPane.INFORMATION_MESSAGE);
}
}
tong1 22 Posting Whiz
/* In the following method, why the factorial goes wrong when n>12 ? */
static int factorial(int n){
int fac=1;
if ((n<0) || (n>12))
return -1;
for (int i=2; i<=n;i++)
fac *=i;
return fac;
}