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

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

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

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

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

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

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

lines 44 and 45 are redundant.

it there a quick way to take the numbers back out

click the "Toggle Plain Text" above your code before copy it.

tong1 22 Posting Whiz

(1) A comma is missing at the end of line 22
(2) input validation also includes other invalid cases, such as NumberFormatException, negative values for investment or number of years.

tong1 22 Posting Whiz

If both files under the same folder,
(1)remove line 3 in the file Main.java, i.e. remove "package deposit_withdraw;"
(2) in lines 31 and 34 in Main.java,
the method getBalance should be written as
myAccount.getBalance();

tong1 22 Posting Whiz

(1) in the selection structure of "if else" you should place the "Beep-Beep" case (if (number%3==0 && number%5==0)...) as the first selection, then "else if (number%3==0 || number%5==0)" for the case "Beep" because the condition for "Beep-Beep" always meets the condition for "Beep".

if (number%3==0 && number%5==0) //the "Beep-Beep" case should be placed as the first selection since its condition always meets the condition for the next selection.
System.out.println("Beep-Beep");
else if (number%3==0 || number%5==0)  // the second selection , i.e. the "Beep" case
System.out.println("Beep");

(2) For the above two cases you have no need to print up the numbers from 0 up to the limit. Only in the third case each number from 1 up to limit has to be printed.

(3) therefore, the case where each number from 1 up to limit has to be printed should be your third selection:

else {  // the third selection/case
int count = 0;
while(count<=number)
System.out.println(count ++);
}
tong1 22 Posting Whiz

May I suggest you use the selection structure where the final selection will be associated with while loop to print a series of number up to the limit.
(1)The cases "Beep" and "Beep-Beep" should no be placed withing the while loop since they are each individual case respectively which should be done once, i.e. just print Beep or Beep-Beep.
Hence, they should be associated with the selection structure, such as

if (number%3==0 && number%5==0) 
             System.out.println("Beep-Beep");
             else if (number%3==0 || number%5==0)
             System.out.println("Beep");

(2) be noticed that the case : if (number%3==0 && number%5==0) should be the first case to be checked. (Why?)
(3) The case, which neither-("Beep") nor ("Beep-Beep"), should be the third selection in the if else structure. In the third selection you may use while loop to print out a series of count number. Therefore the third selection could be the while loop:

else while(count<=number)
     System.out.println(count ++);
tong1 22 Posting Whiz

(1)Create a String object, for instance s (e.g., String s="";) to accommodate the information obtained from your for loop:
for(int a=0 ; a<values.length ; a++){
System.out.println("[Firstname Length: "+values[0].length()+" ]"
+"[Lastname Length: "+values[1].length()+" ]"
+"[Employee IDnumber: "+(i+1)+" ]"+" = "+ staff);
a++;
}
(2)Create a BufferedWriter bw in the following way:
BufferedWriter bw = new BufferedWriter(new FileWriter("a .csv"));
(3)use the member method write(String s) of bw to write the information into the file "a .csv";
bw.write(s);
(4) close the BufferedWriter
bw.close();

tong1 22 Posting Whiz

If the number is divisible by 3 or by 5

if (number%3==0 || number%5==0)

If the number is divisble by 3 and 5

if (number%3==0 && number%5==0)

tong1 22 Posting Whiz

The following errors should be corrected.

The code line 19 should be:
years = Integer.parseInt(yearsInvest);

The code line 20 should be:
while(yearsloop < years)

The code line 22 should be:
balance = investment * Math.pow(1.0 +rate/100, yearsloop);

The code line 23 should be:
JOptionPane.showConfirmDialog(null,

The code line 27 should be:
yearsloop = yearsloop + 1;

The output of the values in the JOptionPane.showConfirmDialog windonw shoud be formated.

tong1 22 Posting Whiz

(1)You have to assign the following variables an initial value, such as 0 for init or 0.0 for double in lines 10,11, and 12:
double withholding= 0.0;
double netPay= 0.0;
int withholding1= 0;
to pass the compiling.

(2) You have to delete the pair of curly brackets at the line 28 and the line 40

tong1 22 Posting Whiz

For present question the teacher of mental arithmetic may tell students count in one's head as follows.
There are 499 expressions.

1 + 999 = 1000
2 + 998 =1000

499 + 501 =1000
(only 500 is missing)
All expressions have the same outcome of 1000. So the outcome of adding all the whole numbers from 1 to 999 is 1000×499 + 500 (499,500).

The above understanding by count in one’s head can be explained by the following for loop

int sum = 0;
for (int i=1; i<=499; i++)
sum += i+ (1000-i) ;  //which is equivalent to  sum += 1000;   
// only the number of 500 is missing

The above loop thus could be simplified by an expression:
sum = 499*1000 // do the accumulation of 1000 499 times

Therefore, the code for the following for loop:

int sum =0;
for (i=1;i<=999;i++)
sum += i;

could be simplified by an expression:
sum = 499*1000+500;
where the final sum (499,500) is the consequence of adding all the whole numbers from 1 to 999

Of course, we have to follow computer professor’s instruction to obtain the result of adding all numbers from 1 to 999 by a loop rather than an expression.

tong1 22 Posting Whiz

the local variable intTotal may not have been initialized

The code in line 8 should be:
int intTotal=0; //so that the intTotal is initialized.

We can try a while or a do while loop. How would I go about it that way?

Define the condition for the while loop, as Jon.kiparsky discussed earlier, as follows
while(intCounter <=1000) {
...
}
You may add the rest of the code before, within the loop body, and after the loop.

tong1 22 Posting Whiz

(1) The code in the line 12 is not correct. The code in line 12 could be:
intTotal = intTotal + intCounter;
or
intTotal += intCounter;
(2) The code in line 13 should be moved/inserted into the place between the line 14 and 15.
(3) The initial value for the control parameter intCounter in the for loop could be 1 rathern than 0
jwmollman , in the future can you try to use while or do while loop to accomplish the task? or use a recursive/iterative method to do the job? We have various ways to go.

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

The following code could be helpful.

public class Prinf{
	static double decimal(double d){
		int dd = (int)d;
		d -=dd;
		return d;
	}
	public static void main(String args[]){
         double d = 6.328941;
         System.out.printf("%8.6f\n",decimal(d));
	}
}

output:
0.328941

tong1 22 Posting Whiz

Or simply put the header as:
import java.util.*;

tong1 22 Posting Whiz

Should replace
line 14: int year = scan.nextInt(); with the following code:

int year; // declaration of the integer variable year
tong1 22 Posting Whiz

The errors I have found are indicated as follows:

(1) line 10 is a header declaration (import java.util.*;", which should be place in "the heading part", i.e. the first line of the code.
(2) line 13:
The class name is Scanner rather than scanner;
(3) lines 25,27:
the method println(...) are missing handles. Both should be:
System.out.println(...);
(4) line 16 the variable year has not been delrared yet. The line 16 should be:
int year = scan.nextInt();
(5) In line 20 the boolean variable's name (leapyear ) is not consistent with the later name (isLeapYear) in line 23. Both should be identical.

tong1 22 Posting Whiz

The story from text book “Java How to program” by H.M.Deitel & P.J.Deitel, 5th ediction, 2003. p.372) .
“Let us motivate the need for static class-wide data with a video game example. Suppose that we have a video game with Martians and other space creatures. Each Martian tends to be brave and willing to attack other space creature when the Martian is aware that there are at least four other Martians present. If fewer than five Martians are present, each Martian becomes cowardly, so each Martian needs to know the martianCount. …“
Accordingly I have written the following java program to demostrate the usage of static and instance variable/method.

class Martian  {
private String 	name; // instance variable
private static int count; // class variable
 
public Martian(String s){ // constructor with one argument: the name of the Martian
   name = s; 
   System.out.println( name + " was created");
   count++;
	};

/* The method cowardly() is defined as static since it descripts the psychosis of the whole class Martian/all Martians
 * Also be noticed that the static method accesses the static variable(count) only */
 
public static void cowardly() { // the method to test whether each individual Marian is cowardly or not.
System.out.println( // if the total number of Martians is less than 5, they are cowardly.
(count < 5 ? "Martians are cowardly." : "Martians aren't cowardly."));
   }

public static int getCount() { return count; }

protected void finalize(){ // A martian died, the memory has been returned …
tong1 22 Posting Whiz

Instance variable/method - Variables/methods that are specific to each instance (object) of the class e.g. name, age.... When accessing/calling them, the object, as the reference has to be used as a handle.
Class variable/method - Variables/methods that represent/deal with class wide situation, e.g. a static variable which belongs to a class and has only one value specific to the class. When accessing/calling them, the class name is needed as a handle.

tong1 22 Posting Whiz
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

Your code is basically correct. Please use the tag [CODE] for your code.
I have made a small modification. I am not sure if there is a term called "accumulated interests" which is different from simple interests.

import java.lang.*;
public class simple {
public static void main (String[] args){
// this program calculates the simple interest.
int principal, noy;
double rate, si;
principal = 1000;
noy = 3;
rate = 2.5;
si = (principal * noy * rate) /1000;
double d = (Math.pow((1.0 + rate/100), (double)noy) - 1)*100;
System.out.printf (" The principal is %d \n number of years: %d, \nrate is: %f \n The calculated simple interest is:%f\n ", principal,noy,rate,si);
System.out.printf("Accumulated interests: %5.2f\n", d);  // using C_style to define the output of the  double
    }
}

output:
The principal is 1000
number of years: 3,
ate is: 2.500000
The calculated simple interest is:7.500000
Accumulated interests: 7.69

masijade commented: do not simply do other's homework. At the very least [i]explain[/i] the changes. Better, just tell them what to change. They don't learn anything this way. -2
tong1 22 Posting Whiz

Following javaAddict's code, I have replaced the BufferedWriter and FileWriter with BufferedReader and FileReader. In order to get each integer value back, the method of class String split is given the delimiter of a space " ". Please read the method of String split(...) in API. Therefore, for reading the existing file I would like to use the following code. Of course, xterradaniel, you have to parse each token into int type.

BufferedReader rd = null;
	try {
   		rd = new BufferedReader(new FileReader("Exercise09_19.txt"));
		String s="";
		
		while( (s=rd.readLine()) != null){
			String ss[]=s.split(" "); // set up the delimiter as space " "
			for (int i=0; i<ss.length;i++)
		    System.out.print(ss[i] + " ");// The string/token array is printed
		}
		
	} catch (Exception e) {
  	System.out.println(e.getMessage());
	} finally {
	  try {if (rd!=null) rd.close();} catch (Exception e) {}
	}
tong1 22 Posting Whiz

for (double d : numbers) {
total += d;
}

is equivalent to:

for (int i=0; i<numbers.length;i++){
double d = numbers[i];
total += d;
}
tong1 22 Posting Whiz
import java.io.*;
class vowel{
public static void main (String args[])throws IOException{
String sentence;
InputStreamReader isr = new InputStreamReader (System.in);
BufferedReader br = new BufferedReader (isr);
sentence = br.readLine();
System.out.println (vowels(sentence)[0]);
System.out.println (vowels(sentence)[1]);
	}
   static Object[] vowels (String default1){ // return an Object array including various data types
	char ch;
	int vowels_position [] = {0,0,0,0,0};
	char vowels_value [] = {'a','e','i','o','u'};
	for (int i=0; i<default1.length(); i++){
	ch=default1.charAt(i);
	switch (ch) {
	case 'a': case 'A':{vowels_position[0]++;break;}
	case 'e': case 'E':{vowels_position[1]++;break;}
	case 'i': case 'I':{vowels_position[2]++;break;}
	case 'o': case 'O':{vowels_position[3]++;break;}
	case 'u': case 'U':{vowels_position[4]++;break;}
	  }
	}
	int count=0;
	for (int k=0; k<vowels_position.length; k++)
	if (vowels_position[k]>vowels_position[count])
	count=k;
	Object o[]=new Object[2]; // only two different types of elements are needed
	o[0]=vowels_value[count];  // char type element
	o[1]=vowels_position[count]; // int type element
	return o; // return the multi-type Object array
  }
}
Xufyan commented: great :) +0
jon.kiparsky commented: Give help, not code. +0
tong1 22 Posting Whiz

When executing the line of code:
System.out.println(new Final(2));
an address of the instance of the Final is printed as 9cab16 (Final@9cab16)
which tells that the instance of Final is stored at the memory: 9cab16 in hexadecimal system

tong1 22 Posting Whiz

Calling String toString() method shows that
the JVM would dynamically identify the objects of cat, Dog, Duck, and Cow since the array stores their references respectively. Therefore neither casting nor the instanceof operator is needed. An Object array may store a reference of any kind of type.

public class Part5{

	public static void main(String[] args) {
		
		Object[] animals=new Object[4];
		animals[0]=new Cat();
		animals[1]=new Dog();
		animals[2]=new Duck();
		animals[3]=new Cow();
		
		for (Object o:animals)
		System.out.println(o);
	}
}


class Cat {
	public String toString(){
		return "Miyau...";
	}
}
class Dog 
{
	public String toString(){
		return "HowHow....";
	}
}
class Duck {
	public String  toString(){
		return "GAAGAa.....";
	}
}
class Cow {
	public String toString(){
		return "Moooooooo......";
	}
}

output:
Miyau...
HowHow....
GAAGAa.....
Moooooooo......

tong1 22 Posting Whiz

It happends with Chinese characters as well. I think this is probably due to the computer system (windows' config) where your output is printed.

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

Learn from code example

tong1 22 Posting Whiz

Use StringTokenizer in java.util.* to get each word as a token. The delimiters include space character, and other interpunction。

tong1 22 Posting Whiz

Megha SR
Even you have corrected all the errors accordingly you are still unable to run this program.
If you run it, the following error will be printed:
Exception in thread "main" java.lang.NoSuchMethodError: main
You should define a proper main method which requests only one argument: a String array: String args[].
So if you insert the proper main method, for example, as follows, the JVM will interprete it and prints output.

public static void main(String args[]){
	main(2,3,4,5,6);
}
tong1 22 Posting Whiz
tong1 22 Posting Whiz

I do not understand your question. Anyway, I am nocited that
to capture the output in DOS window one may use pipe:
java ABC > data.dat
so that the output by intepreting ABC will be captured/stored in the file data.dat

tong1 22 Posting Whiz

The reason is: the loop body still needs i.
the (i=cis.read(cipherTextBytes)) is consider as the returning value. If the value returned is not -1 the loop continues.

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

Thank you jon for reminding me about keanoppy's intention.
keanoppy, thank you for your try. You may probably put a semicolon after the if (...)line of code so it does not work. I have tested positively.
The code is printed as follows.
keanoppy, if you want to remove the "do" from the three sentenses, one has to write a method to remove the sub string "do" from any string, as I understand, since only single character should be a delimiter.

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

public class AutoTextSumm {
	public static void main(String[] args) {
		String s1;
                String sDelim = ".?! ";
		StringTokenizer str1=new StringTokenizer("i like you very much.i do not hate you!i do.",sDelim);		
		while(str1.hasMoreTokens()) {
                    s1=str1.nextToken();
                    s1=s1.trim();
                    if (s1.compareTo("do")!=0)
                    System.out.print(s1+ " ");
		}
	}
}