Prompt: I need to create code using 2 methods to convert an Integer to binary. This is on zybooks and it has run successfully but it is saying some some of the output is wrong.
My code:
public static String intToReverseBinary(int integerValue) {
String reverseBinary = "";
int x = integerValue;
while (x != 0) {
int remainder = x % 2;
x = x /2;
reverseBinary = reverseBinary + Integer.toString(remainder);
}
return stringReverse(reverseBinary);
}
public static String stringReverse(String inputString) {
String reversed = "";
for (int i = inputString.length() - 1; i >= 0; i--) {
reversed = reversed + inputString.charAt(i);
}
return reversed;
}
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int userInput = scnr.nextInt();
System.out.println(intToReverseBinary(userInput));
}
It says: Convert 19 to binary using intToReverseBinary() and stringReverse()
Your output
intToReverseBinary(19) incorrectly returned 10011. But isn't that correct?
import java.util.Scanner;
public class LabProgram {
/* Define your methods here */
public static String intToReverseBinary(int integerValue){
String reverseBinary="";
while (integerValue>0){
int remainder = integerValue % 2;
integerValue = integerValue /2;
reverseBinary = reverseBinary + Integer.toString(remainder);
}
return reverseBinary;
}
public static String stringReverse(String inputString){
String reversed = "";
for (int i = inputString.length() - 1; i >= 0; i--) {
reversed = reversed + inputString.charAt(i);
}
return reversed;
}
public static void main(String[] args) {
Scanner s= new Scanner(System.in);
int userint;
userint=s.nextInt();
System.out.println(stringReverse((intToReverseBinary(userint))));
}
}
Related
I'm trying to print a statement vertically, and then backward vertically with two classes so I can practice multiple skills. However, frustratingly, I cannot get my program to work and keep getting a "string index out of range error". I'm not sure if I'm miscalling my functions because I am new to Java.
class Main {
public static void main(String[] args) {
MyString.verPrint("treasure");
MyString.backPrint("treasure");
}
}
public class MyString {
public static String verPrint(String x){
int i = x.length();
while(0 < i){
x = x.charAt(i) + "\n";
i++;
}
return(x);
}
public static String backPrint(String x){
int i = x.length() - 1;
while(i >= 0){
i--;
x = x.charAt(i) + "\n";
}
return(x);
}
}
The problem with your solution is you are updating the input string in the first iteration by assigning a character and a new line to it. Hence, it doesn't work for the latter iterations. I've made some changes in your snippet. You may follow it -
public class Main {
public static void main(String[] args) {
System.out.println(MyString.verPrint("treasure"));
System.out.println(MyString.backPrint("treasure"));
}
}
class MyString {
String x;
public static String verPrint(String x){
int i = x.length();
String y = "";
int j = 0;
while(j < i){
y += x.charAt(j) + "\n";
j++;
}
return(y);
}
public static String backPrint(String x){
int i = x.length() - 1;
String y = "";
while(i >= 0){
y += x.charAt(i) + "\n";
i--;
}
return(y);
}
}
String s="HELLO";
char[] y=s.toCharArray();
for (char x : y) {
System.out.println(x);
}
OUTPUT
H
E
L
L
O
String S="Hello";
S=new StringBuffer(S).reverse().toString();
System.out.println(S);
char[] y=S.toCharArray();
for (char x : y) {
System.out.println(x);
}
You know output
your conditions have problem, while checking for the length and index of x string parameter:
public class Main {
public static void main(String[] args) {
System.out.println(verPrint("treasure"));
System.out.println("-----------");
System.out.println(backPrint("treasure"));
}
public static String verPrint(String x) {
int i = 0;
String result = "";
while (i < x.length()) {
result += x.charAt(i++) + "\n";
}
return result;
}
public static String backPrint(String x) {
int i = x.length() - 1;
String result = "";
while (i >= 0) {
result += x.charAt(i--) + "\n";
}
return result;
}
}
So I had tried this online challenge but got runtime error.Please help.I am new to programming. I have attached the problem statement and my solution.
The Challenge
Using the Java language, have the function KaprekarsConstant(num) take an integer of four digits (with at least two being distinct) and perform the following routine on said number:
Arrange the digits in descending order and in ascending order.
Subtract the smaller number from the bigger number, padding the difference with zeroes if necessary to maintain a four-digit number.
Then repeat step 1 and 2 using the four-digit difference.
Stop when the difference of the two, permuted numbers equals 6174.
Return the number of times that you had to perform steps 1 and 2 before arriving at a difference with the value of 6174.
nb: performing the routine on 6174 will always give you 6174 (7641 - 1467 = 6174).
For example: if num is 3524 your program should return 3: (pass 1) 5432 - 2345 = 3087, (pass 2) 8730 - 0378 = 8352, (pass 3) 8532 - 2358 = 6174.
Here is my solution:
import java.util.*;
import java.io.*;
class Main {
public static int KaprekarsConstant(int num) {
int diff = 0, count = 0;
while (diff != 6174) {
String s1 = String.valueOf(num);
int[] ch1 = new int[s1.length()];
for (int i = 0; i < ch1.length; i++) {
ch1[i] = s1.charAt(i);
}
Arrays.sort(ch1);
String s2 = String.valueOf(ch1);
String s3 = "";
for (int j = s2.length() - 1; j >= 0; j++) {
s3 += s2.charAt(j);
}
int a = Integer.parseInt(s2);
int b = Integer.parseInt(s3);
if (a > b) {
diff = a - b;
} else if (b > a) {
diff = b - a;
} else {
System.out.println("goal cant be reached");
break;
}
count++;
num = diff;
}
return num;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print(KaprekarsConstant(s.nextLine()));
}
}
Try this code:
/**
* KaprekarConstant
*/
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Arrays;
import java.util.Collections;
public class KaprekarConstant {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int inputNumber;
char[] digits;
System.out.print("Enter four digit number: ");
try {
inputNumber = scan.nextInt();
if (checkLength(inputNumber))
throw new Exception();
Kaprekar(inputNumber);
} catch (InputMismatchException e) {
System.out.println("Not a number");
} catch (Exception ex) {
System.out.println("Number must have four digits");
} finally {
scan.close();
}
}
public static void Kaprekar(int target) {
int maximum = 0, minimum = 0, result = 0;
Integer[] digits = new Integer[4];
if (target == 6174)
return;
int i = 0;
while (i < 4) {
digits[i] = target % 10;
target /= 10;
i++;
}
Arrays.sort(digits);
minimum = toInt(digits);
Arrays.sort(digits, Collections.reverseOrder());
maximum = toInt(digits);
result = maximum - minimum;
System.out.println(String.format("%d - %d = %d", maximum, minimum, result));
Kaprekar(result);
}
public static boolean checkLength(int number) {
if (String.valueOf(number).length() < 5 && String.valueOf(number).length() > 3)
return false;
return true;
}
public static int toInt(Integer[] digits) {
int number = 0;
for (int digit : digits) {
number *= 10;
number += digit;
}
return number;
}
}
I think this is best method to find the karpekar constant.
There were some basic syntax & logical errors in your code. I have made appropriate changes in it. See if you understand it.
import java.util.*;
import java.io.*;
public class Main {
public static int KaprekarsConstant(int num) {
int diff = 0, count = 0;
while (diff != 6174) {
String s1 = String.valueOf(num);
char[] ch1 = new char[s1.length()];
for (int i = 0; i < ch1.length; i++) {
ch1[i] = s1.charAt(i);
}
Arrays.sort(ch1);
String s2 = new String(ch1);
String s3 = "";
for (int j = s2.length() - 1; j >= 0; j--) {
s3 += s2.charAt(j);
}
int a = Integer.parseInt(s2);
int b = Integer.parseInt(s3);
if (a > b) {
diff = a - b;
} else if (b > a) {
diff = b - a;
} else {
System.out.println("goal cant be reached");
break;
}
count++;
num = diff;
}
return count;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print(KaprekarsConstant(s.nextInt()));
}
}
This solution has less lines of code:
import static java.lang.System.out;
import java.util.Arrays;
/**
* #see https://en.wikipedia.org/wiki/6174_%28number%29
*/
public class KaprekarConstant {
public static void main(String[] args) {
assert(count(3524) == 3);
assert(count(3087) == 2);
assert(count(8352) == 1);
assert(count(6174) == 1);
out.println("All passed.");
}
public static int count(int start) {
int ct = 0;
do {
start = calc(start);
ct++;
} while (start != 6174);
return ct;
}
static int calc(int n) {
String n1s = String.format("%04d", n);
char[] chs = n1s.toCharArray();
Arrays.sort(chs);
n1s = new String(chs);
String n2s = new StringBuilder(new String(n1s)).reverse().toString();
int n1 = Integer.parseInt(n1s);
int n2 = Integer.parseInt(n2s);
return Math.max(n1, n2) - Math.min(n1, n2);
}
}
Here is a Python implementation:
def kc_count(start_int):
def kc_calc(n):
ns1 = ''.join(sorted("%04d" % n))
ns2 = ns1[::-1]
return max(int(ns1), int(ns2)) - min(int(ns1), int(ns2))
ct = 0;
while True:
start_int = kc_calc(start_int)
ct += 1
if start_int == 6174:
break
return ct
assert(kc_count(3524) == 3)
assert(kc_count(3087) == 2)
assert(kc_count(8352) == 1)
assert(kc_count(6174) == 1)
I have to write a program that finds primes between two user inputted numbers. The only problem I'm having is that the output has one extra comma than it needs. How would I go about fixing this?
import java.util.Scanner;
public class Primes {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int start = sc.nextInt();
int end = sc.nextInt();
for (int i =start; i <= end; i++) {
if (isPrime(i)) {
System.out.printf("%d,", i);
}
}
}
public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i =2; i < Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
Input: 1 10
Output: 2,3,4,5,7,9,
try to use a StringJoiner is more apropriate in this case:
import java.util.Scanner;
public class Primes {
public static void main(String[] args) {
StringJoiner joiner = new StringJoiner(",");
Scanner sc = new Scanner(System.in);
int start = sc.nextInt();
int end = sc.nextInt();
for (int i =start; i <= end; i++) {
if (isPrime(i)) {
joiner.add(Integer.toString(i));
}
}
System.out.println(joiner.toString());
}
without StringJoiner :
public class Primes {
public static void main(String[] args) {
String separator = "";
Scanner sc = new Scanner(System.in);
int start = sc.nextInt();
int end = sc.nextInt();
for (int i =start; i <= end; i++) {
if (isPrime(i)) {
System.out.printf(separator + "%d", i);
separator = ",";
}
}
}
Here's a bit of a different approach, using streams:
String output = IntStream.rangeClosed(start, end)
.filter(Primes::isPrime)
.mapToObj(String::valueOf)
.collect(Collectors.joining(","));
System.out.println(output);
i was wondering how can i create a method where i can get the single instance from a string and give it a numericValue for example, if theres a String a = "Hello what the hell" there are 4 l characters and i want to give a substring from the String a which is Hello and give it numeric values. Right now in my program it gets all the character instances from string so the substring hello would get number values from the substring hell too because it also has the same characters.
my code :
public class Puzzle {
private static char[] letters = {'a','b','c','d','e','f','g','h','i', 'j','k','l','m','n','o','p','q','r','s',
't','u','v','w','x','y','z'};
private static String input;
private static String delimiters = "\\s+|\\+|//+|=";
public static void main(String[]args)
{
input = "help + me = please";
System.out.println(putValues(input));
}
//method to put numeric values for substring from input
#SuppressWarnings("static-access")
public static long putValues(String input)
{
Integer count;
long answer = 0;
String first="";
String second = "";
StringBuffer sb = new StringBuffer(input);
int wordCounter = Countwords();
String[] words = countLetters();
System.out.println(input);
if(input.isEmpty())
{
System.out.println("Sisestage mingi s6na");
}
if(wordCounter == -1 ||countLetters().length < 1){
return -1;
}
for(Character s : input.toCharArray())
{
for(Character c : letters)
{
if(s.equals(c))
{
count = c.getNumericValue(c) - 9;
System.out.print(s.toUpperCase(s) +"="+ count + ", ");
}
}
if(words[0].contains(s.toString()))
{
count = s.getNumericValue(s);
//System.out.println(count);
first += count.toString();
}
if(words[3].contains(s.toString())){
count = s.getNumericValue(s);
second += count.toString();
}
}
try {
answer = Long.parseLong(first)+ Long.parseLong(second);
} catch(NumberFormatException ex)
{
System.out.println(ex);
}
System.out.println("\n" + first + " + " + second + " = " + answer);
return answer;
}
public static int Countwords()
{
String[] countWords = input.split(" ");
int counter = countWords.length - 2;
if(counter == 0) {
System.out.println("Sisend puudu!");
return -1;
}
if(counter > 1 && counter < 3) {
System.out.println("3 sõna peab olema");
return -1;
}
if(counter > 3) {
System.out.println("3 sõna max!");
return -1;
}
return counter;
}
//method which splits input String and returns it as an Array so i can put numeric values after in the
//putValue method
public static String[] countLetters()
{
int counter = 0;
String[] words = input.split(delimiters);
for(int i = 0; i < words.length;i++) {
counter = words[i].length();
if(words[i].length() > 18) {
System.out.println("One word can only be less than 18 chars");
}
}
return words;
}
Program has to solve the word puzzles where you have to guess which digit corresponds to which letter to make a given equality valid. Each letter must correspond to a different decimal digit, and leading zeros are not allowed in the numbers.
For example, the puzzle SEND+MORE=MONEY has exactly one solution: S=9, E=5, N=6, D=7, M=1, O=0, R=8, Y=2, giving 9567+1085=10652.
import java.util.ArrayList;
public class main {
private static String ChangeString;
private static String[] ArrayA;
private static String a;
private static int wordnumber;
private static String temp;
public static void main(String[] args) {
// TODO Auto-generated method stub
a = "hello what the hell";
wordnumber = 0;
identifyint(a,wordnumber);
}
public static void identifyint (String a, int WhichWord){
ChangeString = a.split(" ")[WhichWord];
ArrayA = a.split(" ");
replaceword();
ArrayA[wordnumber] = ChangeString;
//System.out.print(ArrayA[wordnumber]);
a = "";
for(int i = 0; i<ArrayA.length;i++){
if(i==wordnumber){
a = a.concat(temp+ " ");
}
else{
a = a.concat(ArrayA[i]+" ");
}
}
System.out.print(a);
}
public static void replaceword(){
temp = "";
Character arr[] = new Character[ChangeString.length()];
for(int i = 0; i<ChangeString.length();i++){
arr[i] = ChangeString.charAt(i);
Integer k = arr[i].getNumericValue(arr[i])-9;
temp = temp.concat(""+k);
}
a = temp;
}
}
Change wordnumber to the word you want to replace each time. If this is not what you have asked for, please explain your question in more detail.
i have a homework assignment where im supposed to read in a string in this format [ 1+2/3+4] then i have to store 5 variables, which are the first 3 numbers and the first 2 operators. my question is how can i loop through the string and store the values into different variables. this is what i have so far.
public class ExpresionEvaluation {
static String expression;
static double o1;
static double o2;
private static double o3;
static char operator1;
private static char operator2;
public static String getOperand(String s) {
s = s.trim();
String num = "";
while (s.length() > 0 && s.charAt(0) >= '0' && s.charAt(0) <= '9') {
num = num + s.charAt(0);
s = s.substring(1);
}
expression = s;
return (num);
}
public static char getOperator(String s) {
s = s.trim();
char r = 0;
int i = 0;
while (s.length() > 0 && s.charAt(0) >= '0' && s.charAt(0) <= '9') {
r = s.charAt(i);
s = s.substring(i+1);
i++;
}
return (r);
}
public static double add(double a, double b) {
return (a + b);
}
public static double sub(double a, double b) {
return (a - b);
}
public static double mult(double a, double b) {
return (a * b);
}
public static double div(double a, double b) {
return (a / b);
}
public static double solveExpresion(String e) {
double answer = 0;
for(int i = 0;i< e.length();i++){
String operand1;
String operand2;
operand1 = getOperand(e);
o1 = Double.parseDouble(operand1);
operand2 = getOperand(expression);
o2 = Double.parseDouble(operand2);
operator1 = getOperator(expression);
}
return (answer);
}
}
this is my main class
import java.util.Scanner;
public class TestCalc {
public static void main(String args[]) {
Scanner kb = new Scanner(System.in);
String equation;
System.out.println("Please enter your equation: ");
equation = kb.nextLine();
double newNum = ExpresionEvaluation.solveExpresion(equation);
//System.out.println(newNum);
System.out.println(ExpresionEvaluation.o1);
System.out.println(ExpresionEvaluation.operator1);
System.out.println(ExpresionEvaluation.o2);
//System.out.println(ExpresionEvaluation.expression);
}
}
everytime i run this it says that i have a empty string.
Here's my quick solution to retrieve the 5 variables as expected, using Matcher/Pattern:
public static void main(String[] args) throws ParseException {
String operation = getOperationFromInput();
List<Integer> firstThreeNumbers = retrieveFirstThreeNumbers(operation);
List<Character> firstTwoOperators = retrieveFirstTwoOperators(operation);
printNumbersAndOperators(firstThreeNumbers, firstTwoOperators);
}
private static String getOperationFromInput() {
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("\n");
return scanner.next();
}
private static List<Integer> retrieveFirstThreeNumbers(String operation) {
List<Integer> firstThreeNumbers = new ArrayList<>();
Pattern patternNumber = Pattern.compile("\\d");
Matcher matcher = patternNumber.matcher(operation);
for (int i = 0; i < 3 && matcher.find(); i++) {
firstThreeNumbers.add(Integer.valueOf(matcher.group()));
}
return firstThreeNumbers;
}
private static List<Character> retrieveFirstTwoOperators(String operation) {
List<Character> firstTwoOperators = new ArrayList<>();
Pattern patternOperator = Pattern.compile("[+-/*]");
Matcher matcher = patternOperator.matcher(operation);
for (int i = 0; i < 2 && matcher.find(); i++) {
firstTwoOperators.add(matcher.group().charAt(0));
}
return firstTwoOperators;
}
private static void printNumbersAndOperators(List<Integer> firstThreeNumbers, List<Character> firstTwoOperators) {
System.out.println(firstThreeNumbers + " " + firstTwoOperators);
}
In this code, I store the first three numbers in a List<Integer> and the first two operators in a List<Character>.
There're multiple ways to achieve to a solution, so as a homework, try to find another ways :)