the function doesn't take more than 10 letters on scanner - java

I need to get from the user the length and the value of the array and return the digit that shows the most times. for example: the user gave me the length "4" and the numbers {83,238,8,54} the function will return " the numbers that shows the most times is 8";
but it send an error massage if the user enter more than 10 digits in general.
String sum = "";
// get the length
System.out.println("Enter the size of the array :");
int size = in.nextInt();
// create the array
String[] arr = new String[size+1];
// get value
System.out.println("Enter the elements of the array:(max capity 10 digits) ");
for(int i=0; i<arr.length; i++) {
arr[i] = in.nextLine();
sum+=arr[i];
}
System.out.println("the numbers that you gave me are: "+sum);
int all = Integer.parseInt(sum);
System.out.println("the digit that shows the most time is: "+maxOccurring(all));
}
static int countOccurrences(int x,int d) {
int count = 0;
while (x > 0)
{
if (x % 10 == d)
count++;
x = x / 10;
}
return count;
}
static int maxOccurring( int x)
{
if (x < 0)
x = -x;
int result = 0;
int max_count = 1;
for (int d = 0; d <= 10; d++)
{
int count = countOccurrences(x, d);
if (count >= max_count)
{
max_count = count;
result = d;
}
}
return result;
}
}
```

You get an NumberFormatException at the following line:
int all = Integer.parseInt(sum);
Exception trace is:
Exception in thread "main" java.lang.NumberFormatException: For input string: "25445648942"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at scan.ScannerTest.main(ScannerTest.java:27)
This exception is telling you that Integer.parseInt can't interpret the number you're passing through it (obtained by concatenating all the entered digits), in this precise example: "25445648942"
That's because this function is trying to yield an Integer from all those digits, which has a maximum capacity of 2^31 - 1 = 2,147,483,647. The entered number is higher that this, so it logically fails.
You should treat each entered number separately and count the digits in each, then do a sum of all to get your answer.
BTW, you don't ever need to convert to a number type to count the digits. It's simple string processing

Related

Program is running but I get error when the user inputs integers

My program runs but I'm getting an error String index out of range: 3 When I enter 1 2 for example. I tried changing the values of 1 in partStr = str.substring(lastSpace + 1, x); but that didn't work. Any ideas what I'm doing wrong?
public static void main(String[] args) {
String str;
int x;
int length;
int start;
int num;
int lastSpace = -1;
int sum = 0;
String partStr;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a series of integers separated by spaces >> ");
str = keyboard.nextLine();
length = str.length();
for (x = 0; x <= length; x++) {
if (str.charAt(x) == ' ') {
partStr = str.substring(lastSpace + 1, x);
num = Integer.parseInt(partStr);
System.out.println(" " + num);
sum += num;
lastSpace = x;
}
}
partStr = str.substring(lastSpace + 1, length);
num = Integer.parseInt(partStr);
System.out.println(" " + num);
sum += num;
System.out.println(" -------------------" + "\nThe sum of the integers is " + sum);
}
You should traverse upto length - 1.
The indexing in String is similar to what happens in arrays.If the length of String is 5 for example,the characters are stored in 0-4 index positions.
Your current loop is traversing beyond the size of the string.
str.length() will return the amount of characters of the string, let's say N
for(x = 0; x <= length; x++) will loop N+1 times, instead of N, because the index starts at 0 and you also enter the loop when x is equal to the length
replacing <= with < in the for loop will fix your problem
The issue you faced is because you tried to access a character at the index, x (i.e. str.charAt(x)) from str where x is beyond the maximum value of the index in str. The maximum value of the index in str is str.length - 1 whereas the for loop is running up to str.length. In order to fix that problem, you need to change the condition to x < length.
However, even after fixing that issue, your program may fail if any entry is non-integer or if there are multiple spaces in the input. A clean way, including exception handling, to do it would be as follows:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String str;
int sum = 0;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a series of integers separated by spaces >> ");
str = keyboard.nextLine();
// Split str on space(s) and assign the resulting array to partStr
String[] partStr = str.split("\\s+");
// Iterate through partStr[] and add each number to sum
for (String num : partStr) {
try {
sum += Integer.parseInt(num);
} catch (NumberFormatException e) {
// Integer::parseInt will throw NumberFormatException for a non-integer string.
// Display an error message for such entries.
System.out.println(num + " is an invalid entry");
}
}
// Display the entries and the sum
System.out.println("Your entries are: " + Arrays.toString(partStr));
System.out.println("The sum of the integers is " + sum);
}
}
A sample run:
Enter a series of integers separated by spaces >> 10 a 20 10.5 30 b xy 40
a is an invalid entry
10.5 is an invalid entry
b is an invalid entry
xy is an invalid entry
Your entries are: [10, a, 20, 10.5, 30, b, xy, 40]
The sum of the integers is 100

The sum of certain digits from an input number

I've been trying to sum a certain digit from a number, for example
Number: 5
Input: 54365
Output: The sum of 5's is 10
Second example:
Number: 5
Input: 5437555
Output: The sum of 5's is 20
I've managed to separate the digits yet I couldn't find the condition to sum
a certain number (for instance number 5 like the examples).
I'd appreciate to hear your idea of doing it
public static void main(String[] args) {
int sum = 0;
int number = MyConsole.readInt("Enter a number:");
while (number > 0) {
if (number % 10 == 8) {
sum += 8;
} else {
number /= 10;
}
}
System.out.println("The sum of 8's is:" + sum);
}
My way of separating the numbers.
Also i have a small program to get input instead of using scanner since we still haven't went through it in class.
Your requirement seems reasonably clear to me.
Given a number
final int number = 5;
And a starting number
final int input = 54365;
The easiest way is to convert that number to a String
final int inputStr = String.valueOf(input);
Then, you can filter each char for it, and sum them
final int sum =
inputStr.chars() // Get a Stream of ints, which represent the characters
.map(Character::getNumericValue) // Convert a char to its numeric representation
.filter(i -> i == number) // Filter for the designated number
.sum(); // Sum all the filtered integers
Output: 10
Using the same approach, but with an old-style for loop
final int input = 54365;
final int inputStr = String.valueOf(input);
final int number = 5;
int sum = 0;
for (final char c : inputStr.toCharArray()) {
final int n = Character.getNumericValue(c);
if (n == number) {
sum += number;
}
}
Your solution can work
int number = 5;
int input = 543655;
int sum = 0;
while (input > 0) {
if (input % 10 == number) {
sum += number;
}
input /= 10;
}

Largest Occurrence Count

Im new to programming and am stumped on this problem, Ive tried a few different ways with no success.
Implement (source code) a program (name it LargestOccurenceCount) that read from the user positive non-zero integer values, finds the largest value, and counts it occurrences. Assume that the input ends with number 0 (as sentinel value to stop the loop). The program should ignore any negative input and should continue to read user inputs until 0 is entered. The program should display the largest value and number of times it appeared
Scanner reader = new Scanner(System.in);
int num = 0;
int array[] = null;
while ((num = reader.nextInt()) != 0) {
System.out.println("Enter a positive integer (0 to quit): ");
num = reader.nextInt();
array[num] = num;
}
Sample run 1:
Enter positive integers (0 to quit): 3 4 5 -9 4 2 5 1 -5 2 5 0
Largest value: 5
Occurrences: 3 times
The program should output the largest value entered and the number of times it was entered before 0 is entered.
You can use the following snippet:
// part of reading the values from command line and
// putting them into this array is omitted
int[] array = ...;
int biggest = 0;
int occurance = 0;
for(int num : array) {
if(num > biggest) {
biggest = num;
occurance = 0;
}
if(num == biggest) {
occurance++;
}
}
System.out.printf("Biggest number %s occured %s times.%n", biggest, occurance);
As mentioned in the comment, I've omitted the part where you read the values from the command line, as that doesn't seem to be your problem.
Another solution which does the reading directly, and without the need of an array and all inside one loop:
Scanner scanner = new Scanner(System.in);
int biggest = 0;
int occurance = 0;
int num;
while (true) {
System.out.print("Enter a number: ");
// this may throw an Exception if the users input is not a number
num = Integer.parseInt(scanner.nextLine());
if(num == 0) {
// user entered a 0, so we exit the loop
break;
}
if(num > biggest) {
biggest = num;
occurance = 1;
} else if(num == biggest) {
biggest++;
}
}
System.out.printf("Biggest number %s occured %s times.%n", biggest, occurance);
Split your problem into two parts.
1. Find the largest value
int findLargest(int[] array) {
assert array.length > 0;
int result = array[0];
for (int element : array) {
if (element > result) {
result = element;
}
}
return result;
}
... and find it in the array
int countOccurences(int[] array, int value) {
int occurences = 0;
for (int element : array) {
if (element == value) {
occurences++;
}
}
return occurences;
}
Note that array should have at least one element;
If there is no requirements to use array only, you can use ArrayList for storing user inputs
List<Integer> list = new ArrayList<>();
while ((num = reader.nextInt()) != 0) {
System.out.println("Enter a positive integer (0 to quit): ");
num = reader.nextInt();
list.add(num);
}
Then if you are good with stream api, there is quite concise solution:
Map.Entry<Integer, Long> lastEntry = list.stream()
.collect(groupingBy(Function.identity(), TreeMap::new, counting()))
.lastEntry();
System.out.println(
"Largest value: " + lastEntry.getKey() +
" Occurrences: " + lastEntry.getValue() + " times");

Find consecutive number of 1's

I am trying to find the number of consecutive 1's in a binary.
Example: Convert Decimal number to Binary and find consecutive 1's
static int count = 0;
static int max = 0;
static int index = 1;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
scan.close();
String b = Integer.toBinaryString(n);
char[] arr = b.toCharArray();
System.out.println(arr);
for (int i = 0; i < b.length(); i++) {
if (arr[i] == index) {
count++;
} else {
count = 0;
}
if (count > max) {
max = count;
}
}
System.out.println(max);
}
I am always getting 0. It seems as if the condition is not working in my code. Could you please provide your suggestion on where am I going wrong with this?
Your qusetion is not so clear but AFAIU from your algorithm, you're trying to find number of most repeated 1's. The issue is that when you're doing comparision if (arr[i] == index), the comparison is done with a char and integer because type of arr is char array. Isn't it? To overcome it either you can convert the char array into integer or convert the integer index value into char. I do this to overcome it.
if (arr[i] == index + '0')
It is not an really elegant solution. I assume that you're a student and want you to show what's wrong. If I want to do something like this, I use,
private static int maxConsecutiveOnes(int x) {
// Initialize result
int count = 0;
// Count the number of iterations to
// reach x = 0.
while (x!=0) {
// This operation reduces length
// of every sequence of 1s by one.
x = (x & (x << 1));
count++;
}
return count;
}
Its trick is,
11101111 (x)
& 11011110 (x << 1)
----------
11001110 (x & (x << 1))
^ ^
| |
trailing 1 removed
As I understand correctly, you want to count maximum length of the group of 1 in the binary representation of the int value. E.g. for 7917=0b1111011101101 result will be 4 (we have following groups of 1: 1, 2, 3, 4).
You could use bit operations (and avoid to string convertation). You have one counter (to count amount of 1 in the current group) and max with maximum of all such amounts. All you need is just to check lowest bit for 1 and then rotate value to the right until it becomes 0, like getMaxConsecutiveSetBit1.
Or just do it in a very simple way - convert it to the binary string and count amount of 1 characters in it, like getMaxConsecutiveSetBit2. Also have one counter + max. Do not forget, that char in Java is an int on the JVM level. So you do not have compilation problem with compare char with int value 1, but this is wrong. To check if character is 1, you have to use character - '1'.
public static void main(String[] args) {
try (Scanner scan = new Scanner(System.in)) {
int val = scan.nextInt();
System.out.println(Integer.toBinaryString(val));
System.out.println(getMaxConsecutiveSetBit1(val));
System.out.println(getMaxConsecutiveSetBit2(val));
}
}
public static int getMaxConsecutiveSetBit1(int val) {
int max = 0;
int cur = 0;
while (val != 0) {
if ((val & 0x1) != 0)
cur++;
else {
max = Math.max(max, cur);
cur = 0;
}
val >>>= 1;
}
return Math.max(max, cur);
}
public static int getMaxConsecutiveSetBit2(int val) {
int max = 0;
int cur = 0;
for (char ch : Integer.toBinaryString(val).toCharArray()) {
if (ch == '1')
cur++;
else {
max = Math.max(max, cur);
cur = 0;
}
}
return Math.max(max, cur);
}
Change type of index variable from int to char:
static char index = 1;
to let the comparison made in this line:
if (arr[i] == index)
do its job. Comparing int 1 (in your code this is the value stored in index variable) with char '1' (in your example it's currently checked element of arr[]) checks if ASCII code of given char is equal to int value of 1. This comparison is never true as char '1' has an ASCII code 49 and this is the value that is being compared to value of 1 (49 is never equal to 1).
You might want to have a look at ASCII codes table in the web to see that all characters there have assigned corresponding numeric values. You need to be aware that these values are taken into consideration when comparing char to int with == operaror.
When you change mentioned type of index to char, comparison works fine and your code seems to be fixed.
Using your for loop structure and changing a few things around while also adding some other stats to report which could be useful. I count the total number of 1's in the number, the number of consecutive 1's (groups of 1's), and the greatest number of consecutive 1's. Also your for loop was looping based on the string length and not the array's length which is just sort of nit picky. Here is the code
int count = 0;
int max = 0;
char index = '1';
int consecutiveOnePairs = 0;
int numberOfOnes = 0;
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
String b = Integer.toBinaryString(n);
char[] arr = b.toCharArray();
System.out.println(arr);
for (int i = 0; i < arr.length; i++) {
if (arr[i] == index)
{
count++;
numberOfOnes++;
}
if((i + 1 == arr.length && count > 1) || arr[i] != index)
{
if(count > 1)
consecutiveOnePairs++;
if (count > max)
max = count;
count = 0;
}
}
System.out.println("Total Number of 1's in " + n + " is " + numberOfOnes);
System.out.println("Total Number of Consecutive 1's in " + n + " is " + consecutiveOnePairs);
System.out.println("Greatest Number of Consecutive 1's in " + n + " is " + max);
scan.close();
Output
13247
11001110111111
Total Number of 1's in 13247 is 11
Total Number of Consecutive 1's in 13247 is 3
Greatest Number of Consecutive 1's in 13247 is 6
511
111111111
Total Number of 1's in 511 is 9
Total Number of Consecutive 1's in 511 is 1
Greatest Number of Consecutive 1's in 511 is 9
887
1101110111
Total Number of 1's in 887 is 8
Total Number of Consecutive 1's in 887 is 3
Greatest Number of Consecutive 1's in 887 is 3
If you use Java 8, you can try this snippet:
public int maxOneConsecutive(int x)
{
String intAsBinaryStr = Integer.toBinaryString(x);
String[] split = intAsBinaryStr.split("0");
return Arrays.stream(split)
.filter(str -> !str.isEmpty())
.map(String::length)
.max(Comparator.comparingInt(a -> a)).orElse(0);
}

Reversing an integer in Java using a for loop

This is a homework problem
How would I reverse an integer in Java with a for loop? The user will input the integer (I don't know how long it will be) and I need to reverse it. ie: If they enter 12345, my program returns 54321.
Here's the catch, you can't use String, StringBuffer, arrays, or other advanced structures in this problem.
I have a basic idea of what I need to do. My problem is...in the for loop, wouldn't the condition need to be x < the length of the integer (number of digits)? How would I do that without String?
Thanks for any input, and I'll add more information if requested.
EDIT:
Of course, after introspection, I realized I should use another for loop to do this. What I did was create a for loop that will count the digits by dividing by 10:
int input = scan.nextInt();
int n = input;
int a = 0;
for (int x = 0; n > 0; x++){
n = n/10;
a = a + 1;
}
EDIT 2:
This is what I have
int input = scan.nextInt();
int n = input;
int a = 0;
int r = 0;
for (int x = 0; n > 0; x++){
n = n/10;
a = a + 1;
}
for (int y = 0; y < n; y++) {
r = r + input%10;
input = input/10;
}
System.out.println(input);
When I run it, it isn't reversing it, it's only giving me back the numbers. ie: if I put in 1234, it returns 1234. This doesn't make any sense to me, because I'm adding the last digit to of the input to r, so why wouldn't it be 4321?
While your original number is nonzero, take your result, multiply it by 10, and add the remainder from dividing the original by 10.
For example, say your original number is 12345. Start with a result of 0.
Multiply result by 10 and add 5, giving you 5. (original is now 1234.)
Multiply result by 10 and add 4, giving you 54. (original is now 123.)
Multiply result by 10 and add 3, giving you 543. (original = 12.)
Multiply result blah blah 5432. (original = 1.)
Multiply, add, bam. 54321. And 1 / 10, in int math, is zero. We're done.
Your mission, should you choose to accept it, is to implement this in Java. :) (Hint: division and remainder are separate operations in Java. % is the remainder operator, and / is the division operator. Take the remainder separately, then divide the original by 10.)
You will need to use math to access each of the digits. Here's a few hints to get your started:
Use the % mod operator to extract the last digit of the number.
Use the / division operator to remove the last digit of the number.
Stop your loop when you have no more digits in the number.
This might not be the proper way but
public static int reverseMe(int i){
int output;
String ri = i + "";
char[] inputArray = ri.toCharArray();
char[] outputArray = new char[inputArray.length];
for(int m=0;m<inputArray.length;m++){
outputArray[inputArray.length-m-1]=inputArray[m];
}
String result = new String(outputArray);
output = Integer.parseInt(result);
return output;
}
public static void reverse2(int n){
int a;
for(int i = 0; i < n ; i ++){
a = n % 10;
System.out.print(a);
n = n / 10;
if( n < 10){
System.out.print(n);
n = 0;
}
}
}
here is the Answer With Correction of Your Code.
import static java.lang.Math.pow;
import java.util.*;
public class MyClass {
public static void main(String args[]) {
Scanner scan=new Scanner(System.in);
int input = scan.nextInt();
int n = input;
int a = 0;
int r = 0;
for (; n > 0;){
n = n/10;
a = a + 1;
}
for (int y = 0; y < input;a--) {
r =(int)( r + input%10*pow(10,a-1));
input = input/10;
}
System.out.println(r);
}
}

Categories