I was trying to implement Booth's algorithm using Java, but the arithmetic right shift function(rightShift()) is being ignored in my multiply() function. Is it because I have used a String for the product variable? Here's my code:-
import java.util.Scanner;
class BoothsAlgorithm{
static String appendZeros(int n){
String result = "";
for(int i = 0; i < n; i++) result += "0";
return result;
}
static String rightShift(String str){
String result = "";
for(int i = 0; i < str.length(); i++){
if(i == 0) result += str.charAt(i);
else result += str.charAt(i-1);
}
return result;
}
static String add(String a, String b){
String result = "";
char carry = '0';
for(int i = a.length()-1; i >= 0; i--){
String condition = "" + a.charAt(i) + b.charAt(i) + carry;
switch(condition){
case "000": result = "0" + result; break;
case "001": result = "1" + result; carry = '0'; break;
case "010": result = "1" + result; break;
case "011": result = "0" + result; break;
case "100": result = "1" + result; break;
case "101": result = "0" + result; break;
case "110": result = "0" + result; carry = '1'; break;
case "111": result = "1" + result; break;
}
}
return result;
}
static String multiply(int a, int b){
String op1 = Integer.toBinaryString(a);
String op2 = Integer.toBinaryString(b);
String negop2 = Integer.toBinaryString(-b);
char prev = '0';
String product = appendZeros(64-op1.length())+op1;
for(int i = 0; i < 32; i++){
if(i > 0) prev = product.charAt(63);
if(product.charAt(63)=='0' && prev == '1'){
String temp = appendZeros(32-op2.length()) + op2 + appendZeros(32);
product = add(product, temp);
}
if(product.charAt(63)=='1' && prev == '0'){
String temp = appendZeros(32-negop2.length()) + negop2 + appendZeros(32);
product = add(product, temp);
}
rightShift(product);
}
return product.substring(32);
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("Enter the first number: ");
int operand1 = sc.nextInt();
System.out.print("Enter the second number: ");
int operand2 = sc.nextInt();
System.out.println("The multiplication is "+multiply(operand1, operand2));
}
}
You need product = rightShift(product); or similar. rightShift returns a new String containing its result. It does not, and cannot, change the String referenced by product in the caller.
Related
I'm trying to make a program that processes a line of rpn expression through a stack method. The input is a string array that is converted from a string input.
String[] collect = "8 6 + 2 /"; //the
String line; //the inputed line
collect = line.split(" "); //the conversion
System.out.println(stackem(collect)); // calling the stack method for an output method
The problem is that the output is always the operator ate the end of the line, so when I put in the code that checks for malformed expressions it always turns into the error. Basically my input would be like this:
input: 8 6 + 2 /
output: Error: "Expression is malformed"
output (without the error code): /
output (what's supposed to be the output): 7
This is the code for the stack method:
public String stackem(String[] input)
{
Stack<String> stack = new Stack<String>();
int x, y;
String result = "";
int get = 0;
String choice;
int value = 0;
String p = "";
int output;
try
{
for (int i = 0; i < input.length; i++)
{
if (input[i] == "+" || input[i] == "-" || input[i] == "*" || input[i] == "/" || input[i] == "^")
{
choice = input[i];
}
else
{
stack.push(input[i]);
continue;
}
switch (choice)
{
case "+":
x = Integer.parseInt(stack.pop());
y = Integer.parseInt(stack.pop());
value = x + y;
result = p + value;
stack.push(result);
break;
case "-":
x = Integer.parseInt(stack.pop());
y = Integer.parseInt(stack.pop());
value = y - x;
result = p + value;
stack.push(result);
break;
case "*":
x = Integer.parseInt(stack.pop());
y = Integer.parseInt(stack.pop());
value = x * y;
result = p + value;
stack.push(result);
break;
case "/":
x = Integer.parseInt(stack.pop());
y = Integer.parseInt(stack.pop());
value = y / x;
result = p + value;
stack.push(result);
break;
case "^":
x = Integer.parseInt(stack.pop());
y = Integer.parseInt(stack.pop());
value = (int)Math.pow(y,x);
result = p + value;
stack.push(result);
break;
default:
continue;
}
}
output = Integer.parseInt(stack.pop());
}
catch (Exception ex)
{
return "Error: Expression is malformed";
}
return "Result: " + output;
}
Is there any way to fix this issue?
I am trying to compare two different strings, one character at a time. I need to return the correct number of digits until they do not equal each other anymore. However, I can't include the character of '.' in the return statement. How would I go about doing this?
import java.util.Scanner;
import java.math.BigDecimal;
public class PiEstimate {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String a;
String b;
char y;
char c;
char d;
String userInput;
do {
System.out.print("Enter a number of randomly generated points:");
userInput = in.nextLine();
if (!isValid(userInput)) {
System.out.print("\n" + "You entered an invalid integer. Please enter a valid integer greater than 0: ");
userInput = in.nextLine();
BigDecimal estimate = new BigDecimal((Math.PI / 4) * 4);
estimate.toString();
System.out.println("\n" + "Your estimate is: " + calculation(userInput));
System.out.println("\n" + "Accuracy of digits is :" + comparison(estimate.toString(),userInput));
} else {
BigDecimal estimate = new BigDecimal((Math.PI / 4) * 4);
estimate.toString();
System.out.println("\n" + "Your estimate is: " + calculation(userInput));
System.out.println("\n" + "Accuracy of digits is :" + comparison(estimate.toString(),userInput));
}
System.out.println("\n" + "Would you like to play again? Enter 'Y' for yes or 'N' for no: ");
String optionToPlay = in.nextLine();
c = optionToPlay.charAt(0);
d = Character.toUpperCase(c);
if (d == 'n' || d == 'N') {
BigDecimal estimate2= new BigDecimal( (Math.PI / 4) * 4);
System.out.println("\n" + "The best estimate is: " + estimate2);
}
} while (d == 'Y');
} // end psvm
public static boolean isValid(String a) {
boolean isFlag = true;
char holder;
for (int i = 0; i < a.length(); i++) {
holder = a.charAt(i);
if (!Character.isDigit(a.charAt(i))) {
return false;
} if (i == 0 && holder == '-') {
return false;
}
} // end for
return isFlag;
} // end isValid
public static double calculation(String a) { // String a means 'looking for a string
double calc = Double.parseDouble(a);
int i;
double x;
double y;
double c = 0;
double runningCounter = 0;
double totalCounter;
for (i = 0; i < calc; i++) {
x = Math.random();
y = Math.random();
c = Math.sqrt((x * x) + (y * y));
if (c <= 1) {
runningCounter++;
}
} // end for
totalCounter = ((runningCounter / calc) * 4);
calc = totalCounter;
return calc;
}
public static int comparison (String bear, String userInput) {
int i = 0;
String s = calculation(userInput) + "";
int b;
int counter2 = 0;
for (i=0; i < s.length(); i++) {
if (s.charAt(i) != bear.charAt(i)) {
return i;
}
}
return i;
} // end comparison
} // end class
Code from IDE
So I have been given a project in where I must validate ISBN-10 and ISBN-13 numbers. My issue is that I want to use an ArrayList based on what the user inputs(the user adds as many numbers as they want to the ArrayList). Here is my code (without an ArrayList). How can I modify this so that the user can put as many ISBN number as they want?
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String isbn;
//Get the ISBN
System.out.print("Enter an ISBN number ");
isbn = input.nextLine();
input.close();
//Strip out the spaces/System.out.println("Press 1 to enter a list of ISBN numbers to verify. ");System.out.println("Press 1 to enter a list of ISBN numbers to verify. ");dashes by replacing with empty character.
isbn = isbn.replaceAll("( |-)", "");
//Check depending on length.
boolean isValid = false;
if(isbn.length()== 10){
isValid = CheckISBN10(isbn);
}else if (isbn.length()== 13){
isValid = CheckISBN13(isbn);
}else{
isValid = false;
}
//Print check Status
if(isValid){
System.out.println(isbn + " IS a valid ISBN");
}else{
System.out.println(isbn + " IS NOT a valid ISBN");
}
}
//Checking ISBN-10 numbers are valid
//
private static boolean CheckISBN10(String isbn){
int sum = 0;
String dStr;
for (int d = 0; d < 10; d++){
dStr = isbn.substring(d, d + 1);
if (d < 9 || dStr != "X"){
sum += Integer.parseInt(dStr) * (10-d);
}else {
sum += 10;
}
}
return (sum %11 == 10);
}
private static boolean CheckISBN13(String isbn){
int sum = 0;
int dVal;
for (int d = 0; d < 13; d++){
dVal = Integer.parseInt(isbn.substring(d, d + 1));
if (d % 2 == 0){
sum += dVal * 1;
}else {
sum += dVal * 3;
}
}
return (sum % 10 == 0);
}
}
public static List<String> scanNumberToListUntilAppears(String end) {
if(end == null || end.isEmpty())
end = "end";
List<String> numbers = new ArrayList<>();
String message = "Enter an ISBN number: ";
try (Scanner input = new Scanner(System.in)) {
System.out.print(message);
while(input.hasNext()) {
String isbn = input.nextLine();
if(isbn.equalsIgnoreCase(end)) {
if(!numbers.isEmpty())
break;
} else {
numbers.add(isbn);
if(numbers.size() == 1)
message = "Enter the next ISBN number or '" + end + "': ";
}
System.out.print(message);
}
}
return numbers;
}
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String isbn;
String ans;
ArrayList<String> isbns = new ArrayList<String>();
// user will enter at least 1 ISBN
do{
//Get the ISBN
System.out.println("Enter an ISBN number ");
isbns.add(input.nextLine());
//loops till answer is yes or no
while(true){
System.out.println("Would you like to add another ISBN?");
ans = input.nextLine();
if(ans.equalsIgnoreCase("no"))
break;
else if (!(ans.equalsIgnoreCase("yes"))
System.out.println("Please say Yes or No");
}
}while(!(ans.equalsIgnoreCase("yes"));
input.close();
//Strip out the spaces/System.out.println("Press 1 to enter a list of ISBN numbers to verify. ");System.out.println("Press 1 to enter a list of ISBN numbers to verify. ");dashes by replacing with empty character.
for(int i = 0; i<isbns.size(); i++)
isbns.set(i, isbns.get(i).replaceAll("( |-)", ""));
isbn = isbn.replaceAll("( |-)", "");
//Check depending on length.
boolean isValid = false;
for(String isbn : isbns){
if(isbn.length()== 10){
isValid = CheckISBN10(isbn);
print(isbn, isValid);
}else if (isbn.length()== 13){
isValid = CheckISBN13(isbn);
print(isbn, isValid);
}else{
isValid = false;
print(isbn, isValid);
}
}
public static void print(String isbn, boolean isValid){
if(isValid){
System.out.println(isbn + " IS a valid ISBN");
}else{ System.out.println(isbn + " IS NOT a valid ISBN");
}
}
//Checking ISBN-10 numbers are valid
private static boolean CheckISBN10(String isbn){
int sum = 0;
String dStr;
for (int d = 0; d < 10; d++){
dStr = isbn.substring(d, d + 1);
if (d < 9 || dStr != "X"){
sum += Integer.parseInt(dStr) * (10-d);
}else {
sum += 10;
}
}
return (sum %11 == 10);
}
private static boolean CheckISBN13(String isbn){
int sum = 0;
int dVal;
for (int d = 0; d < 13; d++){
dVal = Integer.parseInt(isbn.substring(d, d + 1));
if (d % 2 == 0){
sum += dVal * 1;
}else {
sum += dVal * 3;
}
}
return (sum % 10 == 0);
}
i have a problem writing guess the word game java code .
i'll show you my current code and till you the problem .
import java.util.Scanner;
class Q
{
public static void main(String argss[])
{
String strs[] = { "kareem", "java", "izz", "tamtam", "anas" };
Scanner input = new Scanner(System.in);
int index = ((int) (Math.random() * 5));
int points = 50;
String c;
boolean result = false;
boolean finalResult = false;
boolean tempResult = false;
String word = strs[index];
System.out.println(
"\t *** Enter a character and guess the world*** \n\t ***You will loose if your points become 0 *** \n ");
System.out.println(stars(word));
System.out.println("Your points: " + points);
System.out.print("Enter and guess a character! ");
String temp = stars(word);
String oldTemp = temp;
c = input.next();
while (points > 0)
{
for (int i = 0; i < word.length(); i++)
{
result = (word.charAt(i) + "").equals(c);
if (result == true)
{
temp = toChar(i, temp, c);
}
}
finalResult = temp.equals(word);
tempResult = temp.equals(oldTemp);
System.out.println(temp);
if (finalResult == true)
{
System.out.println("\n \n YOU HAVE GUESSED THE WORLD,YOU WON ! ");
break;
}
if (tempResult == true)
{
points = points - 5;
System.out.println("False and now your points are " + points);
}
else if (tempResult == false)
{
System.out.println("True and now your points are " + points);
}
if (points <= 0)
{
System.out.println("\n\n*********************\n* Sorry , you loose *\n********************* ");
break;
}
System.out.print("Guess another time,enter a character: ");
c = input.next();
}
}
public static String stars(String word)
{
String temp = "";
for (int i = 0; i < word.length(); i++)
temp = temp + "*";
return temp;
}
public static String toChar(int index, String temp, String c)
{
char[] tempChar = temp.toCharArray();
char s = c.charAt(0);
tempChar[index] = s;
temp = String.valueOf(tempChar);
return temp;
}
}
now as you can see in line number 39 , i have a little problem here because when its false it'll be no longer right .
do you know another way to compare if the entry is right or not ?
Doesn't look like you are changing oldTemp inside the while loop. Try setting it to equal to temp after all of the if statements.
if (points <= 0)
{
System.out.println("\n\n*********************\n* Sorry , you loose *\n********************* ");
break;
}
oldTemp = temp; // add this here
System.out.print("Guess another time,enter a character: ");
c = input.next();
For class I am creating a Binary to Denary converter and I can't seem to get it to work. My use of if and else if statements seems to make my code very cluttered.
Is there a way of reducing the amount of clutter? The task says that it would be useful to investigate: .toString, .substring(int a, int b) and java.lang.Math.pow(double a, double b). Anyway of also getting this to work? All the values, since they're defined as 0 to begin with, end up all being 0.
import java.util.Scanner;
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
String binary;
int value0 = 0;
int value1 = 0;
int value2 = 0;
int value3 = 0;
int value4 = 0;
int value5 = 0;
int value6 = 0;
int value7 = 0;
System.out.println("Welcome to the Binary to Denary converter!");
System.out.println("Please enter an 8-BIT Binary value:");
binary = userInput.next();
char result0 = binary.charAt(0);
char result1 = binary.charAt(1);
char result2 = binary.charAt(2);
char result3 = binary.charAt(3);
char result4 = binary.charAt(4);
char result5 = binary.charAt(5);
char result6 = binary.charAt(6);
char result7 = binary.charAt(7);
if (result0 == 1){
value0 = 128;
}
else if (result0 == 0){
value0=0;
}
if (result1 == 1){
value1 = 64;
}
else if (result1 == 0){
value1=0;
}
if (result2 == 1){
value2 = 32;
}
else if (result2 == 0){
value2=0;
}
if (result3 == 1){
value3 = 16;
}
else if (result3 == 0){
value3=0;
}
if (result4 == 1){
value4 = 8;
}
else if (result4 == 0){
value4=0;
}
if (result5 == 1){
value5 = 4;
}
else if (result5 == 0){
value5=0;
}
if (result6 == 1){
value6 = 2;
}
else if (result6 == 0){
value6=0;
}
if (result7 == 1){
value7 = 1;
}
else if (result7 == 0){
value7=0;
}
int answer = value0+value1+value2+value3+value4+value5+value6+value7;
System.out.println("Your Denary value is:"+value0+"+"+value1+"+"+value2+"+"+value3+"+"+value4+"+"+value5+"+"+value6+"+"+value7+"="+answer);
}
}
As others said in the comments, you use too many variables.
Try this:
public static void main (String[] args) throws java.lang.Exception
{
Scanner userInput = new Scanner(System.in);
String binary;
int answer = 0;
System.out.println("Welcome to the Binary to Denary converter!");
System.out.println("Please enter an 8-BIT Binary value:");
binary = userInput.next();
for (int i = 0; i < binary.length(); i++) {
if (binary.charAt(i) == '1') {
answer += java.lang.Math.pow(2, binary.length() - i - 1);
}
}
System.out.println("Your Denary value is:"+answer);
}
If you understand binary conversion correctly, we go from right to left and increment by power of 2. So instead of checking for each values, compare each character in the string and check if it is 1 and increment if it is.
Here is the working demo of the code above.