String index out of range (Repeating Sequence of digits) - java

I seem to be having a problem with my code which is to look for the repeating sequence of digits. I have converted(?) double to string because I get the error unreachable statement. (which I guess helps to looking for the reason why I get the error I have now?).
Whenever I run it, it goes fine until I finish entering N and D.
It'll say "Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3"
Here is my code below:
import java.util.*;
public class RepeatingSequence{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Enter N,D: ");
int numerator = in.nextInt();
int denominator = in.nextInt();
double quotient = numerator / denominator;
String number = "" + quotient;
char n = number.charAt(0);
int j = 1;
int z = 0;
String output = "";
char[] index = number.toCharArray();
for ( int i = 2; number.charAt(j) != number.charAt(i); i++ ){
index[z] = number.charAt(z);
index[j] = number.charAt(j);
index[i] = number.charAt(i);
output = output + index[i];
if ( index[i] != index[z] ){
System.out.print(index[z] + ".(" + index[j] + output + ")");
}
}
}
}

just add i < number.length() to the condition
( int i = 2; i < number.length() && number.charAt(j) != number.charAt(i); i++ )

For your exception, I think you should write safer code - something on the lines of:
int len = number.length();
for ( int i = 2; (i < len) && (j < len) &&
number.charAt(j) != number.charAt(i); i++ ){
...
}
I am not attempting to solve the problem that you are trying to solve but just the problem you are facing. Sorry for that.

I changed your code a little bit try it out and see what you think:
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Enter N,D: ");
double numerator = in.nextDouble();
double denominator = in.nextDouble();
double quotient = numerator / denominator;
String number = "" + quotient;
char n = number.charAt(0);
int j = 1;
int z = 0;
String output = "";
char[] index = number.toCharArray();
int max = -1;
int currentNumber = -1;
int temp = -1;
int tempMax = -1;
System.out.println("" + quotient);
boolean check = true;
for(int i = (number.indexOf(".") + 1); i < index.length; i++)
{
if(max == -1)
{
currentNumber = i;
temp = i;
max = 1;
tempMax = 1;
}
else
{
if(index[i] == index[i-1])
{
tempMax++;
}
else
{
if(tempMax > max)
{
check = false;
max = tempMax;
currentNumber = temp;
}
tempMax = 1;
temp = i;
}
}
}
if(check)
{
max = tempMax;
}
System.out.println(index[currentNumber] + " repeats " + max + " times.");
}
Example of input/output:
Enter N,D: 1
3
0.3333333333333333
3 repeats 16 times.

Related

How can I test credit numbers with hyphens (" -" ) to get it as INVALID . When I tried 4003-6000-0000-0014 i am getting errors

I cant get credit card numbers containing hymens as INVALID such as 4003-6000-0000-0014 must give me INVALID but its giving me errors of string.
public class prog {
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in) ;
System.out.println("How many credit card you want to check?");
int numOfCredit = userInput.nextInt() ;
int creditnumbers[] = new int[numOfCredit] ;
for (int i = 0 ; i<numOfCredit ; i++)
{
System.out.println("Enter credit card number "+(i+1)+": ") ;
String creditNumber = userInput.next() ;
validateCreditCardNumber(creditNumber);
}
}
private static void validateCreditCardNumber(String str) { // function to check credit numbers
int[] ints = new int[str.length()];
for (int i = 0; i < str.length(); i++) {
ints[i] = Integer.parseInt(str.substring(i, i + 1));
}
for (int i = ints.length - 2; i >= 0; i = i - 2) {
int j = ints[i];
j = j * 2;
if (j > 9) {
j = j % 10 + 1;
}
ints[i] = j;
}
int sum = 0;
for (int i = 0; i < ints.length; i++)
{
sum += ints[i];
}
if (sum % 10 == 0)
{
System.out.println("VALID");
}
else
{
System.out.println("INVALID");
}
}
}
I get these errors after running with hymens :
Exception in thread "main" java.lang.NumberFormatException: For input string: "-"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:642)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at testing/testing.prog.validateCreditCardNumber(prog.java:33)
at testing/testing.prog.main(prog.java:22)
you can replace in your string "-" with "" (blank) and then apply this function:
String card = "4003-6000-0000-0014";
Boolean t = check(card.replace("-",""));
public static boolean check(String ccNumber)
{
int sum = 0;
boolean alternate = false;
for (int i = ccNumber.length() - 1; i >= 0; i--)
{
int n = Integer.parseInt(ccNumber.substring(i, i + 1));
if (alternate)
{
n *= 2;
if (n > 9)
{
n = (n % 10) + 1;
}
}
sum += n;
alternate = !alternate;
}
return (sum % 10 == 0);
}

Loop to add string of number

I try for an exercice to add
String nb = "135";
String nb2 = "135";
Result should be a String of "270"
I have no idea how to do that...I try to make a for loop and make an addition : nb.charAt(i) + nb2.charAt(i) but with no succes, I don't know what I have to do with the carry over.
EDIT : I try to don't use Integer or BigInteger, only String this is why I try to use a for loop.
Thanks for clue.
String str = "";
// Calculate length of both String
int n1 = nb.length(), n2 = nb2.length();
int diff = n2 - n1;
// Initially take carry zero
int carry = 0;
// Traverse from end of both Strings
for (int i = n1 - 1; i>=0; i--)
{
// Do school mathematics, compute sum of
// current digits and carry
int sum = ((int)(nb.charAt(i)-'0') +
(int) nb2.charAt(i+diff)-'0') + carry);
str += (char)(sum % 10 + '0');
carry = sum / 10;
}
// Add remaining digits of nb2[]
for (int i = n2 - n1 - 1; i >= 0; i--)
{
int sum = ((int) nb2.charAt(i) - '0') + carry);
str += (char)(sum % 10 + '0');
carry = sum / 10;
}
// Add remaining carry
if (carry > 0)
str += (char)(carry + '0');
// reverse resultant String
return new StringBuilder(str).reverse().toString();
try below snippet:
String s1 = "135";
String s2 = "135";
String result = Integer.toString (Integer.parseInt(s1)+Integer.parseInt(s2));
try converting char to int using Integer.parseInt(nb.charAt(i)) + Integer.parseInt(nb2.charAt(i))
you can use Character.numericValue to give you the integer value of a character, this will probably help you write the method. This method will also return -1 if there is no numeric value or -2 if it is fractional like the character for 1/2
You need to convert the strings to numbers to add them. Let's use BigInteger, just in case the numbers are really big:
String nb = "135";
String nb2 = "135";
BigInteger num1 = new BigInteger(nb);
BigInteger num2 = new BigInteger(nb2);
String result = num1.add(num2).toString();
Do it as follows:
public class Main {
public static void main(String args[]) {
System.out.println(getSum("270", "270"));
System.out.println(getSum("3270", "270"));
System.out.println(getSum("270", "3270"));
}
static String getSum(String n1, String n2) {
StringBuilder sb = new StringBuilder();
int i, n, cf = 0, nl1 = n1.length(), nl2 = n2.length(), max = nl1 > nl2 ? nl1 : nl2, diff = Math.abs(nl1 - nl2);
for (i = max - diff - 1; i >= 0; i--) {
if (nl1 > nl2) {
n = cf + Integer.parseInt(String.valueOf(n1.charAt(i + diff)))
+ Integer.parseInt(String.valueOf(n2.charAt(i)));
} else {
n = cf + Integer.parseInt(String.valueOf(n1.charAt(i)))
+ Integer.parseInt(String.valueOf(n2.charAt(i + diff)));
}
if (n > 9) {
sb.append(n % 10);
cf = n / 10;
} else {
sb.append(n);
cf = 0;
}
}
if (nl1 > nl2) {
for (int j = i + 1; j >= 0; j--) {
sb.append(n1.charAt(j));
}
} else if (nl1 < nl2) {
for (int j = i + 1; j >= 0; j--) {
sb.append(n2.charAt(j));
}
}
return sb.reverse().toString();
}
}
Output:
540
3540
3540
I would like to propose a much cleaner solution that adds 2 positive numbers and returns the result. Just maintain a carry while adding 2 digits and add carry in the end if carry is greater than 0.
public class Main{
public static void main(String[] args) {
System.out.println(addTwoNumbers("135","135"));
}
private static String addTwoNumbers(String s1,String s2){
if(s1.length() < s2.length()) return addTwoNumbers(s2,s1);
StringBuilder result = new StringBuilder("");
int ptr2 = s2.length() - 1,carry = 0;
for(int i=s1.length()-1;i>=0;--i){
int res = s1.charAt(i) - '0' + (ptr2 < 0 ? 0 : s2.charAt(ptr2--) - '0') + carry;
result.append(res % 10);
carry = res / 10;
}
if(carry > 0) result.append(carry);
return trimLeadingZeroes(result.reverse().toString());
}
private static String trimLeadingZeroes(String str){
for(int i=0;i<str.length();++i){
if(str.charAt(i) != '0') return str.substring(i);
}
return "0";
}
}
Demo: https://onlinegdb.com/Sketpl-UL
Try this i hope it works for you
Code
public static int convert_String_To_Number(String numStr,String numStr2) {
char ch[] = numStr.toCharArray();
char ch2[] = numStr2.toCharArray();
int sum1 = 0;
int sum=0;
//get ascii value for zero
int zeroAscii = (int)'0';
for (char c:ch) {
int tmpAscii = (int)c;
sum = (sum*10)+(tmpAscii-zeroAscii);
}
for (char d:ch2) {
int tmpAscii = (int)d;
sum1 = (sum*10)+(tmpAscii-zeroAscii);
}
return sum+sum1;
}
public static void main(String a[]) {
System.out.println("\"123 + 123\" == "+convert_String_To_Number("123" , "123"));
}
}

Reverse and sum the number occurrence in string - java

I would like to write a function that will be reverse a number and then sum it up.
For example, the input string is
We have 55 guests in room 38
So the expected output should be
83 + 55 = 138
I have face a question is that I can't read the last number
example:
input string is '8 people'
output is 0
Here's the code I've written :
int total = 0;
String num = "";
String a = input.nextLine();
for (int i = a.length() - 1; i > 0; i--) {
if (Character.isDigit(a.charAt(i))) {
num += a.charAt(i);
if (!Character.isDigit(a.charAt(i - 1))) {
total += Integer.valueOf(num);
num = "";
}
}
}
All you really need to do is :
String input = "We have 55 guests in room 38";
int sum = 0;
String[] split = input.split(" "); // split based on space
for (int i = 0; i < split.length; i++) {
if (split[i].matches("[0-9]+")) {
sum = sum + Integer.parseInt(new StringBuffer(split[i]).reverse().toString());
}
}
System.out.println(sum);
Explanation:
Here we use regex to check if the String split contains only
digits.
Now we reverse the String and then parse it to an int before
summing.
Try this and works for any input in the form "We have x guests in room y". For your program however, instead if the for loop > 0 do > -1 I think:
Scanner scan = new Scanner(System.in);
scan.next(); scan.next();
String numberOne = "" + scan.nextInt();
scan.next(); scan.next(); scan.next();
String numberTwo = "" + scan.nextInt();
// String numberOne = "" + scan.nextInt(), numberTwo = "" + scan.nextInt();
String numberOneReversed = "", numberTwoReversed = "";
for(int k = numberOne.length() - 1; k > -1; k--)
numberOneReversed += numberOne.charAt(k);
for(int k = numberTwo.length() - 1; k > -1; k--)
numberTwoReversed += numberTwo.charAt(k);
int sum = Integer.parseInt(numberOneReversed) + Integer.parseInt(numberTwoReversed);
System.out.println("" + numberOneReversed + " + " + numberTwoReversed + " = " + sum);
scan.close();
Note for your program as defined in your question:
for (int i = a.length() - 1; i > -1; i--) {
instead of
for (int i = a.length() - 1; i > 0; i--) {
and
if (i != 0 && !Character.isDigit(a.charAt(i - 1))) {
instead of
for (int i = a.length() - 1; i > 0; i--) {
Will return the sum correctly.
Okay here is what I created using BigIntegers instead of ints:
public static BigInteger nameOfFunctionGoesHere(String input) {
BigInteger total = new BigInteger(new byte[] {0});
int i = 0;
while (i < input.length()) {
if (Character.isDigit(input.charAt(i))) {
int j = i + 1;
while (!(j >= input.length()) && Character.isDigit(input.charAt(j))) {
j++;
}
String num = input.substring(i, j);
char[] flipped = new char[num.length()];
for (int n = num.length() - 1; n >= 0; n--) {
flipped[n] = num.charAt(num.length() - (n + 1));
}
total = total.add(new BigInteger(new String(flipped)));
i = j;
} else {
i++;
}
}
return total;
}
You can of course use ints as well like this:
public static int nameOfFunctionGoesHere(String input) {
int total = 0;
int i = 0;
while (i < input.length()) {
if (Character.isDigit(input.charAt(i))) {
int j = i + 1;
while (!(j >= input.length()) && Character.isDigit(input.charAt(j))) {
j++;
}
String num = input.substring(i, j);
char[] flipped = new char[num.length()];
for (int n = num.length() - 1; n >= 0; n--) {
flipped[n] = num.charAt(num.length() - (n + 1));
}
total = total + Integer.parseInt(new String(flipped));
i = j;
} else {
i++;
}
}
return total;
}
With longs too:
public static long nameOfFunctionGoesHere(String input) {
long total = 0;
int i = 0;
while (i < input.length()) {
if (Character.isDigit(input.charAt(i))) {
int j = i + 1;
while (!(j >= input.length()) && Character.isDigit(input.charAt(j))) {
j++;
}
String num = input.substring(i, j);
char[] flipped = new char[num.length()];
for (int n = num.length() - 1; n >= 0; n--) {
flipped[n] = num.charAt(num.length() - (n + 1));
}
total = total + Long.parseLong(new String(flipped));
i = j;
} else {
i++;
}
}
return total;
}

How to calculate big numbers in java?

ex
I want the sum form 1^1 to n^n : 1^1 + 2^2 + 3^3 + .............+n^n
and I know how, but the problem that I want only the last ten numbers of the sum but I have only to use primitive data. how can I calculate large numbers using only primitive data.
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
short n = in.nextShort();
if(n < 0) {
System.out.println("please give a positive number");
return;
}
long l = rechnung(n);
System.out.println(l);
String str = Objects.toString(l, null);
String s = ziffer(str);
System.out.println(s);
}
public static long rechnung(short j) {
long summe = 0;
for(int i = 1; i <= j; i++) {
summe += Math.pow(i,i);
}
return summe;
}
public static String ziffer(String s) {
String str = "";
int k =s.length() - 10;
int cond = k + 9;
if(s.length() <= 10) {
return s;
}
for(int j = k; j <= cond; j++) {
str = str + s.charAt(j);
}
return str;
}
As you only need to keep the lower 10 digits you can use a % 10_000_000_000L to keep the digits you need with each calculation.

Java binary multiplication using integer arrays not working

I'm making a program that accepts two decimal numbers and convert them into binary numbers, which are stored in integer arrays. Then I need to do multiplication using the two integer arrays. The result should also be a binary integer array (I need to validate that using a for loop). Then I convert them result to decimal number.
So far, I have the following code. My logic to convert the decimal number to binary works fine and vice verse. However, the binary result is always somehow smaller than the expected result. I have spent a lot of time on this, could you help me check what is wrong?
public class BinaryMultiplication {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
int[] binaryNum1 = toBinary(num1);
int[] binaryNum2 = toBinary(num2);
System.out.println("Expected result: " + num1 * num2);
System.out.println("Decimal number 1: " + toDecimal(binaryNum1));
System.out.println("Decimal number 2: " + toDecimal(binaryNum2));
int[] resultBinaries = new int[100];
for (int i = 0; i < resultBinaries.length; ++i) {
resultBinaries[i] = 0;
}
for (int i = 0; binaryNum1[i] != -1; ++i) {
for (int j = 0; binaryNum2[j] != -1; ++j) {
resultBinaries[i + j] += binaryNum1[i] * binaryNum2[j] % 2;
resultBinaries[i + j] %= 2;
}
}
resultBinaries[99] = -1;
for (int i = 0; resultBinaries[i] != -1; ++i) {
if (resultBinaries[i] > 1) {
System.out.println("The result is not a binary!!");
}
}
System.out.println("Actual decimal result: " + toDecimal(resultBinaries));
}
public static int toDecimal(int[] binaryNum) {
int result = 0;
int factor = 1;
for (int i = 0; binaryNum[i] != -1; ++i) {
result += binaryNum[i] * factor;
factor *= 2;
}
return result;
}
public static int[] toBinary(int num) {
int[] binaries = new int[100];
int index = 0;
while (num > 0) {
binaries[index++] = num % 2;
num /= 2;
}
binaries[index] = -1;
return binaries;
}
}
A sample input & output: ( the binary validation loop works fine)
45 67
Expected result: 3015
Decimal number 1: 45
Decimal number 2: 67
Actual decimal result: 2871
for (int i = 0; binaryNum1[i] != -1; ++i) {
for (int j = 0; binaryNum2[j] != -1; ++j) {
resultBinaries[i + j] += binaryNum1[i] * binaryNum2[j] % 2;
resultBinaries[i + j] %= 2;
}
}
What happens when resultBinaries[i + j] increases to 2? It's reduced to 0 and then resultBinaries[i + j + 1] should be increased with 1, but this isn't happening in the code as far as I can see.

Categories