tong1 22 Posting Whiz

vnaa,
In stead of reversing a string your ploblem is to write a series of sub-strings starting from the last character using the member method substring in the class String:

String s="Hello";
	for (int i=1;i<s.length()+1;i++)
	System.out.print(s.substring(s.length()-i) + ", ");
vnaa commented: Excellent solution +0
tong1 22 Posting Whiz

The main method should be written as follows:

public static void main(String args[])throws IOException
{
sp obj=new sp();
obj.takenum();obj.showresult();
}
tong1 22 Posting Whiz

The difference between two adjacent numbers in the series of numbers increases one each time. Therefore, one has to update the difference by one increment each time:

difference++

Hence one may calculate the next number by the following code:

num +=difference++;

Therefore the for each loop could be written as follows:

int difference=0, num=1;
   for(int j= 0; j<22; j++){
   num +=difference++; 
   System.out.print(num + " ");
		}
tong1 22 Posting Whiz

Lxyslckr,
As masijade indicates, one should use the second version.
May I indicate some errors in the second version?
line 1 should be
if (y >= 1980 && y<= 2012)
line 3 should be
year = y;
line 8 should be
year = 2010;

tong1 22 Posting Whiz

Note that the instructor asks to verify the value provided for "year" is at least 1908 and at most 2012, hence the code should be:

if (y >= 1980 && y<= 2012)
year=y;
else
year=2010;

The following code by using ternary operator is also valid:

year = ( y>=1980 && y<=2012)? y : 2010;
tong1 22 Posting Whiz

(1)Insert the line of code before line 58 to check the two indexes' values: tosFloat and TosInt:

System.out.println("tosFloat: " + first.tosFloat + " ,tosInt: " + first.tosInt);

(2) the values of the two indexes before the run time error message is issued thus are found:
tosFloat: -1 ,tosInt: 2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at Stack1.main(Stack1.java:59)
(3) Therefore, it is easy to realize that
the first for each loop pushes 3 float values into the Stack first so that the first.tosFloat becomes 2; then the second for each loop pops them all out so that the first.tosFloat becomes -1; the third for each loop has nothing to do with first.tosFloat; and the fourth for loop has finally started to execute the code:

first.StackArrayF[first.tosFloat]=first.StackArrayI[first.tosInt];

where the first.tosFloat is -1, causing an ArrayIndexOutOfBoundsException.

tong1 22 Posting Whiz

Xufyan, you may have two control indexes, such as int tosInt=-1,tosFloat=-1 to manage these two indipendent arrays of different data type which store different data. It is a common sense.

tong1 22 Posting Whiz

(1) write a static method where the essential code has been already made as you posted:

static char letterToInt(char c) {
     switch (c)
			{
			case 'A': case 'a': case 'B': case 'b':
			case 'C': case 'c': return '2';  
/* no "break" is needed becasue we have had the "return" */
			case 'D': case 'd': case 'E': case 'e':
			case 'F': case 'f': return '3';
...
return '0'

(2) the main() method will call the static char letterToInt(char c) to conver each English letter into digital character:

...
	System.out.println("Enter phone number expressed in letters: ");		
         str = console.next();

	for (int i=0;i<str.length();i++)
	System.out.print(letterToInt(str.charAt(i)));  // to convert each English letter into digital character and print it
	System.out.println();

(3) Why the English letters can not refer to the digital characters '0' and '1'?

Xufyan commented: nice - Xufyan +0
tong1 22 Posting Whiz

Based on your description I would assume that the method drawRect(int x0,int y0,int width, int length) has a time complxity O(n) since the plot shows

"an increasing linear trend at first".

The method must limit the width and length, that is, if either the width or the length reaches the maximum value (upper limit) it will remain unchanged. That's why

"the plot finally remains constant...".

The plot shows an real observation.

" then decrease rapidly"

may be due to some optimization of the operation when it is feasible.

tong1 22 Posting Whiz

The following code shows an idea on how to have only the figures after the decimal point are printed after the integer part is removed. Please rewording my comments if it is necessary.

public class Prinf{
	static double decimal(double d){ //a method to return the value after the decimal point
	int dd = (int)d; // cast into the int data type so that only the integer part is stored in dd
	d -=dd; // the value after the decimal point is finally left after the original value of the argument d minus the integer part dd.
	return d; // return the residual value, i.e. the value after the decimal point
	}
	public static void main(String args[]){
         double d = 6.328941; // for example, we have a double variable of a value with 6 figures after the decimal point.
         System.out.printf("%8.6f\n",decimal(d));  // The 6 figures after the decimal point are printed after the integer part is removed.
	}
}
tux4life commented: Good approach, I'd also have done this. :) +8
tong1 22 Posting Whiz

A further development of extemer's program leads to the following table showing the furture values of one thousand dolloars investment calculated based on compound interest: a(t) = (1 + i)^t where i is rate while t the number of years

import java.text.DecimalFormat;
import javax.swing.*;
import javax.swing.JTextArea.*;

   class TextAreaDemoB {
     public static void main(String[] args){

     double amount,
           p=1000.0,
           rate=.025;

     DecimalFormat pre= new  DecimalFormat("0.00");
     DecimalFormat preRate= new DecimalFormat("0.000");
     JTextArea out= new JTextArea(0,0);

     out.append(" year, rate->\t");
     for (int j=0;j<10;j++)
     out.append(preRate.format(rate+j*0.025)+ "\t");
     out.append("\n");

     for(int year=1; year<=10; year++) {
     	out.append( year + "\t");
     	for (int j=0; j<10; j++){
     amount=p * Math.pow( 1.0 + (rate+j*0.025) , year );
 	 out.append(pre.format( amount )+ "\t" );
 	 }
 	 out.append("\n");
 	 }

    JOptionPane.showMessageDialog(null,out,"Future values of $1000 investment with various numbers of years and rates",JOptionPane.INFORMATION_MESSAGE);
	}
}
tong1 22 Posting Whiz

masijade , Thank you for your remind.
I have added code to show the difference between two kinds of interests: simple and accumulated.
I hope gudads will compare the output format between his and mine to make further decision about changes in the code for his output, perhaps also show difference between two kinds of interests if there is.

tong1 22 Posting Whiz

Since the interpunction is not a word shoud we indicate some delimiters as well so that, e.g. "How are you ?" will be made of 3 words instead of 4.

StringTokenizer sT = new StringTokenizer(myString, " ,.!?'\"");
tux4life commented: Good :) +8
tong1 22 Posting Whiz

A nested while loop may do the job.
Here is the code:

import java.util.*;
import java.util.StringTokenizer;

public class AutoTextSumm {
  public static void main(String[] args) {
	String s1,s2;
        String sDelim = ".?!";
	StringTokenizer str1=new StringTokenizer("i like you very much.i do not hate you!i do.",sDelim);		
	while(str1.hasMoreTokens()) {  // get 3 sentense
           s1=str1.nextToken();
           s1=s1.trim();                  
           StringTokenizer str2=new StringTokenizer(s1, " ");                   
             while(str2.hasMoreTokens()){ // check each word
                s2=str2.nextToken();
                s2=s2.trim();
                if (s2.compareTo("do")!=0) // check word "do"
                System.out.print(s2+ " "); // print/store the valid words
              }
           System.out.println();
	 }
	}
}
tong1 22 Posting Whiz

line 7 : case Character.isUpperCase(ch): is wrong. The reason is:

Only constant values may define each case. That is, Following each "case" must be a constant rather than variable/expression. The Character.isUpperCase(ch) is not a constant, thus it is not working.
If you don't like "if... " you may delete "if... ", which also works well. So the correct code for the switch could be:

switch (ch)    {     
      case '\u0020':
      break;
      case '\u0009':
      break;
      default:
         ch=Character.toLowerCase(ch);
         store+=ch;  
  	}
Xufyan commented: +++ :) +0
tong1 22 Posting Whiz

One thing you have to remember:
If you have defined some non-default constructors, the compiler will not implicitly provide a default constructor. If you need a default one you'd better define one. Otherwise it wouldn't pass compiling. For example, the following code leads to an error message for line 10:unsolved symbol

import java.io.*;

public class DefaultConstructor {

    public DefaultConstructor(String s) {
    	System.out.println("I am Not Default with no arguments. " + s );
    	}      

    public static void main(String[] args) {
        DefaultConstructor d = new DefaultConstructor();
    }
}
prem2 commented: Nice Example +1
tong1 22 Posting Whiz

Default constructor is the constructor with no arguments requested. It is called implicitly when creating an instance.

import java.io.*;

public class DefaultConstructor {
    
    public DefaultConstructor() {
    	System.out.println("I am Default with no arguments.");
    	}      

    public static void main(String[] args) {
        DefaultConstructor d = new DefaultConstructor();
    }
}

output:
I am Default with no arguments.

tong1 22 Posting Whiz

Thank you for your "Why". I found I sent you a wrong version. In line code 11 if you put:

FileDialog fd = new FileDialog(null , "Open a document", FileDialog.LOAD);

you will have the error message: "the constructor file dialog is ambiguous"
However, the line of code 11:

FileDialog fd = new FileDialog(this, "Open a document", FileDialog.LOAD);

will pass compiling. Therefore, we should emphasize:
For the first argument "Frame parent" of the FileDialog constroctor one should use "this" indicating the parent Frame is the current object.

tong1 22 Posting Whiz

ezkonekgal ,thank you for your reply. I have checked and tested your code.
(1) You use JFileChooser which seems better than FileDialog which I use currently (because, as you reported, eclipse complains about the constructor I wrote).
(2) May I suggest you delete the "OK" button which is useless.
(3) Your code runs correctly. I have replaced your LayoutManager by FlowLayout so that components show up properly.
Attached please find the modified code. It runs correctly in my machine.

tong1 22 Posting Whiz

Your code shown above is correct. I have tested with a known file. The result is correct. AS long as the browsing files is concerned, as jon.kiparsky indicated, it is already available in Swing. For example, the class FileDialog is a candidate for this purpose. Since its constructor requests a parent frame , as written in Java API, the class you define has to inherit JFrame. I have modified your code as follows. You have to modify your main method accordingly. Attached please the code altered for your reference.

import java.io.*;
import java.awt.*;
import javax.swing.*;
class FileRead extends JFrame {
	static File name;  // it is created in constructor, then used in main
	static int count =0; // count the number of lines where characters are found
	static int count2=0; // count the nubmer of empty lines
	
public 	FileRead(){  // constructor for FileRead
	try{
      FileDialog fd = new FileDialog(this, "Open a document", FileDialog.LOAD); 
      fd.setDirectory(System.getProperty("user.dir")); // the window starts with current folder
      fd.setVisible(true);	
   	  name= new File(fd.getDirectory(), fd.getFile());
   	 }catch(Exception e){
   	 	System.err.println(e.getMessage());
   	 	}
   	setSize(400,400);
   	setVisible(true);
   	 }

Good luck.

tong1 22 Posting Whiz

I hope the following code could help you.
I also made some comments to help you to understand.

import java.util.*;
public class RandomNumSelected{  
 
 static int random[] = new int [20];  // store 20 random numbers varying from 0 to 255;
 static int selected[] = new int[5];  // store the 5 distinct numbers you were looking for
 
	static int search(int a[], int n, int d){   //search the array a from subscript 0 until (n-1) for d. 
	for (int i=0;i<n;i++)  
	if (a[i]==d) // if the element is found
	return i;  // then return correspongding subscript
	return -1; // No thing happens in the for loop, implying d is not found, thus return -1. 
	}
	
    public static void main(String []args){
    Random rn = new Random();
    for (int i=0; i<20; i++)  //  assign 20 random values to the elements of array random 
    random[i]= rn.nextInt(256);
    
    int counter=0;
    selected[0]=random[0]; // the first random number is stored in selected array
    for (int i=1; i<5; i++)
     for(int j=1;i<random.length;j++)
    		if (search(random,i,random[j]) == -1){ // if the current selected array has no such value of random[j]
    		selected[i]=random[j]; // the random number random[j] is stored in the array selected
    		break;  //terminate the nested loop so that the next run for the outerloop starts
    		}    		
   	System.out.println("The 20 random numbers varying betwee 0 and 255 [0,255]: ");
   	for(int a:random)
   	System.out.print(a + " ");
   	System.out.println();  
   	System.out.println("The 5 distinct numbers selected from the above 20 numbers:"); 				
   for (int a:selected)
   System.out.print(a + " ");
   System.out.println();
    }
}

The output:
The 20 random numbers …

tong1 22 Posting Whiz

har58, you should make plan beforehand. For example,
(1) pre-store 20 existing random nmbers in an array.
(2) when executing program store the distinct 5 random numbers in another array one by one.

Should we start with the following code as clues:

public class RandomNumSelected{  
 
 int random[] = new int [20];  // store 20 random numbers varying from 0 to 255;
 int selected[] = new int[5];  // store the 5 distinct numbers you were looking for
 
	static int search(int a[], int n, int d){   //search the array a from subscript 0 until (n-1) for d. 
	for (int i=0;i<n;i++)  
	if (a[i]==d) // if the element is found
	return i;  // then return correspongding subscript
	return -1; // No thing happens in the for loop, implying d is not found, thus return -1. 
	}
	
    public static void main(String []args){
    	.....
    	 
      }
}

comments: The random numbers vary in a range. For example, from 0 to 255 [0,255]
You may generate by:
(1) the static method rand() in Math class.
(2) Create a instance of the class Random:
Random ran = new Random();
int n = ran.nextInt(256);

har58 commented: Thanks +1
tong1 22 Posting Whiz

You may replace the code in line 24 where the error occurs by the following two lines of code:

int va = this.statVect[i].getValor();
     va += otroVect[i].getValor();
     this.statVect[i].set(va);

Can you answer me Why we should modify in this way?

javaAddict commented: Allowing the OP to think +6
tong1 22 Posting Whiz

One may also use the ordinal() method to provide index for the twoDim so that the int i could be saved.

String twoDim[][] = new String[2][5] ;
   for ( Days day : Days.values())
      twoDim[0][day.ordinal()]=day.name();

   for (Periods prds : Periods.values()) 
      twoDim[1][prds.ordinal()]=prds.name();
tong1 22 Posting Whiz

I wonder if the following way is a candidate answer for Xufyan's question?
Should we make Days type 1D array and Periods type 1D array to play a go-between role? Then use the method name() to store the names in two final String arrays?

public class Enumeration0 {
  enum Days {Monday, Tuesday, Wednesday, Thursday, Friday}
  enum Periods {Period1, Period2, Period3, Period4, Period5}
  
    public static void main(String[] args){
    String sd[]=new String[5]; // allocate String array sd
    String sp[]=new String[5]; // allocate String array sp
    Days d[] = Days.values();  // create Days array d with values of Days
    Periods p[]=Periods.values(); // create Periods array p with values of Periods
    
    for(int i=0; i<5; i++){  // store the enum values in String arrays: sd and sp 
	sd[i]=d[i].name();
	sp[i]=p[i].name();
		}
    for (String  s : sd)   // print String array sd
	System.out.print(s + " ");
	System.out.println();
    for (String  s : sp)  // print String array sp
	System.out.print(s + " ");
	System.out.println();
	}
}
tong1 22 Posting Whiz

A method to declare and allocate Xufyan's ladder array is written as follows so that the creation of the array seems further concisely in main method.

public class array{
	
	static int[][] allocateLadderArray( boolean up){
		int [][]a; // declare 2D array a
		a = new int[4][]; // allocate spaces for 4 rows, i.e. declare 4 1D arrays
		for (int i=0; i<4; i++) // allocate spaces for the 2D Latter array
		if (up)
		a[i] = new int[4-i];
		else
		a[i] = new int[i+1]; 
		return a;   // return the reference of the allocated array
	}
	static void printArray(int a[][]){
	 for ( int i=0; i<a.length; i++ ){
     for ( int j=0; j<a[i].length; j++ )
     System.out.print (a[i][j] + " ");
     System.out.println ("");
     		} 
     }
     static void assignValues(int a[][]){
     int k=100;
       for (int i=0; i<a.length; i++ )
     for (int j=0; j<a[i].length; j++ ) {     
     a[i][j] = k;
     	k = k-10;
     }	
     }

public static void main (String [] args){

 	int [][] TwoDArray1 = allocateLadderArray(true);  //return a reference of an allocated ladder array to TwoDArray1
 	int [][] TwoDArray2 = allocateLadderArray(false); //return a reference of an allocated ladder array to TwoDArray2
   	
	assignValues(TwoDArray1); // assign initial values to every elements of the 2D array TwoDArray1
	assignValues(TwoDArray2); // assign initial values to every elements of the 2D array TwoDArray2
   	printArray(TwoDArray1); // print all elemens in format of rows and columns 
   	printArray(TwoDArray2); // print all elemens in format of rows and columns 
  }
}
tong1 22 Posting Whiz

I have implemented Xyfuan's latter arrays using two methods: static void init(int a[][]) to assign initial values to each elements and static void printArray(int a[][]) to print a 2D array. it works. Please check if there are any improper remarks/comments.
The output:
100 90 80 70
60 50 40
30 20
10
100
90 80
70 60 50
40 30 20 10

The code:

public class array{
     static void printArray(int a[][]){
     for ( int i=0; i<a.length; i++ ){
       for ( int j=0; j<a[i].length; j++ )
       System.out.print (a[i][j] + " ");
       System.out.println ();
     		} 
     }
     static void init(int a[][]){
     int k=100;
     for (int i=0; i<a.length; i++ )
       for (int j=0; j<a[i].length; j++ ) {     
       a[i][j] = k;
       k = k-10;
     }	
     }

public static void main (String [] args){

 	int [][] TwoDArray1; // declare 2D array TwoDArray1
 	int [][] TwoDArray2; // declare 2D array TwoDArray2
 	TwoDArray1 = new int [4][]; // allocate spaces for 4 rows, i.e. declare 4 1D arrays
	TwoDArray2 = new int [4][]; // allocate spaces for 4 rows, i.e. declare 4 1D arrays
   	for (int i=0; i<4; i++){
  	TwoDArray1[i]= new int[4-i]; // allocate spaces for the 2D array TwoDArray1
   	TwoDArray2[i]= new int[i+1]; // allocate spaces for the 2D array TwoDArray2
   	}
   	
	init(TwoDArray1); // assign initial values to every elements of the 2D array TwoDArray2
	init(TwoDArray2); // assign initial values to every elements of the 2D array TwoDArray1
   	printArray(TwoDArray1); // print all elemens in format of rows and columns 
   	printArray(TwoDArray2); // print all elemens in format of rows and columns 
  }
}
tong1 22 Posting Whiz

If you want the first value to be 100 the following loop would be proper in line 13 - 17.

for ( i=0; i<TwoDArray.length; i++ )
     for ( j=0; j<=i; j++ ) {     
     TwoDArray [i][j] = k;
     	k = k-10; // equivalent to "k -= 10;"
     }

In your last version, the location of the curly brace after the loop control: for ( Row=0; Row<TwoDArray.length; Row++ ) should simply move immediately after the loop control: for ( Elements=0; Elements<=Row; Elements++ )

Xufyan commented: thanks alot +0
tong1 22 Posting Whiz

You did not show line 28 as error message indicates.
Your result will be always 1 since int division: 1/(e*i) always 0.
You should declare double e = 1.0 instead of int e;
For example, the java method in calculating PI using Lord formula could be:

double Lord(int n) {  // n represents number of iterations/terms
        double pi =1;
        double sqroot;
  for (int i = 3  ; i <n ; i +=2  )
        pi += 1.0/(i*i);
        pi = Math.sqrt(pi*8);
  return pi;
}

The calculation is arried out in terms of double instead of int type.

The java program is presented in terms of class. In C/C++ you may not define a class, but in Java you have to.
Please tell me how to delete my post? I have some posts to be deleted.

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

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

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.