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

Mattox is right.

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

(1) flyingcurry ,if you have to sort the whole array the second argument “length” is redundant. In fact, the length is the array.length。
(2) The line 13 could be replaced with

for (j=0; j<length-1-i; j++)  //to avoid the unnecessary comparisons made of the stable region.

See the post on bubble sort

The line 21 should be replaced with

for (i=0; i<length; i++)
tong1 22 Posting Whiz

One should write the following line of code to update the control variable ctr (the ODD numbers less than 10):

for (;ctr<=10; ctr+=2, ctr2++) {
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

Just for your reference.
In Pyphon the list data type has a method: pop().
list.pop()
removes the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)

tong1 22 Posting Whiz

It works. Attached please find the mofidied program.

tong1 22 Posting Whiz

(1) You may define the method as the main(). Hence replace the line 8 with

public static void main(String args[] ){

(2) You forgot to create the instance of Scanner: input. Hence insert line 8 the following code:

Scanner input=new Scanner(System.in);
tong1 22 Posting Whiz

The UML for the class MyPoint could be written as follows:

-x : double
-y : double

+MyPoint()
+MyPoint(x:double,y:double)

+getX() : double
+getY() : double
+setX(x:double):void
+setY(y:double):void
+distance(AnotherPoint:MyPoint):double
+distance(p1:MyPoint,p2:MyPoint):double

tong1 22 Posting Whiz

If you want to generate a negative random number, for example, in the range varying from -200 to -300 [-200,-300], you may write the code as follows:

import java.lang.Math;
…
int a = (int)(Math.random()*101)-300;
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

The class Math in the package java.lang has a static method random() which returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
I use this method to generate random number. For example, to generate a integer varying from 0 to 255 [0,255], one may call the method by the following code:

int a = (int) (Math.random()*256);

Please study the API for reference.

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

In this case you should cast the result of the evaluation of "xCenter + 200 * Math.cos(2 * Math.PI * 3 / 7)" or "yCenter + 200 * Math.sin(2 * Math.PI * 3 / 7)":

g.drawLine ((int)(xCenter + 200 * Math.cos(2 * Math.PI * 3 / 7)),(int)(yCenter + 200 * Math.sin(2 * Math.PI * 3 / 7)), 70 ,336);
tong1 22 Posting Whiz

In the definition of class EnemyShip, you may add a static int attribute numEnemieShip from which you may know the number of enemy ships created from time to time. Hence, the constructor is defined as follows:

public EnemyShip(int x, int direction){        
this.x = x;        
this.direction = direction;    
numEnemieShip++;
}
tong1 22 Posting Whiz

Your set methods (settotalPrice() and settotalPriceWithTax()) should be of the type void

tong1 22 Posting Whiz

As far as I know, if the instance of JFrame is a, the code for registering its closing button could be one line of code as follows:

a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tong1 22 Posting Whiz

The following code demonstrates how to analyze a keyboard input in terms of tokens. The client may input no more than 100 words with the final string “end” (excluded). These words are simultaneously stored in the String array s, through which one may do search for a specific word.

import java.util.*;
public class Tokenizer0 {	
	public static void main(String args[]){
		Scanner asdf = new Scanner(System.in); // obtain an instance of Scanner
		String s []= new String[100]; // declare a string array with the size of 100 to accommodate the input words via asdf
		int counter = 0; // counter counts the number of input words
		
		while(asdf.hasNext()){ //returns true if asdf has next token
		s[counter++]=asdf.next(); // assign the next token to the string array
		if (s[counter-1].compareTo("end")==0) break; // check the input word. if the input is "end", then stop the while loop
		}
		System.out.println("Number of Words:" + (counter-1)); // print out the total number of input words
		for (int i=0; i<counter-1; i++) // print out the input words
		System.out.println(s[i]);
	}
}
kramerd commented: You are counting the number of lines, not words +0
tong1 22 Posting Whiz

To drawing a line one has to use the instance of Graphics : Graphics g so that the method in drawing a line can be applied:
g.drawLine(int x1, int y1, int x2, int y2) ;
which draws a line, using the current color, between the points (x1, y1) and (x2, y2) in this graphics context's coordinate .

Hence the method drawVerticalLine you posted should have a parameter of the type of Graphics (or use other way to obtain the instance of Graphics).

tong1 22 Posting Whiz

Any primitive data type has its own wrapper class. The wrapper class of int is Integer which is defined in the package java.lang. Its static attribute MAX_VALUE represents the positive largest value (2147483647)while MIN_VALUE the negative smallest value. In the same way one may obtain the maximum/minimum values for other data types, such as short, long, float, and so on.

import java.lang.Integer;
public class Max {
public static void main(String args[]){
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MIN_VALUE);
	}
}
tong1 22 Posting Whiz

As indicated by API :
acos
public static double acos(double a)Returns the arc cosine of a value; the returned angle is in the range 0.0 through pi.
The return value of Math.acos is in radian instead of degree. It has to be multiplied by 57.296 (180/PI) to become the value in degree.

tong1 22 Posting Whiz

Alternatively, one may use the CANCEL button on the input dialog box:
JOptionPane.showInputDialog(inputMessage); to check if the program should terminate or not.

inputString = JOptionPane.showInputDialog(inputMessage);
        if (inputString== null){
        JOptionPane.showMessageDialog(null, "See you next time",
        "Telephone Digit",JOptionPane.PLAIN_MESSAGE);        	
        	break;
        }
tong1 22 Posting Whiz

Your forgot to add the component userMessageLabel into container:

add(userMessageLabel); // this line of code is missing

Please use CODE tag to post your code so that one may refer your certain code to a specific line number

tong1 22 Posting Whiz

Following Dean_Grobler's suggestion you may read each number as a string s, and then convert s into a decimal number in the type of double by the following line of code:

double d = Double.parseDouble(s);

or convert s into a decimal number in the type of float:

float f = Float.parseFloat(s);
tong1 22 Posting Whiz

It's impossible to add an integer value into a boolean type array which stores boolean value only.

tong1 22 Posting Whiz

If multiple choices( selecting one more items at one time) are allowed you may use "if" but no "else".
For the 3 choices you may simply use Class JCheckBox.
In your layout the selections seem to be more complex than a ckeckbox.

tong1 22 Posting Whiz

Linked list
Queue
binary search tree
Overridden method
Thread and animation

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

(1) The default layout manager for JFrame is BorderLayout where 5 blocks are defined as NORTH,WEST,SOUTH,NORTH,CENTER. So the code: f.setLayout(new BorderLayout()); is redundant.

(2) Since the f container is controlled by a BorderLayout when you add any sub-containers into f you have to indicate which block each container goes to. Thus the code, for example, should be:

c.add(p1, BorderLayout.NORTH); // the container p1 having 4 buttons goes to the NORTH block
c.add(p2, BorderLayout.CENTER); // the container p2 having textarea1,label1, and textfield1 goes to the CENTER block

(3) Since you have created an instance of JFrame in the constructor, the class Gui has no need to extend JFrame any more.

(4) Use f.setVisible(true); instead of f.show() which is deprecated

(5) The size of the frame might not be proper to show all the components. You may have to make it bigger/wider perhaps, such as altered with f.setSize(500,300);

(6) Inser the following line of code by the end of the constructor to register the closing button:

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

(7) Use code tag to post your code so that one may discuss the code by referring a specific line number.

tong1 22 Posting Whiz

Please fill the following table on a page to trace the nested for each loop:
for(int count = 0; count <= 3; count++)
for(int count2 = 0; count2 < count; count2++)
System,out,println(count2)
Only when both contitions: (count2<count) and (count<=3) are true, the output is available. If so fill the output accordingly. Otherwise fill the output with N/A

tong1 22 Posting Whiz

Please fill the following table on a page to trace the nested for each loop:

for(int count = 0; count <= 3; count++)
for(int count2 = 0; count2 < count; count2++)
System,out,println(count2)

Only when both contitions: (count2<count) and (count<=3) are true, the output is available. If so fill the output accordingly. Otherwise fill the output with N/A
value of count value of count2 (count2<count)? (count<=3)? output
0 0 F T N/A
1 0 T T 0
1 1 F T N/A
2 0 T T 0
2 ...
2
3
3
3
3 ...

tong1 22 Posting Whiz

The index variable "cnt" in line 29 and 35 is 5 after the method EnterNumbers() has been called. The value 5 of the "cnt" is "OutOfBounds".

You have to rewrite the method NumberCheck() because it is not functional.

tong1 22 Posting Whiz

The width of each button is given too small.
Try to replace lines 19 and 20 with the following width of 150:

b1.setBounds(50, 50, 150, 50);
b2.setBounds(50, 125, 150, 50);

tong1 22 Posting Whiz

An animation is executed in the way where Thread.sleep( sleepTime ) should be called after each image is displayed. In your code, the sleep method is called each time after 15 images have been displayed. This is improper.

tong1 22 Posting Whiz

Please to use the code tag so that the number of line could be mentioned.
I guess that your problem is the control index "currentImage", the global variable, that is out of the bound after completing the first run of the paint(), i.e. after the 15 (totalImages) pictures are displayed. So do insert the code line:
currentImage = currentImage%totalImages;
after the code line
currentImage = ++currentImage;

tong1 22 Posting Whiz

Please use code tags around posted code to make it more readable.
Since your class projectThree extends Applet an method public void init(){...} would be defined instead of a constructor. Hence the code line: public projectThree() should be replaced by public void init()
I have a question for your reference:
What is a spot? I think it is a point which should be defined by the coordinate: x and y. If the spot is a point defined by coordinate x and y, then the sensible judgement is the distance between the secret spot(point) and the point clicked by the mouse.

tong1 22 Posting Whiz

Xufyan has declared two arrays but only one controlling index tos (normally written as top, the stack top indicator), in the class Stack. How can one use only one indicator to indicate the tops of two different arrays since the tops of the two arrays could be different? Hence, we should declare two tifferent tops: int topInt and float topFloat. The class Stack is defined as follows:

class Stack{
int StackArrayI[] = new int[3]; 
float StackArrayF[] = new float[3]; 
int topInt=-1;
int topFlat=-1;

public void push(int value){
	if (topInt==2)
	System.out.print ("Stack already Full..!\n");
	else
	StackArrayI[++topInt] = value;
	}

public void push(float fvalue){
	if (topFloat==2)
	System.out.print ("Stack already Full..!\n");
	else
	StackArrayF[++topFloat] = fvalue;
	}
	
float pop(){
	if (topFloat==-1){
	System.out.print ("Stack is Empty");
	return 0;
	}
	else
	return StackArrayF[topFloat--]; 
	}
} 
…
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) In the constructor you have redundant declaration for these attributes
private JRadioButton courier, timesnr, helvetica;
which makes them become the local variables within the constructor, but the actual three attibutes are still null.
(2) The radioButtons have to be grouped so that the client may select only one of them. The radioGroup is an additional attribute for the class:
private ButtonGroup radioGroup;

radioGroup = new ButtonGroup();
      radioGroup.add(courier);
      radioGroup.add(timesnr);
      radioGroup.add(helvetica);

(3) Finally, one has to insert the following code into the itemStateChanged method:

after line 69

if (courier.isSelected()){
         typeFace = new String("Courier");
         }else if(timesnr.isSelected()){
         typeFace = new String("Times New Roman");
         }else if (helvetica.isSelected()){
         typeFace = new String("Helvetica");
         }
tong1 22 Posting Whiz

nix nix, it is seen from the output shown in your post that

*        *
**      **
***    ***
****  ****
**********

at the 1 st row: 1 star, 8 spaces, and 1 star are printed
at the 2 nd row: 2 stars, 6 spaces, and 2 stars are printed
at the 3 rd row: 3 stars, 4 spaces, and 3 stars are printed
at the 4 th row: 4 stars, 2 spaces, and 4 stars are printed
at the 5 th row: 5 stars, 0 space, and 5 starts are printed
This observation might be summarized in terms of a for loop body where i is the control variable starting by 1 up to 5 with each increment of one as follows.
at the i row: i stars, (10-2*i) spaces, and i stars printed.
Hence, the body of the “for loop” summarized above is thus written as follows:

{
	for (j=0;j<i;j++)  // to print i start(s) 
	System.out.print("*");
	for (j=0;j<10-2*i;j++) // to print (10-2*i) spaces
	System.out.print(" ");
	for (j=0;j<i;j++)  // to print i start(s)
	System.out.print("*");
	System.out.println(); // change to the next new line
}

nix_xni, you may also study Xufyan's suggestion as a reference to complete the coding.

tong1 22 Posting Whiz

In addition to the way ,as kvass points out, to solve this problem one may write a method to do the checking job:

/* The method duplicate checks the partial part (the index from 0 up to the n-1) of the array a to see if there is an b in it or not. */	
	boolean duplicate(int a[], int b, int n){  
		for (int i=0; i<n; i++) //do the for loop check on the array a from the index of 0 up to the index of n-1
		if (b== a[i]) // if there is a b in the array a
		return true;  // both the for loop and also the method call are terminated with returning value of  true
		return false; // if there is no b in the partial array a then return false.
	}

so that the for loop body includes the following operation:

while(duplicate(numbers, inputValue, i)){ /* check if the newly typed in inputValue is already in the partial array a. 
	inputValue is declared as int, i indicates the current number of values stored in the array a. */
	System.out.println("Number cannot be repeated, input in slot " +  i  + " again :"); /* i is the control variable of the for loop. since the method duplicate(...) shows the client typed in a duplicated value, one has to ask the client to redo the input  */
	inputValue = input.nextInt(); // receive the inputValued the client re-typed in 
	}

if the while loop has been passed, …

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

The index of the 10th position is 9. When (tos==9), that is the highest index is 9, the StackArray is full, which means the last value has been already stored in the 10th position. If you want to have no value stored at the 10th position, the condition has to be (tos==8)

tong1 22 Posting Whiz

Thank you James. It works.

tong1 22 Posting Whiz

Thank you, James, for the comment.

In the following code: line 17 the paintComponent() is replaced by paint(). If the paintComponent() is used the line 18 will produce a run error:

at javax.swing.JComponent.paint(JComponent.java:1027)
at CreateSmiley.paintComponent(Smiley.java:18)
(Why? I don't know. Please offer some annotation for this point.)

If the paintComponent() has to be used one has to write two lines of code as the first two lines of the method to do the job of cleaning canvas.

g.setColor(Color.white);
g.fillRect(0,0,600,600);

In order to clean the canvas by calling super.paint(g); one has to replace paintComponent() by paint().

import javax.swing.*;
import java.awt.*;

class CreateSmiley extends JPanel implements Runnable {

int x=0,y=0;
Thread timer=null;   // a Thread instance associated with repaint()
boolean flag =true;  // signal toggle controls the increment/decrement in x and y

public void start(){
	if (timer==null){
	timer = new Thread(this);
	timer.start();
	}
}

public void paint(Graphics g) {  //  paintComponent replaced otherwise the line 18 produces an error message
super.paint(g); // clean the canvas before drawing the next picture
g.setColor(Color.RED);
g.drawOval(x,y,200,200);
g.setColor(Color.YELLOW);
g.fillOval(x+50,y+70,20,20);
g.fillOval(x+130,y+70,20,20);
g.setColor(Color.GREEN);
g.fillArc(x+30,y+80,140,70,190,165);
}

public void run(){
   while(timer != null){
   try {Thread.sleep(300);
   if(flag) {
	x+=5;
	y+=5;
   } else {
	x-=5;
	y-=5;
	}
   if ((x == 400) || (x==0))
	flag = !flag;
   repaint();
	}catch(Exception e){}
   }
  }
}

public class Smiley extends JFrame {	
	public Smiley(){
	super("Smiley");	
   	CreateSmiley s = new CreateSmiley();
   	add(s);
   	s.start();
	setSize(600,600);
	setVisible(true);
	setDefaultCloseOperation(EXIT_ON_CLOSE);	
	}

public static void main(String a[]) throws Exception{
	Smiley sm= new Smiley();
	}
}
tong1 22 Posting Whiz

Thank you very much indeed James. Thank you for your comments. I will try the method getActionListeners() to have a taste in getting a reference to an instance of an anonymous inner class . I am also noticed that the return data type of the method is an array: public ActionListener[] getActionListeners().
I hope it will work fine.

tong1 22 Posting Whiz

You may try the following changes.
Because we want the smileFlow() runs for a certain time (befor x reaches 600), you have to
(1) delete the line code s.smileFlow();
(2) insert the above code s.smileFlow(); after the f.setDefaultCloseOperation(3);
so that it runs after setting up the frame properly.
P.S. the code:f.setDefaultCloseOperation(3);
should be written as:
f.setDefaultCloseOperation(EXIT_ON_CLOSE); // so that one may clearly understand


(3) replace the name of the method: public void paintComponen(Graphics g)
by public void paint(Graphics g)
(4) inser the code line:
super.paint(g); // as the first line code of the method.
into the paint method.
so that the canvas is cleaned before the next operation of repaint().

I have modified your code a little bit so that the Smiley moves "forever".
Attached please find the modification
Please use the code tag to post your code so that one may mention about the code line number.

tong1 22 Posting Whiz

JamesCherrill, I don't understand the second point you made.
How can we reuse the instance the myButton does have? For example, if I want to add the same addActionListener as the myButton to another button, e.g. myButton1, I have to rewrite the definition of the anonymous inner class because I have no way to refer to it. Is there a way to refer to that previous anonymous inner class?

tong1 22 Posting Whiz
class Stam  // the containing class Stam has an anonymous inner class
{
    public int  foo(int d,final int y){  
        int x= new Person(d){    // this anonymous inner class extends the class Person.
            public int getDoubleAge() { //in this inner sub-class a method public int getDoubleAge() is added or overridden if it does pre-exist in the class Person.
                return age*y;
            }
        }.getDoubleAge(); // the handle for the method getDoubleAge() is the anonymous instance of the anonymous inner class
        return x;
    }
}