I'm trying to write a code that multiplies two strings of integers. I'm not too sure where it's going wrong... It works for some numbers, but is horribly wrong for others. I'm not asking for a full solution, but just a hint (I seriously appreciate any help possible) as to where I'm making the obviously silly mistake. Thanks in advance.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Please enter a big integer. ");
String t = scan.nextLine();
System.out.print("And another. ");
String s = scan.nextLine();
BigInt a = new BigInt(t);
BigInt b = new BigInt(s);
System.out.println(a + " + " + b + " = " + a.add(b));
System.out.println(a + " - " + b + " = " + a.sub(b));
System.out.println(a + " * " + b + " = " + a.mul(b));
System.out.println(a + " / " + b + " = " + a.div(b));
}
}
class BigInt {
public BigInt() {
n = new int[1];
}
public BigInt(String s) {
n = new int[s.length()];
for (int i = 0; i < n.length; ++i) {
n[n.length - i - 1] = s.charAt(i) - '0' ;
}
}
private BigInt(int[] n) {
this.n = new int[n.length];
for (int i = 0; i < n.length; ++i) {
this.n[i] = n[i];
}
}
public String toString() {
String s = "";
for (int i : n) {
s = i + s;
}
return s;
}
public BigInt mul(BigInt o) {
int carry = 0;
int s = 0;
int digit;
int subtotal = 0;
int total = 0;
int max = n.length > o.n.length ? n.length : o.n.length;
int[] result = new int[n.length + o.n.length];
for (int i = 0; i < o.n.length; ++i) {
int bottom = i <= o.n.length ? o.n[i] : 0;
for (s = 0; s <= n.length; ++s){
int top = s < n.length ? n[s] : 0;
int prod = (top * bottom + carry);
if (s == (max-1)) {
total = Integer.valueOf((String.valueOf(prod) + String.valueOf(subtotal)));
carry = 0;
digit = 0;
subtotal = 0;
break;
}
if (prod < 10) {
digit = prod;
subtotal += digit;
carry = 0;
}
if (prod >= 10); {
digit = prod % 10;
carry = prod / 10;
subtotal += digit;
}
}
result[i] = total;
}
return new BigInt(trim(result));
}
private int[] trim(int[] nums) {
int size = nums.length;
for (int i = nums.length - 1; i > 0; --i) {
if (nums[i] != 0) {
break;
}
--size;
}
int[] res = new int[size];
for (int i = 0; i < size; ++i) {
res[i] = nums[i];
}
return res;
}
private int[] n;
}
A quick test using:
for (int x = 0; x < 10; x++) {
for (int y = 0; y < 10; y++) {
System.out.println(x + " * " + y + " = " + new BigInt(Integer.toString(x)).mul(new BigInt(Integer.toString(y))));
}
}
demonstrates that somehow your multiply of x * y is actually multiplying by 10x * y. That should give you a clear hint to the problem.
Related
The code shows:
java.util.IllegalFormatConversionException: d != java.lang.String at
java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4302)
at
java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2793)
at java.util.Formatter$FormatSpecifier.print(Formatter.java:2747) a
public class addiePorterMod10Sieve {
void sieveOfEratosthenes(int n) {
boolean prime[] = new boolean[n + 1];
for (int i = 0; i < n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++) {
if (prime[p] == true) {
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
for (int i = 2; i <= n; i++) {
if (prime[i] == true)
System.out.printf(i + "%-1s %-15n", " ");
}
}
public static void main(String args[]) {
int n = 1000;
addiePorterMod10Sieve g = new addiePorterMod10Sieve();
g.sieveOfEratosthenes(n);
}
}
Not very familiar with formatter myself, but the below workaround should achieve what you need as ouput :
int linecount = 0;
for(int i = 2; i <= n; i++)
{
if(prime[i] == true) {
// System.out.printf(i + "%-1s %-15d", " ");
linecount++;
System.out.print(i + " ");
if (linecount == 15) {
linecount =0;
System.out.println();
}
}
}
The error derives from %'s matching with a parameter.
int p = 0;
String nl = "\r\n";
for (int i = 2; i <= n; i++) {
if (prime[i]) {
++p;
System.out.printf("%-15d ", i);
if (p % 10 == 0) {
System.out.println();
}
//System.out.printf("%-15d%s", i, (p % 10 == 0 ? nl : " "));
}
}
Now %n would indeed yield a newline ("\r\n" on Windows, "\n" on Linux) with a flush of the line. However you must place it in the format string,
My out-commented alternative misses immediate flushing to the console.
I am new to java trying to use methods from my Histogram class (Which implements a histogram interface) into a main method which reads a file and uses the first digit of each integer to create a histogram.
My histogram class looks like this
public class Histogram implements HistogramInterface
{
protected int min, max;
protected int[] counts;
public Histogram(int min, int max)
{
this.min = min;
this.max = max;
counts = new int[max - min + 1];
}
public Histogram(int max)
{
this.min = 1;
this.max = max;
counts = new int[max - min + 1];
}
public void submit(int i) throws HistogramOutOfBoundsException
{
if ((min <= i) && (i <= max))
counts[i-min] += 1;
else
{
String message = "\n*******\n";
message += "Submitted value " + i + " is outside range [";
message += min + "," + max + "]" + " of Histogram.\n";
message += "*******\n";
throw new HistogramOutOfBoundsException(message);
}
}
public String toString()
{
int weight; // value of a single *
int num; // number of *'s to print
// calculate weight
int highIndex = 0;
for (int i = 1; i < counts.length; i++)
if (counts[highIndex] < counts[i])
highIndex = i;
weight = ((counts[highIndex] - 1) / MAXWIDTH) + 1;
// create "header"
String histoString ="\n";
if (weight != 1)
histoString += "* = approximately " + weight + " occurrences\n\n";
// create histogram
for (int i = 0; i <= max - min; i++)
{
histoString += String.format("%4d",(i + min)) + ": ";
if (counts[i] == 0)
num = 0;
else
num = ((counts[i] - 1) / weight ) + 1;
for (int j = 0; j < num; j++)
histoString += "*";
histoString += "\n";
}
return histoString;
}
}
And the class Reader which I'm struggling with
import java.util.*;
import java.io.*;
public class Reader {
public static void main(String[] args) {
int min = 1;
int max = 9;
Histogram x = new Histogram(min, max);
int firstNum;
int digits;
int num = 0;
int weight = 20;
Scanner scan;
File file = new File("Data.txt");
try
{
scan = new Scanner(file);
while(scan.hasNextLine()){
digits = scan.nextInt();
firstNum = Integer.parseInt(Integer.toString(digits).substring(0,1));
digits++;
}
}
catch(Exception e)
{
}
}
}
I think you're looking for something like:
try {
scan = new Scanner(file);
while(scan.hasNextLine()){
digits = scan.nextInt();
firstNum = Integer.parseInt(Integer.toString(digits).substring(0,1));
x.submit(firstNum);
digits++;
}
} catch(HistogramOutOfBoundsException e) {}
try {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("Output.txt"), "utf-8")));
out.write(x.toString())
out.close();
} catch (IOException e) {}
I am currently trying to get the number of times the two dice have identical values. This is what I have so far.
public static void main(String [] args)
{
System.out.print("Enter the amount of rolls you want to do: ");
Scanner scan = new Scanner(System.in);
int r = scan.nextInt();
final int FACES = 6, ROLLS = r;
int [] rollCount = new int [FACES];
int [] rolCount = new int [FACES];
Die d1 = new Die();
Die d2 = new Die();
int myRoll = 0;
int myRollTwo = 0;
int Ident = 0;
int i = 0;
while (i <= 1)
{
int ii = 0;
int iii = 0;
for (ii = 1; ii <= ROLLS; ii++)
{
myRoll = d1.roll();
rollCount[myRoll - 1]++;
}
for (ii = 1; ii <= ROLLS; ii++)
{
myRollTwo = d2.roll();
rolCount[myRollTwo - 1]++;
iii++;
}
if (myRoll == myRollTwo)
{
Ident++;
}
if (iii == ROLLS)
{
i++;
}
}
System.out.println("Die Number\tDie One\tDie Two\tTotal\t Amount of Identical Rolls");
for (i = 0; i < rollCount.length; i++)
{
System.out.println((i + 1) + "\t\t\t" + rollCount[i] + "\t\t" + rolCount[i] + "\t\t" + ((rollCount[i] + rolCount[i])*(i + 1)) + "\t\t" + Ident);
}
}
I know that the if statement near the end of the while loop wouldn't work because it would only do it once, so how exactly would I go about getting the number of times the two dice were the same?
I'm trying to make java code from this journal:
Journal Greedy LCS
This code is about a greedy approach for computing longest common subsequences by afroza begum.
And here is my [EDITED] code:
public class LCS_Greedy {
public static void main(String[] args) {
// String X_awal = "ABCBDABE";
// String Y = "BDCABA";
// String X_awal = "XMJYAUZ";
// String Y = "MZJAWXU";
// String X_awal ="AGGTAB";
// String Y="GXTXAYB";
// String X_awal = "ABCDGH";
// String Y = "AEDFHR";
// String X_awal = "AHBCDG";
// String Y = "AEDFHR";
//greedy not always optimum
String X_awal = "bcaaaade";
String Y = "deaaaabc";
String X = match(X_awal, Y);
int[] Penanda_Y = new int[Y.length()];
int y_length = Y.length();
for (int k = 0; k < y_length; k++) {
Penanda_Y[k] = 0;
}
int m = X.length();
int n = Y.length();
String L = "";
String LSym = "";
int R = 0;
int i = 1;
int[] P = new int[100];
P[i] = posisi(X, Y, i, Penanda_Y, R);
i = 1;
while (i <= m) {
if (i != m) {
P[i + 1] = posisi(X, Y, (i + 1), Penanda_Y, R);
}
if (P[i + 1] == 0) {
if (P[i] > R) {
L = L + " " + Integer.toString(P[i]);
LSym = LSym + " " + X.charAt(i - 1);
}
break;
}
if (P[i + 1] < R || P[i] < R) {
R = 0;
}
if (P[i] > P[i + 1]) {
if (R == 0 && i > 1) {
L = L + " " + Integer.toString(P[i]);
LSym = LSym + " " + X.charAt(i - 1);
Penanda_Y[P[i] - 1] = 1;
R = P[i];
i = i + 1;
if (R == Y.length() || i > X.length()) {
break;
}
P[i] = posisi(X, Y, i, Penanda_Y, R);
} else {
L = L + " " + Integer.toString(P[i + 1]);
LSym = LSym + " " + X.charAt(i + 1 - 1);
Penanda_Y[P[i + 1] - 1] = 1;
R = P[i + 1];
i = (i + 1) + 1;
if (R == Y.length() || i > X.length()) {
break;
}
P[i] = posisi(X, Y, i, Penanda_Y, R);
}
} else {
if (R == 0 && i > 1) {
L = L + " " + Integer.toString(P[i + 1]);
LSym = LSym + " " + X.charAt(i + 1 - 1);
Penanda_Y[P[i + 1] - 1] = 1;
R = P[i + 1];
i = (i + 1) + 1;
if (R == Y.length() || i > X.length()) {
break;
}
P[i] = posisi(X, Y, i, Penanda_Y, R);
} else {
L = L + " " + Integer.toString(P[i]);
LSym = LSym + " " + X.charAt(i - 1);
Penanda_Y[P[i] - 1] = 1;
R = P[i];
i = i + 1;
if (R == Y.length() || i > X.length()) {
break;
}
P[i] = posisi(X, Y, i, Penanda_Y, R);
}
}
}
System.out.println("X = " + X_awal);
System.out.println("X = " + Y);
System.out.println("L = " + L);
System.out.println("LSym = " + LSym);
System.out.println("Length = " + LSym.length() / 2);
}
public static String match(String X, String Y) {
String hasil = "";
for (int i = 0; i < X.length(); i++) {
for (int j = 0; j < Y.length(); j++) {
if (X.charAt(i) == Y.charAt(j)) {
hasil = hasil + X.charAt(i);
break;
}
}
}
return hasil;
}
public static int posisi(String X, String Y, int i, int[] Penanda_Y, int R) {
int n = Y.length();
int k;
int kr = 0;
i = i - 1;
for (k = 0; k < n; k++) {
if ((X.charAt(i) == Y.charAt(k)) && Penanda_Y[k] == 0) {
kr = k + 1;
break;
}
}
for (k = R; k < n; k++) {
if ((X.charAt(i) == Y.charAt(k)) && Penanda_Y[k] == 0) {
kr = k + 1;
break;
}
}
return kr;
}
}
But when I run that program, in some case it has true output, but in another case it false. What is wrong with that code? Can anybody explain to me? Thanks
Edit:
My code now can run perfectly, but it seem far away from pseudo code in that journal. Can anybody explain this? Why I cannot make code exactly from the journal? It always error when I make from pseudo code given in that journal. Thanks.
The algorithm will not lead to LCS. The greedy guess was wrong. It assumes the early match will guaranty to form LCS. Even though, the pseudocode takes the earlier matching of first two in X, which may skip a lot of common substring at the beginning of Y. The other simple test is change last 'E' to 'A' in X, the algorithm won't be able to find last matching 'A' for sure. The truth is an early match may lock down the position to forbidden longer match. In other word, we may need to skip some early match, so that we can found a longer match. Dynamic programming way is proved to be true mathematically, however, this algorithm didn't.
Edit: Yes, I know that ScanObj is not a proper name. And here is all of my code. It is not complete so there are some errors and some glitches, but you asked for it:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Scanner;
import javax.swing.JFrame;
public class MainClass {
static String[][] medium = new String[5][4];
static String names[] = { "Gatz ", "Cat ", "Women", "Mice ", "Robin",
"Romeo ", "Summer ", "Tempest", "Hamlet ", "Lear ",
"Titanic ", "StarWars", "DieHard ", "Elf ", "RED " };
static String lexile[] = { "L:1070", "L:123 ", "L:9254", "L:1234",
"L:534 ", "L:349", "L:632 ", "L:1097", "L:6453", "L:812 ",
"L:NA ", "L:NA ", "L:NA ", "L:NA ", "L:NA ", "L:NA " };
static String grade[] = { "G:9", "G:10", "G:12", "G:11", "G:9", "G:12",
"G:11", "G:9", "G:9", "G:12", "G:12", "G:11", "G:11", "G9", "G:9" };
static int max = 4;
char sorttype = (Character) null;
public static void main(String args[]) throws InterruptedException {
System.
out.println("Would you like to browse:\nB)Book C)CD or D)DVD");
Scanner ScanObj =
new Scanner(System.in);
String[] input =
new String[10];
input[1] = ScanObj.nextLine();
int store[] = { 6, 6, 6, 6, 6, 6 };
if (input[1].equals("B") || input[1].equals("Book")
|| input[1].equals(
"book") || input[1].equals("b")) {
String temp[][] =
new String[5][4];
int random[] = new int[5];
boolean repeat = true;
int nums[] = new int[5];
for (int i = 0; i < 5; i++) {
temp[i][0] =
"book";
temp[i][1] =
names[i];
temp[i][2] =
lexile[i];
temp[i][3] =
grade[i];
for (int qwop = 0; qwop < 4; qwop++) {
medium[i][qwop] = temp[i][qwop];
if (qwop == 0)
System.
out.printf(i + 1 + " | ");
else if (qwop < 3)
System.
out.printf(medium[i][qwop] + " | ");
else
System.
out.println(medium[i][qwop] + "\n");
Thread.sleep(150);
}
// System.out.println(temp[i][i]);
// random = store[i];
if (i == 4)
System.
out.printf("\n\n\n");
}
}
if (input[1].equals("C") || input[1].equals("c")
|| input[1].equalsIgnoreCase(
"CD") || input[1].equals("cd")) {
String temp[][] =
new String[5][4];
for (int i = 0; i < 5; i++) {
int random1 = (int) (Math.random() * max) + 6;
for (int p = 0; p < 4; p++) {
for (random1 = (int) (Math.random() * max) + 6; random1 == store[p];) {
random1 = (
int) (Math.random() * max) + 6;
}
}
temp[i][0] =
"CD";
temp[i][1] =
names[i + 5];
temp[i][2] =
lexile[i + 5];
temp[i][3] =
grade[i + 5];
for (int qwop = 0; qwop < 4; qwop++) {
medium[i][qwop] = temp[i][qwop];
if (qwop < 3)
System.
out.printf(medium[i][qwop] + " | ");
else
System.
out.println(medium[i][qwop] + "\n");
Thread.sleep(150);
}
// System.out.println(temp[i][i]);
random1 = store[i];
if (i == 4)
System.
out.printf("\n\n\n");
}
}
if (input[1].equalsIgnoreCase("D") || input[1].equalsIgnoreCase("DVD")) {
String temp[][] =
new String[5][4];
for (int i = 0; i < 5; i++) {
int random1 = (int) (Math.random() * max) + 6;
for (int p = 0; p < 4; p++) {
for (random1 = (int) (Math.random() * max) + 6; random1 == store[p];) {
random1 = (
int) (Math.random() * max) + 6;
}
}
temp[i][0] =
"DVD";
temp[i][1] =
names[i + 10];
temp[i][2] =
lexile[i + 10];
temp[i][3] =
grade[i + 10];
for (int qwop = 0; qwop < 4; qwop++) {
medium[i][qwop] = temp[i][qwop];
if (qwop < 3)
System.
out.printf(medium[i][qwop] + " | ");
else
System.
out.println(medium[i][qwop] + "\n");
Thread.sleep(150);
}
// System.out.println(temp[i][i]);
random1 = store[i];
if (i == 4)
System.
out.printf("\n\n\n");
}
}
// for loop goes through each of the parameters and compltes the
// instructions
System.
out
.println(
"How would you like to sort?\nA)Name B) Lexile C) Grade Level");
input[2] = ScanObj.nextLine();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
// if statement checks if the condition is true, then does the
// instructions if it is
// compareTo checks the ascii values of two strings. If the
// second
// is smaller (would come first in alphabetic order) it returns
// -1
boolean mismatch = true;
while (mismatch) {
if (input[2].equalsIgnoreCase("a")) {
mismatch =
false;
// makes a new temporary String
String temp1 =
null;
// Switches the String at position i with the one above
// it
for (int z = 0; z < medium.length - 1; z++) {
for (int x = z + 1; x < medium.length; x++) {
if (medium[z][1].compareTo(medium[x][1]) > 0) {
for (int qwop = 0; qwop < 4; qwop++) {
temp1 =
medium[z][qwop];
medium[z][qwop] = medium[x][qwop];
medium[x][qwop] = temp1;
}
mismatch =
true;
}
}
}
}
if (input[2].equalsIgnoreCase("b")) {
mismatch =
false;
// makes a new temporary String
String temp3 =
null;
// Switches the String at position i with the one above
// it
for (int z = 0; z < medium.length - 1; z++) {
for (int x = z + 1; x < medium.length; x++) {
if (medium[z][2].compareTo(medium[x][2]) > 0) {
for (int qwop = 0; qwop < 4; qwop++) {
temp3 =
medium[z][qwop];
medium[z][qwop] = medium[x][qwop];
medium[x][qwop] = temp3;
}
mismatch =
true;
}
}
}
}
if (input[2].equalsIgnoreCase("c")) {
mismatch =
false;
// makes a new temporary String
String temp3 =
null;
// Switches the String at position i with the one above
// it
for (int z = 0; z < medium.length - 1; z++) {
for (int x = z + 1; x < medium.length; x++) {
// Here I encounter an error because compareTo()
// sorts Lexicographically, meaning anything
// starting with a 1 comes before anything
// starting with a 2, 3, etc. This means that
// Grade 11 comes before grade 9, and simply
// comparing greater than does not work due to
// the fact that they are Strings.
if (medium[z][3].compareTo(medium[x][3]) > 0) {
for (int qwop = 0; qwop < 4; qwop++) {
temp3 =
medium[z][qwop];
medium[z][qwop] = medium[x][qwop];
medium[x][qwop] = temp3;
}
mismatch =
true;
}
}
}
}
}
}
}
Thread.sleep(1000);
for (int prt = 0; prt < medium.length; prt++) {
for (int qwop = 0; qwop < 4; qwop++) {
if (qwop < 3)
System.
out.printf(medium[prt][qwop] + " | ");
else
System.
out.println(medium[prt][qwop]);
}
}
Thread.sleep(1800);
for (int t = 0; t < 1000; t++) {
System.
out.println("\n\n\nTo edit a selection, type edit\n"
+
"To sort by a different category, type sort\n"
+
"To browse another medium, type browse\n"
+
"To search the " + medium[1][0] + "s, type search");
input[3] = ScanObj.nextLine();
if (input[3].equalsIgnoreCase("browse")) {
Thread.sleep(500);
System.out.println("What would you like to browse?:");
if (medium[1][0].equals("book")) {
System.out.println("CDs, or DVDs");
input[4] = ScanObj.nextLine();
}
if (medium[1][0].equals("CD")) {
System.out.println("Books, or DVDs");
input[4] = ScanObj.nextLine();
}
if (medium[1][0].equals("DVD")) {
System.out.println("Books, or CDs");
input[4] = ScanObj.nextLine();
}
if (input[4].equalsIgnoreCase("CD")
|| input[4].equalsIgnoreCase("DVD")
|| input[4].equalsIgnoreCase("Book")) {
for (int i = 0; i < 5; i++) {
String temp[][] = new String[5][4];
temp[i][0] =
"CD";
int addon = 0;
if (input[4].equals("CD"))
addon = 5;
if (input[4].equals("DVD"))
addon = 10;
temp[i][1] =
names[i + addon];
temp[i][2] =
lexile[i + addon];
temp[i][3] =
grade[i + addon];
for (int qwop = 0; qwop < 4; qwop++) {
medium[i][qwop] = temp[i][qwop];
if (qwop < 3)
System.
out.printf(medium[i][qwop] + " | ");
else
System.
out.println(medium[i][qwop] + "\n");
Thread.sleep(150);
}
}
}
}
if (input[3].equalsIgnoreCase("edit")) {
Thread.sleep(500);
System.
out.println("First type the number of the " + medium[1][0]
+
"\nyou want to edit");
int input4 = ScanObj.nextInt();
System.
out
.println(
"Now, type the number of the column you want to edit");
int input5 = ScanObj.nextInt();
System.
out.println("Now, make your edit:\n");
input[6] = ScanObj.nextLine();
medium[input4][input5] = input[6];
System.
out.println(medium[input4][input5]);
}
for (int y = 0; y < 10; y++) {
if (input[3].equalsIgnoreCase("search")) {
Thread.sleep(2000);
System.
out.println("Would you like to search by 1) Title or 2) Lexile #");
int input4 = 1;
input4 = ScanObj.nextInt();
Thread.sleep(2500);
System.
out.println("Now Type your search");
input[5] = ScanObj.nextLine();
Thread.sleep(2500);
for (int i = 0; i < 5; i++) {
System.
out.println(input4 + ", " + input[5]);
System.
out.println(medium[i][input4]);
if (input[5].compareToIgnoreCase(medium[i][input4]) == 0) {
y = 10;
System.
out.println("why do you lie");
for (int r = 0; r < 4; r++) {
if (r < 3)
System.
out.printf(medium[i][r] + " | ");
else
System.
out.println(medium[i][r]);
Thread.sleep(150);
}
}
else
System.
out.println(medium[i][input4]);
System.
out.println("Couldn't find item, please search again:");
}
}
}
}
}
}
Where ScanObj is my scanner. I'm just trying to get an Integer input, but it always returns null. What's wrong?
Here's an example using Scanner-
int choice;
do {
System.out.print("Would you like to search by (1) Title or (2) Lexile # : ");
choice = scan.nextInt();
} while(choice < 1 || choice > 2); // Keep asking the user for a valid integer
Above code will break, if the input is not an integer.
You can use nextLine-
Scanner scan = new Scanner(System.in);
String response;
do {
System.out.print("Would you like to search by (1) Title or (2) Lexile # : ");
response = scan.nextLine();
} while(!response.equals("1") && !response.equals("2"));
int choice = Integer.parseInt(response);
try {
System.out.print("Say cheeseeeee...");
Thread.sleep(3000);
} catch(InterruptedException e){
// handle exception
e.printStackTrace();
}
System.out.println("\nChoice : " + choice);