I am beginner, why "error: '.class' expected" is appear? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This is a program for calculate the area of triangle that create by six points
and point out what types of triangle.
import java.util.Scanner;
public class assignment {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int m = 0,n = 0;
int[][] x = new int[6][2];
double a,b,c,a1,b1,c1;
String y = "";
System.out.println("Please enter six points,");
for(int i = 0 ; i < x.length ; i++ ){
for(int j = 0 ; j < x[i].length ; j++)
x[i][j] = input.nextInt();
}
for(int i = 0 ; i < 30 ; i++)
System.out.print("--");
System.out.print("\n\t\t\t\tTypes of Triangles\n");
for(int i = 0 ; i < 30 ; i++)
System.out.print("--");
System.out.println();
System.out.println("Point1\t\tPoint2\t\tPoint3\t\tType of Triangle");
for(int i = 0 ; i < 30 ; i++)
System.out.print("--");
System.out.println();
for(int j = 0 ; j < 4 ; j++){
for(int k = j + 1 ; k < 5 ; k++ ){
for(int l = k + 1 ;l < 6 ; l++ ){
a = Math.sqrt(Math.pow((x[j][0]-x[k][0]),2)+Math.pow((x[j][1]-x[k][1]),2));
b = Math.sqrt(Math.pow((x[j][0]-x[l][0]),2)+Math.pow((x[j][1]-x[l][1]),2));
c = Math.sqrt(Math.pow((x[l][0]-x[k][0]),2)+Math.pow((x[l][1]-x[k][1]),2));
c1=Math.max(Math.max(a,b),c);
b1=Math.min(Math.min(a,b),c);
a1=(a+b+c)-c1-b1;
if ( a1 > 0 && b1 > 0 && c1 > 0 && a1 + b1 > c1 && b1 + c1 > a1 && c1 + a1 > b1 ){
if(Math.pow(c1,2) == (Math.pow(b1,2) + Math.pow(a1,2))){
if(a1==b1 || b1==c1 || c1==a1){
y = ("Right-angled\tIsosceles");
}
else if(a1!=b1 && b1!=c1 && c1!=a1){
y = ("Right-angled\tScalene");
}
}
else if(a1==b1 || b1==c1 || c1==a1){
y = ("Isosceles");
}
else if(a1!=b1 && b1!=c1 && c1!=a1){
y=("Scalene");
}
}
else{
y = ("Non-triangle");
}
System.out.println("(" + x[j][0] + "," + x[j][1]+ ")\t\t" + "(" + x[k][0] + "," + x[k][1] + ")\t\t" + "(" + x [l][0] + "," + x[l][1]+")\t\t" + y );
}
}
}
System.out.print("Maximum area of triangle =" + Math.max(area()));
System.out.print("Maximum area of triangle =" + Math.min(area()));
}
public static double area(double[][] n){
double s = 0;
int i;
for(int j = 0 ; j < 4 ; j++){
for(int k = j + 1 ; k < 5 ; k++ ){
for(int l = k + 1 ;l < 6 ; l++ ){
a = Math.sqrt(Math.pow((x[j][0]-x[k][0]),2)+Math.pow((x[j][1]-x[k][1]),2));
b = Math.sqrt(Math.pow((x[j][0]-x[l][0]),2)+Math.pow((x[j][1]-x[l][1]),2));
c = Math.sqrt(Math.pow((x[l][0]-x[k][0]),2)+Math.pow((x[l][1]-x[k][1]),2));
s = (a+b+c)/2;
n[i][0] = Math.sqrt(s * (s-a) * (s-b) * (s-c));
i++;
}
}
}
return n[][];
}
}
I have got a error: '.class' expected,
I am a beginner ,can someone help me please?
thx a lot

There are quite a few problems with the code you posted. Things like assigning to undefined variables such as the following in the area method:
a = Math.sqrt(Math.pow((x[j][0]-x[k][0]),2)+Math.pow((x[j][1]-x[k][1]),2));
You're also referencing the variable x in that statement which is not the correct variable name. The return type and value returned don't match, and there's a syntax problem in the return.
A lot of these problems will be pointed out using an IDE like Eclipse. I think you would do yourself a favor to learn coding in Eclipse.
Here is a revision of your code that runs. I'm not sure about correctness of what you're trying to do:
public class assignment {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int m = 0, n = 0;
int[][] x = new int[6][2];
double a, b, c, a1, b1, c1;
String y = "";
System.out.println("Please enter six points,");
for (int i = 0; i < x.length; i++) {
for (int j = 0; j < x[i].length; j++)
x[i][j] = input.nextInt();
}
for (int i = 0; i < 30; i++)
System.out.print("--");
System.out.print("\n\t\t\t\tTypes of Triangles\n");
for (int i = 0; i < 30; i++)
System.out.print("--");
System.out.println();
System.out.println("Point1\t\tPoint2\t\tPoint3\t\tType of Triangle");
for (int i = 0; i < 30; i++)
System.out.print("--");
System.out.println();
for (int j = 0; j < 4; j++) {
for (int k = j + 1; k < 5; k++) {
for (int l = k + 1; l < 6; l++) {
a = Math.sqrt(Math.pow((x[j][0] - x[k][0]), 2) + Math.pow((x[j][1] - x[k][1]), 2));
b = Math.sqrt(Math.pow((x[j][0] - x[l][0]), 2) + Math.pow((x[j][1] - x[l][1]), 2));
c = Math.sqrt(Math.pow((x[l][0] - x[k][0]), 2) + Math.pow((x[l][1] - x[k][1]), 2));
c1 = Math.max(Math.max(a, b), c);
b1 = Math.min(Math.min(a, b), c);
a1 = (a + b + c) - c1 - b1;
if (a1 > 0 && b1 > 0 && c1 > 0 && a1 + b1 > c1 && b1 + c1 > a1 && c1 + a1 > b1) {
if (Math.pow(c1, 2) == (Math.pow(b1, 2) + Math.pow(a1, 2))) {
if (a1 == b1 || b1 == c1 || c1 == a1) {
y = ("Right-angled\tIsosceles");
} else if (a1 != b1 && b1 != c1 && c1 != a1) {
y = ("Right-angled\tScalene");
}
} else if (a1 == b1 || b1 == c1 || c1 == a1) {
y = ("Isosceles");
} else if (a1 != b1 && b1 != c1 && c1 != a1) {
y = ("Scalene");
}
} else {
y = ("Non-triangle");
}
System.out.println("(" + x[j][0] + "," + x[j][1] + ")\t\t" + "(" + x[k][0] + "," + x[k][1] + ")\t\t" + "(" + x[l][0] + "," + x[l][1] + ")\t\t" + y);
}
}
}
System.out.print("Maximum area of triangle =" + area(x));
//System.out.print("Maximum area of triangle =" + Math.min(area(x)));
}
public static double area(int[][] n) {
double s = 0;
double max = 0;
for (int j = 0; j < 4; j++) {
for (int k = j + 1; k < 5; k++) {
for (int l = k + 1; l < 6; l++) {
double a = Math.sqrt(Math.pow((n[j][0] - n[k][0]), 2) + Math.pow((n[j][1] - n[k][1]), 2));
double b = Math.sqrt(Math.pow((n[j][0] - n[l][0]), 2) + Math.pow((n[j][1] - n[l][1]), 2));
double c = Math.sqrt(Math.pow((n[l][0] - n[k][0]), 2) + Math.pow((n[l][1] - n[k][1]), 2));
s = (a + b + c) / 2;
if (s > max) {
max = s;
}
}
}
}
return max;
}
}

Related

Java for loop I want to print the result the same way that i print the numbers that i use

I want to print the result the same way that i print the numbers that i use.
for ex i print 1,2,3,4 2,3,4,5 but the pow remains the same 1024,1024,1024,1024.
public static void main(String[] args) {
int d = 0, e = 0;
double c = 0;
for (int a = 1; a < 5; a++) {
d = a;
for (int b = 2; b < 6; b++) {
c = java.lang.Math.pow(a, b);
}
}
for (int a = 1, b = 2; a < 5; a++, b++) {
d = a;
e = b;
System.out.println(d + " " + e + " " + c);
}
}
This should work, and is also more readable.(you really ought to indent code properly).
Your problem is in the loop logic.
What you are doing is probably possible with for loops, but i think a while loop with two conditionals would work nice.
int a = 1;
int b = 2;
double c = 0.0;
while (a < 5 && b < 6){
c=java.lang.Math.pow (a,b);
System.out.println ( a+ " " +b +" " + c);
b++;
a++;
}
public static void main(String[] args) {
int d = 0, e = 0;
double c = 0;
for (int a = 1; a < 5; a++) {
for (int b = 2; b < 6; b++) {
c = java.lang.Math.pow(a, b);
System.out.println(a + " " + b + " " + c);
}
}
}
If I understood your problem try something like this output should be ok

Battleship Code Too Many Hits

This project was to make a 2d battleship project using arrays. If you hit, it makes an "X." If it's one slot away up, down, right, or left, it is "H" for hot. If it's two slots away, it's "W" for warm. "C" for cool for three slots, and miss for everything else.
Every time I go to test out my code, it works for the first time perfectly fine, but afterwards it marks every input as a hit, when it should mark it as "H", "W", "C", or "M."
import java.util.Scanner;
public class Battleship
{
public static void main ()
{
int rowLoc = 0;
int colLoc = 0;
int rowGuess;
int colGuess;
int guesses = 1;
int shipNum = 5;
//variable declaration
String[][] battleGrid = new String[10][10];
String[][] battleGridKnown = new String[10][10];
//grid declaration
System.out.println("Welcome to Battleship!\nFive ships are hidden in row 0-9 and columns 0-9.");
System.out.println("After each guess, you will been told if your guess was...");
System.out.println("- Hit (X)\n- Close (H for hot)\n- Somewhat close (W for warm)\n- Not that close (C for cool)\n- Miss (M).");
//welcome message
for (int r = 0; r < battleGrid.length; r++)
{
for (int c = 0; c < battleGrid[r].length; c++)
{
battleGrid[r][c] = "-";
}
}
//initializes what is in battleGrid by default
for (int r = 0; r < battleGridKnown.length; r++)
{
for (int c = 0; c < battleGridKnown[r].length; c++)
{
battleGridKnown[r][c] = "-";
}
}
//initializes what is in battleGridKnown by default
for (int k = 1; k <= shipNum; k++)
{
do
{
rowLoc = (int)(Math.random() * 10 + 0);
colLoc = (int)(Math.random() * 10 + 0);
} while(battleGrid[rowLoc][colLoc] == "S");
battleGrid[rowLoc][colLoc] = "S";
}
//sets ships and also the stuff around the ships
/*for (int r = 0; r < battleGrid.length; r++)
{
for (int c = 0; c < battleGrid[r].length; c++)
{
System.out.print(battleGrid[r][c] + "");
}
System.out.println("");
}
System.out.println("");
//test printer*/
while(shipNum > 0)
{
System.out.print("Enter your row guess (0-9): ");
Scanner in = new Scanner (System.in);
rowGuess = in.nextInt();
System.out.print("Enter your column guess (0-9): ");
colGuess = in.nextInt();
// enter row + column guesses
if (battleGrid[rowGuess][colGuess] == battleGrid[rowLoc][colLoc])
{
shipNum--;
battleGridKnown[rowGuess][colGuess] = "X";
System.out.println("Hit! There are " + shipNum + " ships remaining.");
System.out.println("Guess attempt number: " + guesses + ".");
for (int r = 0; r < battleGridKnown.length; r++)
{
for (int c = 0; c < battleGridKnown[r].length; c++)
{
System.out.print(battleGridKnown[r][c] + "");
}
System.out.println("");
}
System.out.println("");
}
else if(rowGuess == rowLoc-- || rowGuess == rowLoc++ || colGuess == colLoc-- || colGuess == colLoc++)
{
battleGridKnown[rowGuess][colGuess] = "H";
System.out.println("Hot!");
System.out.println("Guess attempt number: " + guesses + ".");
for (int r = 0; r < battleGridKnown.length; r++)
{
for (int c = 0; c < battleGridKnown[r].length; c++)
{
System.out.print(battleGridKnown[r][c] + "");
}
System.out.println("");
}
System.out.println("");
}
else if(rowGuess == rowLoc - 2 || rowGuess == rowLoc + 2 || colGuess == colLoc - 2 || colGuess == colLoc + 2)
{
System.out.println("Warm...");
battleGridKnown[rowGuess][colGuess] = "W";
System.out.println("Guess attempt number: " + guesses + ".");
for (int r = 0; r < battleGridKnown.length; r++)
{
for (int c = 0; c < battleGridKnown[r].length; c++)
{
System.out.print(battleGridKnown[r][c] + "");
}
System.out.println("");
}
System.out.println("");
}
else if(rowGuess == rowLoc - 3 || rowGuess == rowLoc + 3 || colGuess == colLoc - 3 || colGuess == colLoc + 3)
{
System.out.println("Cool...");
battleGridKnown[rowGuess][colGuess] = "C";
System.out.println("Guess attempt number: " + guesses + ".");
for (int r = 0; r < battleGridKnown.length; r++)
{
for (int c = 0; c < battleGridKnown[r].length; c++)
{
System.out.print(battleGridKnown[r][c] + "");
}
System.out.println("");
}
System.out.println("");
}
else
{
System.out.println("Miss.");
System.out.println("Guess attempt number: " + guesses + ".");
for (int r = 0; r < battleGridKnown.length; r++)
{
for (int c = 0; c < battleGridKnown[r].length; c++)
{
battleGridKnown[rowGuess][colGuess] = "M";
System.out.print(battleGridKnown[r][c] + "");
}
System.out.println("");
}
System.out.println("");
}
guesses++;
}
System.out.println("Thank you for playing!\nYou found all the ships in " + guesses + " guesses.");
}
}

How do I print out factors of an input using loops?

Here is my mess of a code. I have to write a program that inputs a positive integer greater than 3. Validate that the integer is in fact greater than 3. Then print all possible pairs of positive integers great than whose product is less than or equal to the number entered.
ex. If 24 is the input.
It would print:
4 = 2 x 2
6 = 2 x 3
8 = 2 x 4
10 = 2 x 5
12 = 2 x 6
14 = 2 x 7
16 = 2 x 8....
9 = 3 x 3
12 = 3 x 4..
24 = 3 x 8...
all the way to
24 = 4 x 6
import java.util.Scanner;
public class Factors {
public static void main(String[] args) {
// Define Variables
Scanner input = new Scanner(System.in);
int i = 0;
int j = 0;
int k = 2;
int product = 0;
// Ask for input/loop
while (i < 3) {
System.out.println("Please enter an integer greater than 3");
i = input.nextInt();
}
while (product < i) {
if (product == i) { j++; k = 2;
for (j = 2; product < i; k++) {
product = j * k;
System.out.println(product + " = " + j + " x " + k);
if (product == i) { j++; k = 2;
}
}
}
}
}
}
public class Factors {
public static void main(String[] args) {
// Define Variables
Scanner input = new Scanner(System.in);
int i = 0;
int product = 0;
// Ask for input/loop
while (i < 3) {
System.out.println("Please enter an integer greater than 3");
i = input.nextInt();
}
for (int j = 2; j < i / 2; j++) {
for (int k = 2; k < i / 2; k++) {
if (j <= k && j * k <= i)
System.out.println(j * k + " = " + j + "*" + k);
}
}
// while (product < i) {
// if (product == i) {
// j++;
// k = 2;
// for (j = 2; product < i; k++) {
// product = j * k;
// System.out.println(product + " = " + j + " x " + k);
// if (product == i) {
// j++;
// k = 2;
// }
// }
// }
// }
}
}

Making a hollow diamond with a word in it

What I need is a little modification to my code so that every part of my hollow diamond prints a letter of the word "HURRICANE"
My code is:
String st1 = "HURRICANE";
int a = 0;
for (int i = 5; i >= 1; i--) {
for (int j = 1; j <= 9; j++) {
if (j == i || (10 - i) == j) {
System.out.print(st1.charAt(a)); //needs change
} else {
System.out.print(' ');
}
}
System.out.println();
}
for (int i = 2; i <= 5; i++) {
for (int j = 1; j <= 9; j++) {
if (j == i || (10 - i) == j) {
System.out.print(st1.charAt(a)); //needs change
} else {
System.out.print(' ');
}
}
System.out.println();
}
The output comes out as:
H
H H
H H
H H
H H
H H
H H
H H
H
I need to modify my "charAt" statement a little so it comes out to be:
H
U U
R R
R R
I I
C C
A A
N N
E
How should I make my print statement?
It's worth noting that the example provided only works for Strings the same length as "HURRICANE". A superior solution would work for all strings.
Partial solution for you to complete, since I guess it's your coursework and I don't want you to copy / paste / fail exams :P
public static void main(String[] args) {
String st1 = "HURRICANE";
char[] st1CharArray = st1.toCharArray();
int maxSpaces = st1CharArray.length / 2 + 1;
for (int i = 0; i <= st1CharArray.length / 2; i++) {
if (i == 0) {
System.out.println(getSpacesString(maxSpaces) + st1CharArray[i]);
} else {
System.out.println(getSpacesString(maxSpaces - i)
+ st1CharArray[i] + getSpacesString(i * 2 - 1)
+ st1CharArray[i]);
}
}
// Loop from st1CharArray.length / 2 + 1 and get the second half done.
}
private static String getSpacesString(int numberOfSpaces) {
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < numberOfSpaces; i++) {
strBuilder.append(" ");
}
return strBuilder.toString();
}
//: Playground - noun: a place where people can play
import UIKit
var name : String = "HURRICANE"
var dimensions : Int = name.count - 1
var k : Int = 0
for rows in 0...dimensions{
for columns in 0...dimensions{
k = abs( (dimensions/2) - rows )
if columns == k || columns == dimensions - k{
print(Array(name)[rows], terminator: "")
}
else{
print(" ", terminator: "" )
}
}
print("")
}
String st1 = "HURRICANE";
int a = 0;
for (int i = 5; i >= 1; i--) {
for (int j = 1; j <= 9; j++) {
if (j == i || (10 - i) == j) {
System.out.print(st1.charAt(5 - i));
} else {
System.out.print(' ');
}
}
System.out.println();
}
for (int i = 2; i <= 5; i++) {
for (int j = 1; j <= 9; j++) {
if (j == i || (10 - i) == j) {
System.out.print(st1.charAt(3 + i));
} else {
System.out.print(' ');
}
}
System.out.println();
}
Let's assume that a word has an odd number of characters, otherwise we get a crooked diamond.
Try it online!
public static void main(String[] args) {
String str = "abrahadabra";
int n = str.length() / 2;
for (int i = -n, ch = 0; i <= n && ch < str.length(); i++, ch++) {
for (int j = -n; j <= n; j++)
if (Math.abs(i) + Math.abs(j) == n)
System.out.print(str.charAt(ch));
else
System.out.print(" ");
System.out.println();
}
}
Output:
a
b b
r r
a a
h h
a a
d d
a a
b b
r r
a

Rectangular/lattice multiplication

I am trying to implement the rectangular/lattice multiplication in Java. For those who don't know, this is a short tutorial.
I tried some methods wherein I used a single array to store multiplication of two digits and sigma-append zeroes to it. Once all the numbers are multiplied, I pick two elements from the array and then add the sigma value and fetch two more numbers and again perform the same thing until all the numbers are fetched.
The logic works fine but I am not able to find the exact number of zeroes that I should maintain, since for every different set of numbers (4 digits * 3 digits) I get different number of zeroes.
Could somebody please help?
I liked the tutorial, very neat. So I wanted to implement it, but not do your project work. So I came up with a lousy, quick and dirty implementation, violating many of the design rules I practice myself. I used arrays to save the digit by digit multiplication results, and pretty much followed what the tutorial said. I never have had to count the number of 0's, and I am not sure what is sigma-appending, so I cannot answer that. Lastly, there is a bug in the code which shows up when the 2 numbers have a different count of digits. Here is the source code - feel free to edit and use any part. I think an easy fix would be to prepend 0's to the smaller number to make the digit count the same for the 2 numbers, and not to display the corresponding row/columns. More bookkeeping, but thats up to you.
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Lattice extends JPanel implements ActionListener {
protected Font axisFont, rectFont, carrFont;
protected Color boxColor = new Color (25, 143, 103), gridColor = new Color (78, 23, 211),
diagColor = new Color (93, 192, 85), fontColor = new Color (23, 187, 98),
carrColor = new Color (162, 34, 19);
protected int nDigitP, nDigitQ, dSize = 60,
m1, m2, lastCarry, iResult[],
xDigits[], yDigits[], prodTL[][], prodBR[][];
public Lattice (int p, int q, Font font) {
nDigitP = (int) Math.ceil (Math.log10 (p)); xDigits = new int[nDigitP];
nDigitQ = (int) Math.ceil (Math.log10 (q)); yDigits = new int[nDigitQ];
prodTL = new int[nDigitP][nDigitQ]; prodBR = new int[nDigitP][nDigitQ];
m1 = p; m2 = q; // To display in report
int np = p, nq = q, size = font.getSize(); // Save the digits in array
for (int i = 0 ; i < nDigitP ; i++) {
xDigits[i] = np % 10;
np /= 10;
}
for (int i = 0 ; i < nDigitQ ; i++) {
yDigits[i] = nq % 10;
nq /= 10;
}
for (int i = 0 ; i < nDigitP ; i++) { // Cell products as upper/lower matrix
for (int j = 0 ; j < nDigitQ ; j++) {
int prod = xDigits[i] * yDigits[j];
prodTL[i][j] = prod / 10;
prodBR[i][j] = prod % 10;
}}
axisFont = font.deriveFont (Font.PLAIN, size+8.0f);
rectFont = font.deriveFont (Font.PLAIN, size+4.0f);
carrFont = font.deriveFont (Font.PLAIN);
setPreferredSize (new Dimension ((nDigitP+2)*dSize, (nDigitQ+2)*dSize));
}
public void paint (Graphics g) {
int w = getWidth(), h = getHeight();
Graphics2D g2 = (Graphics2D) g; // To make diagonal lines smooth
g2.setPaint (Color.white);
g2.fillRect (0,0,w,h);
int dx = (int) Math.round (w/(2.0+nDigitP)), // Grid spacing to position
dy = (int) Math.round (h/(2.0+nDigitQ)); // the lines and the digits
g2.setRenderingHint (RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint (RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.setFont (axisFont);
FontMetrics fm = g2.getFontMetrics();
for (int i = 0 ; i < nDigitP ; i++) { // Grid || Y-axis and labels on axis
int px = w - (i+1)*dx;
g2.setPaint (gridColor);
if (i > 0)
g2.drawLine (px, dy, px, h-dy);
String str = /*i + */"" + xDigits[i];
int strw = fm.stringWidth (str);
g2.setPaint (fontColor);
g2.drawString (str, px-dx/2-strw/2, 4*dy/5);
}
for (int i = 0 ; i < nDigitQ ; i++) { // Grid || X-axis and labels on axis
int py = h - (i+1)*dy;
g2.setPaint (gridColor);
if (i > 0)
g2.drawLine (dx, py, w-dx, py);
String str = /*i + */"" + yDigits[i];
int strw = fm.stringWidth (str);
g2.setPaint (fontColor);
g2.drawString (str, w-dx+2*dx/5-strw/2, py-dy/2+10);
}
g2.setFont (rectFont);
fm = g2.getFontMetrics(); // Upper/Lower traingular product matrix
for (int i = 0 ; i < nDigitP ; i++) {
for (int j = 0 ; j < nDigitQ ; j++) {
int px = w - (i+1)*dx;
int py = h - (j+1)*dy;
String strT = "" + prodTL[i][j];
int strw = fm.stringWidth (strT);
g2.drawString (strT, px-3*dx/4-strw/2, py-3*dy/4+5);
String strB = "" + prodBR[i][j];
strw = fm.stringWidth (strB);
g2.drawString (strB, px-dx/4-strw/2, py-dy/4+5);
}}
g2.setFont (axisFont);
fm = g2.getFontMetrics();
int carry = 0;
Vector cVector = new Vector(), iVector = new Vector();
for (int k = 0 ; k < 2*Math.max (nDigitP, nDigitQ) ; k++) {
int dSum = carry, i = k/2, j = k/2;
//System.out.println ("k="+k);
if ((k % 2) == 0) { // even k
if (k/2 < nDigitP && k/2 < nDigitQ)
dSum += prodBR[k/2][k/2];
// go right and top
for (int c = 0 ; c < k ; c++) {
if (--i < 0)
break;
if (i < nDigitP && j < nDigitQ)
dSum += prodTL[i][j];
//System.out.println (" >> TL (i,j) = (" + i+","+j+")");
if (++j == nDigitQ)
break;
if (i < nDigitP && j < nDigitQ)
dSum += prodBR[i][j];
//System.out.println (" >> BR (i,j) = (" + i+","+j+")");
}
// go bottom and left
i = k/2; j = k/2;
for (int c = 0 ; c < k ; c++) {
if (--j < 0)
break;
if (i < nDigitP && j < nDigitQ)
dSum += prodTL[i][j];
//System.out.println (" >> TL (i,j) = (" + i+","+j+")");
if (++i == nDigitP)
break;
if (i < nDigitP && j < nDigitQ)
dSum += prodBR[i][j];
//System.out.println (" >> BR (i,j) = (" + i+","+j+")");
}} else { // odd k
if (k/2 < nDigitP && k/2 < nDigitQ)
dSum += prodTL[k/2][k/2];
// go top and right
for (int c = 0 ; c < k ; c++) {
if (++j == nDigitQ)
break;
if (i < nDigitP && j < nDigitQ)
dSum += prodBR[i][j];
//System.out.println (" >> BR (i,j) = (" + i+","+j+")");
if (--i < 0)
break;
if (i < nDigitP && j < nDigitQ)
dSum += prodTL[i][j];
//System.out.println (" >> TL (i,j) = (" + i+","+j+")");
}
i = k/2; j = k/2;
// go left and bottom
for (int c = 0 ; c < k ; c++) {
if (++i == nDigitP)
break;
if (i < nDigitP && j < nDigitQ)
dSum += prodBR[i][j];
//System.out.println (" >> BR (i,j) = (" + i+","+j+")");
if (--j < 0)
break;
if (i < nDigitP && j < nDigitQ)
dSum += prodTL[i][j];
//System.out.println (" >> TL (i,j) = (" + i+","+j+")");
}}
int digit = dSum % 10; carry = dSum / 10;
cVector.addElement (new Integer (carry));
iVector.addElement (new Integer (digit));
String strD = "" + digit;
int strw = fm.stringWidth (strD);
if (k < nDigitP) {
int px = w - (k+1)*dx - 4*dx/5, py = h-dy + fm.getHeight();
g2.drawString (strD, px-strw/2, py);
} else {
int px = dx - 12, py = h - (k-nDigitP+1)*dy - dy/4;
g2.drawString (strD, px-strw/2, py+5);
}} // End k-loop
g2.setPaint (diagColor);
for (int i = 0 ; i < nDigitP ; i++) {
int xt = (i+1) * dx,
yb = (i+2) * dy;
g2.drawLine (xt, dy, 0, yb);
}
for (int i = 0 ; i < nDigitQ ; i++) {
int xb = (i + nDigitP - nDigitQ) * dx,
yr = (i+1) * dy;
g2.drawLine (w-dx, yr, xb, h);
}
// System.out.println ("carry Vector has " + cVector.size() + " elements");
g2.setFont (carrFont);
g2.setPaint (carrColor);
fm = g2.getFontMetrics();
for (int k = 0 ; k < 2*Math.max (nDigitP, nDigitQ) ; k++) {
carry = ((Integer) cVector.elementAt (k)).intValue();
lastCarry = carry; // To display
if (carry == 0)
continue;
String strC = "" + carry;
int strw = fm.stringWidth (strC),
px = w-dx-5-strw/2, // Const X while going Up
py = dy + fm.getHeight(); // Const Y while going Left
if (k < (nDigitQ-1))
py = h-(k+3)*dy + dy/5 + fm.getHeight();
else
px = w - (k-nDigitQ+2) * dx - dx/2 - strw/2;
g2.drawString (strC, px, py);
}
int n = iVector.size(); // Save the vector content to display later
iResult = new int[n];
for (int i = 0 ; i < n ; i++)
iResult[i] = ((Integer) iVector.elementAt (n-i-1)).intValue();
g2.setPaint (boxColor); g2.drawRect (dx, dy, w-2*dx, h-2*dy);
}
private void displayResults () {
StringBuffer sb = new StringBuffer ("Lattice: " + m1 + " \u00D7 " + m2 + " = " +
((lastCarry == 0) ? "" : (""+lastCarry)));
for (int k = 0 ; k < iResult.length ; k++)
sb.append ("" + iResult[k]);
// System.out.println (sb.toString());
JOptionPane.showMessageDialog (null, sb.toString(), "Lattice Multiplier",
JOptionPane.INFORMATION_MESSAGE);
}
public JPanel getButtonPanel () {
JPanel bp = new JPanel(new GridLayout (1,bNames.length));
for (int i = 0 ; i < bNames.length ; i++) {
JButton b = new JButton (bNames[i]);
b.addActionListener (this);
bp.add (b);
}
return bp;
}
private final static String[] bNames = {"Close", "Result"};
public void actionPerformed (ActionEvent e) {
String cmd = e.getActionCommand();
if (cmd.equals (bNames[0])) System.exit (0);
else if (cmd.equals (bNames[1])) displayResults();
}
public static void main (String[] args) {
JTextField tf1 = new JTextField (), tf2 = new JTextField();
JPanel num2m = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets (2,2,2,2);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = GridBagConstraints.RELATIVE;
gbc.anchor = GridBagConstraints.EAST;
JLabel
label = new JLabel ("Multiplicand", JLabel.TRAILING); num2m.add (label, gbc);
label = new JLabel ("Multiplier", JLabel.TRAILING); num2m.add (label, gbc);
gbc.gridx++;
gbc.weightx = 1.0f; num2m.add (tf1, gbc); num2m.add (tf2, gbc);
JFrame lf = new JFrame ("Lattice Multiplication");
if (JOptionPane.showConfirmDialog (lf, num2m, "Enter numbers to multiply",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE ) == JOptionPane.OK_OPTION) {
try {
int m = Integer.parseInt (tf1.getText()), n = Integer.parseInt (tf2.getText());
Lattice lattice = new Lattice (m, n, label.getFont());
lf.add (lattice.getButtonPanel(), "South");
lf.add (lattice, "Center");
lf.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
lf.pack();
lf.setVisible (true);
} catch (NumberFormatException nex) {
JOptionPane.showMessageDialog (lf, "Invalid numbers to multiply",
"Lattice Multiplier Error", JOptionPane.ERROR_MESSAGE);
System.exit (1);
}} else { System.exit (2);
}}}
this works for any set of numbers..2 digit multiplicand with 4 digit multiplier..etc..
if(numberM.length()!=numberN.length()){
int mLen = numberM.length();
int nLen = numberN.length();
if(numberM.length()>numberN.length()){
for(int i=0;i<mLen-nLen;i++){
numberN = "0" + numberN;
}
}
else
{
for(int i=0;i<nLen-mLen;i++){
numberM = "0" + numberM;
}
}
}
int result[] = new int[numberN.length()+numberM.length()];
String numberRN = new StringBuffer(numberN).reverse().toString();
String numberRM = new StringBuffer(numberM).reverse().toString();
//reversing the number
int n[] = new int[numberN.length()];
int m[] = new int[numberM.length()];
int size_of_array = 0;
for(int i=0;i<numberN.length();i++){
n[i] = Integer.parseInt((new Character(numberRN.charAt(i))).toString());
m[i] = Integer.parseInt((new Character(numberRM.charAt(i))).toString());
}
//System.out.println("Numbers are:");
//displayArray(n,"n");
//displayArray(m,"m");
size_of_array = (m.length*2)*2;
int soa = size_of_array;
int tempArray[] = new int[size_of_array*m.length];
//System.out.println("Size of tempArray ="+tempArray.length);
//placing the numbers in a single array
int oddValue =3;
int index = 0;
tempArray[index++] = 0;
for(int i=0;i<m.length;i++){
for(int j=0;j<n.length;j++){
//System.out.println("n["+j+"]="+n[j]+" and m["+i+"]="+m[i]);
tempArray[index++] = (n[j] * m[i]) % 10;
tempArray[index] = (n[j] * m[i]) / 10;
//System.out.println("tempArray["+(index-1)+"]="+tempArray[index-1]+" tempArray["+(index)+"]="+tempArray[index]);
index++;
}
//System.out.println("index before appending zero="+index);
size_of_array=(i+1)*soa;
index = size_of_array;
//System.out.println("index after appending zero="+index);
//index+=i+oddArray[i];
index+=i+oddValue;
oddValue++;
//System.out.println("After move index="+index);
}
//System.out.println("tempArray full");
//displayArray(tempArray,"tempArray");
//adding the numbers and also dealing with carry
int count=0;int ind = 0;int res = 0;int carry =0;int tempInd = 0;
for(int i=0;i<m.length*2;i++){
tempInd = ind;
for(int k=0;k<m.length;k++){
//System.out.println(tempArray[ind]+"---"+tempArray[ind+1]);
res = tempArray[ind] + tempArray[ind+1] + res + carry;
ind = ind + soa ;
carry = 0;
//System.out.println("res="+res+" ind="+ind+" soa="+soa);
}
//System.out.println("----------------");
result[count++] = res %10;
carry = res /10;
res = 0;
ind = tempInd+2;
}
//displayArray(result,"result");
displayResult(result,sign);
}
private static void displayResult(int[] result,String sign) {
System.out.print("The result is "+sign);
for(int i=result.length-1;i>=0;i--){
System.out.print(result[i]);
}
}
static void displayArray(int tempArray[],String name){
for(int k =0;k<tempArray.length;k++)
System.out.print(" "+name+"["+k+"]-"+tempArray[k]);
System.out.println("");
}

Categories