My code is supposed to prompt the user for an integer and count the occurrences of each digit in the integer. But it outputs nothing. Please help and here's my code.
import java.util.Scanner;
public class NumberCounts {
public static void main(String [] args) {
Scanner scan = new Scanner(System.in);
int arr [] = new int [10];
int num;
int outcome;
System.out.println(" Enter a number: ");
num = scan.nextInt();
while ( num != 0){
outcome = num % 10;
arr[num % 10]+=1;
num /= num;
}
for ( int i = 0; i <= arr.length; i++){
System.out.println(i + " : " + arr[i]);
}
}
}
Inside your while loop, you are dividing num by itself, then assigning the result back to num. This will make num equal to 1 forever. Change it to
num /= 10;
which will remove the last digit.
Also, you already calculated the last digit and stored the result in outcome. You might as well use it:
arr[outcome]+=1;
Then, when you get to the loop to print the array, in the condition, always use < an array length to stop after processing the last index length - 1. This will prevent the ArrayIndexOutOfBoundsException that is waiting to show up.
for (int i = 0; i < arr.length; i++){
Related
I'm having trouble doing my code since I'm learning from scratch I don't have any idea how I'm going to print out a reversed input from my array.
This is what I have so far:
import java.util.Scanner;
public class ReverseList {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] array = new int[10];
int num = 0;
int count = 0;
int total = 1;
loop:
for (count = 0; count <= 10; count++) {
System.out.print("Enter a number (999 to quit): ");
num = scan.nextInt();
if (num == 999) {
break loop;
}
if (count == 9) {
break loop;
}
array[count] = num;
total = count+1;
}
System.out.print("\n The list reversed is:" );
//List Reversed
}
}
And the application output should look similar to:
Enter a number (999 to quit): 19 <enter>
Enter a number (999 to quit): 44 <enter>
Enter a number (999 to quit): 25 <enter>
Enter a number (999 to quit): 16 <enter>
Enter a number (999 to quit): 999 <enter>
The list reversed is: 16 25 44 19
Your current code has a few bugs. First, total should be incremented by one (not count). You should not embed a test on count in the loop. You should not rely on so many different magic numbers. Finally, to print the array contents reversed start with the total number of elements and count backwards. Like,
Scanner scan = new Scanner(System.in);
int[] array = new int[10];
int total = 0;
for (int count = 0; count < array.length; count++) {
System.out.print("Enter a number (999 to quit): ");
int num = scan.nextInt();
if (num == 999) {
break;
}
array[count] = num;
total++;
}
System.out.println("The list reversed is:");
for (int count = total - 1; count >= 0; count--) {
System.out.println(array[count]);
}
Do some loop but reversed with i--.
Little explanation:
int i value will be 9, i >= 0 doing this loop to array index 0, i-- will decrease the value each time iteration executed.
for (int i = array.length-1; i >= 0; i--){
System.out.print(array[i]+" ");
}
Along with the other answers regarding a naïve method of reversing an array,
I can suggest the following method to reverse an array:
Using Swapping Technique
In this method, we swap the first element of array with the last element of the array, the second first with the second last, the third first with the third last and so on. This will be repeated until all the elements are swapped. The original array gets replaced by the reversed array.
Implementation of the reverse function is given below:
static void reverse(int array[], int sizeOfArray) {
int i, k, t;
for (i = 0; i < sizeOfArray / 2; i++) {
t = array[i];
array[i] = array[n - i - 1];
array[n - i - 1] = t;
}
I'm not sure what to title this question(if anyone has input on what to name the question, please let me know). My program asks the user for 5 int and 5 doubles. Then those numbers are put in an array and passes it to a method to get the average. My question is if I separate the user input by spaces and press enter(like so, 5 space 6...enter; it allows me to enter more than what is allowed in the array index. Why doesn't it give you a error? and how do you prevent this? Also any advice on how I write code would be helpful too!
Here is the code.
import java.util.*;
public class Lab7A_BRC{
public static void main(String[] args) {
System.out.println("\t\t Average arrays ");
Scanner input = new Scanner(System.in);
//array count varriable
int n = 5;
//array declaration
int [] list1 = new int[n];
double [] list2 = new double[n];
System.out.print("Enter 5 integer values. ");
for(int i = 0; i < n; i++) {
list1[i]= input.nextInt();
if(i == (n - 1)){
System.out.println("\t The average of the 5 integers is "
+ average(list1, n));
}
}
System.out.println("Enter 5 double values. ");
for (int i = 0; i < n; i++){
list2[i]= input.nextDouble();
if(i == (n-1)){
System.out.println("\t The average of the 5 doubles is "
+ average(list2, n));
}
}
}
public static int average(int[] array, int n){
int sum = 0;
for(int i = 0; i < n; i++){
int holdNumber = array[i];
sum += holdNumber;
}
int average = sum / n;
return average;
}
public static double average(double[] array, int n){
double sum = 0;
for(int i = 0; i < n ; i++){
double holdNumber = array[i];
sum += holdNumber;
}
double average = sum / n;
return average;
}
}
It doesn't give you an error because you only read the first 5 values, as stated in your for loop.
The first thing is you should decouple your input logic from your output logic, so you know for sure you're in your 5th number when you exit the for loop.
Then you can check if there's anything else than a blank string left, if there is then you can throw an exception stating it has too many numbers.
I've adapted the integer part, you can easily adapt the doubles logic.
Feel free to ask if you have any doubts.
The adapted code:
import java.util.Scanner;
public class Lab7A_BRC {
public static void main(String[] args) {
System.out.println("\t\t Average arrays ");
Scanner input = new Scanner(System.in);
//array count varriable
int n = 5;
//array declaration
int[] list1 = new int[n];
double[] list2 = new double[n];
System.out.print("Enter 5 integer values. ");
for (int i = 0; i < n; i++) {
list1[i] = input.nextInt();
}
if (!input.nextLine().equals("")) {
throw new RuntimeException("Too many numbers entered!");
}
System.out.println("\t The average of the 5 integers is "
+ average(list1, n));
System.out.println("Enter 5 double values. ");
for (int i = 0; i < n; i++) {
list2[i] = input.nextDouble();
if (i == (n - 1)) {
System.out.println("\t The average of the 5 doubles is "
+ average(list2, n));
}
}
}
public static int average(int[] array, int n) {
int sum = 0;
for (int i = 0; i < n; i++) {
int holdNumber = array[i];
sum += holdNumber;
}
int average = sum / n;
return average;
}
public static double average(double[] array, int n) {
double sum = 0;
for (int i = 0; i < n; i++) {
double holdNumber = array[i];
sum += holdNumber;
}
double average = sum / n;
return average;
}
}
I think you're confusing two different concepts.
One is the input, and another one is your variable.
Input is a buffer (read: block of data) managed by the shell and the Scanner. It can contain an arbitrary amount of data, you have nothing to do with it.
What happens in your code is that the scanner takes the buffer and parses (read: interprets) the next valid value from the buffer and transforms it into the right data type - until the "nth" element. So, because you're taking "n" elements (controlled by the for), it doesn't matter how much data is available in the input buffer, you always read a finite amount.
The only way the amount of data matters is when there's no more input for the scanner to read from, in which case it asks for more input.
The reason is that you are iterating till the n number that you defined in the beginning.
for(int i = 0; i < n; i++) {
list1[i]= input.nextInt();
So if you try to enter 1 1 1 1 1 124124 1241 you will see that the average is 1 because the rest is ignored and not added to the list. Because it doest not try nextInt() more than n given.
I am a beginner, so my answer might be wrong:), sorry for that. This code is working for me. Like #iajrz mentioned, you can do spaece or newline when try to use system.in.
Because the for loop does n iterations so you pick up only the first n integers of the input. If your input is 1 2 3 4 5 6 7 8 it will select only 1 2 3 4 5 (because in your code n=5). You can also insert multiple digits number separated by spaces, so input 15 0 00 0010 0 has average=5
I need to write a program that asks for 20 numbers and outputs the amount of even numbers. I figured out the loop part (for-loop) but i don't have any idea how to collect the data if that makes any sense.
Here is the loop:
for (int num = 0; num < 20; num++) {
System.out.println("Anna luku");
num = input.nextInt();
}
If you want to give the numbers when you run the program you can use this:
public static void main(String[] args) {
int counter=0;
Scanner sc = new Scanner(System.in);
System.out.println("Write 20 numbers:");
for(int i=0; i<20; i++) {
System.out.print("Number " + i + ":");
int temp =sc.nextInt(); //this waits for you to write an int
if(temp%2==0)
counter++;
}
sc.close();
System.out.println("Even numbers:" + counter);
}
i've tested it ant it works, keep in mind that you need to press enter after you write each number
You can use the code like this:
int count = 0;
for (int num = 0; num < 20; num++) {
System.out.println("Anna luku");
if (input.nextInt() % 2 == 0)
count++;
}
You can use the modulo operator to check if a number is divisible by another number (in this case - by 2). Note, BTW, that your code overwrites the loop variable, which is probably not what you meant:
int evens = 0;
for (int i = 0; i < 20; i++) {
num = input.nextInt();
if (num % 2 == 0)
evens++;
}
}
System.out.prinf("You inputted %d even numbers%n", evens);
Do you mean some thing like this ?
Scanner input = new Scanner(System.in);
int inputs[] = new int[20];
System.out.printf("Please enter %d numbers\n",inputs.length);
for(int i = 0; i < inputs.length;i++){
System.out.println("Enter value number "+(i+1));
int value = input.nextInt();
inputs[i]=value;
}
I'm new in Java and I try to find the sum of first three digits in int number.
I have a number 123456 I want to find the sum of first three digits 123 and then find sum of last three digits 456 and then compare it. I can't understand how to do this. I code next:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number:");
int number = scanner.nextInt();
int length = (int) Math.ceil(Math.log10(number));
for (int i = 1; i <= 3; i++) {
System.out.println(i);
}
System.out.println(length);
System.out.println(number);
}
I think that I shoud to use for loop, but I'm not sure. I know how to count the length of a number. But how to how to find the sum of the first three numbers and last three?
Assuming your length is constant (6):
String first = (""+number).substring(0, 3);
String second = (""+number).substring(3, 6);
int firstSum = 0;
int secondSum = 0;
for (int x = 0; x < first.length; x++)
firstSum += Integer.parseInt(first.charAt(x)+"");
for (int x = 0; x < second.length; x++)
secondSum += Integer.parseInt(second.charAt(x)+"");
System.out.println("Sum of first 3: " + firstSum);
System.out.println("Sum of second 3: " + secondSum);
Read the String API- it has a lot of useful methods. For small programs like this, it's usually pretty easy to convert to String, use String methods, then parse back to int.
EDIT: Andy Turner and Jeremy Kato informed me about Character.getNumericValue(). Thus, the statement:
firstSum += Integer.parseInt(first.charAt(x)+"");
Could be changed to:
firstSum += Character.getNumericValue(first.charAt(x));
Likewise for secondSum.
First, probably should correct your spelling of length - though maybe not, because you don't really need that variable to do this.
What your code should do to make this easier for you is to not convert the input into an int immediately. You'll first want to split the input string into two pieces, then take the two numbers and sum them up with a loop.
Here's my idea of what I'd do:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number:");
String input = scanner.nextLine();
String firstHalf = input.substring(0, 3); // note that depending on how
// many digits you want to change, these numbers must change as well.
String secondHalf = input.substring(3);
int sum1 = 0;
int sum2 = 0;
// don't forget: start at 0, not 1!
for(int i = 0; i<=3; i++){
sum1 += Character.getNumericValue(firstHalf.charAt(i));
sum2 += Character.getNumericValue(secondHalf.charAt(i));
// this call to the Character class converts a character to an int.
}
System.out.println(sum1);
System.out.println(sum2);
}
Just note that this code is made to work with your input being 6 characters, and it assumes they're going to be numbers. It'll crash if you enter too few characters in or if you put letters in, but you can always worry about that later.
Here's a straightforward way of doing it, making the assumption that your integer has an even number of digits...
public class Test {
public static void main(String[] args) {
// Makes the assumption that the input integer contains an even number of digits.
int x = 123456;
String s = Integer.toString(x);
int[] count = new int[2];
for (int i = 0; i < s.length(); i++) {
int digit = Integer.parseInt(s.substring(i, i + 1));
int countIndex = (int)Math.floor(i * 2 / s.length());
count[countIndex] += digit;
}
int half = s.length() / 2;
System.out.println("First Sum of " + s.substring(0, half) + ": " + count[0]);
System.out.println("Second Sum of " + s.substring(half) + ": " + count[1]);
}
}
Alternate Method
Here's another way of doing it without using the arrays above, and actually simplified the logic by abstracting the sum to a method.
public class Test {
public static void main(String[] args) {
// Makes the assumption that the input integer contains an even number of digits.
int x = 123456;
String s = Integer.toString(x);
int half = s.length() / 2;
String firstHalf = s.substring(0, half);
String secondHalf = s.substring(half);
System.out.println(firstHalf);
System.out.println(secondHalf);
int sum1 = sumString(firstHalf);
int sum2 = sumString(secondHalf);
System.out.println("Sum 1: " + sum1);
System.out.println("Sum 2: " + sum2);
}
private static int sumString(String s) {
int sum = 0;
for (int i = 0; i < s.length(); i++) {
sum += Integer.parseInt(s.substring(i, i + 1));
}
return sum;
}
}
Here is an alternative solution which doesn't use Strings or arrays:
public static void main(String args[]){
int num=123456;
int second = 0;
int first = 0;
second = addLastThree(num);
num /= 1000;
first = addLastThree(num);
System.out.println("first -- > " + first);
System.out.println("second -- > " + second);
}
static int addLastThree(int num){
int sum = 0;
for (int i =0; i<3; i++){
sum += (num/Math.pow(10,i)) % 10;
}
return sum;
}
you can try this code and every line was explained in comments.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number:");
int number = scanner.nextInt();
int n=number; //duplicating the value for the reference.
int l = (int) Math.log10(number) + 1; //Length of the number
int half = l/2; //to find half length of the number to sum first and last digits seperately.
int last_Sum = 0; //to store sum of last digits
int first_Sum = 0; //to store sum of first digits
for(int i=0; i<half && number>0; i++){ //to sum last digits
last_Sum = last_Sum + number%10;
number = number/10;
}for(int i=0; i<half && number>0; i++){ //to sum first digits
first_Sum = first_Sum + number%10;
number = number/10;
}
System.out.println("Length of the number "+l);
System.out.println("Number is "+n);
System.out.println("Sum of last digits "+last_Sum);
System.out.println("Sum of first digits "+first_Sum);}}
I'm trying to get both, the largest number and the largest occurring number, from a user input. The problem with my code is it only returns the first value of the array.
public class CountMax {
public static void main(String [] args) {
//Create scanner object
Scanner input = new Scanner(System.in);
//Obtain user input
System.out.println("Enter numbers: ");
int num = input.nextInt();
int array[] = new int[num];
//loop through array
int max = array[0];
int count = 1;
for (int i = 0; i < array.length; i++) {
array[i] = num;
if(array[i] > max) {
max = array[i];
count = 1;
} else if(array[i] == max) {
count++;
}
}
//output results
System.out.println("The largest number is " + max);
System.out.println("The occurrence count of the largest number is " + count);
}}
I know this post is old, but Wyatt Lowery's solution is incorrect, just in case someones stumbles upon it from Google just like I did. You cannot count the number of max values in an array in the same loop like that until you have found the max value.
Example using Wyatt's class: 2 is obviously an incorrect answer.
Enter numbers:
1, 2, 3, 4, 5, 5, 7
The largest number is 7
The occurrence count of the largest number is 2
I would do:
int max = array[0];
int sum = 0;
for(int i = 1; i < array.length; i++) {
if(array[i] > max) max = array[i];
}
for(int i = 0; i < array.length; i++) {
if(array[i]==max) sum++;
}
One problem I noticed:
int num = input.nextInt();
When you do this, it is only going to take the first int (Meaning, only 1 number) As well when you are creating your array int array[] = new int[num], you are creating an array with the SIZE of num, and not actually creating an array with the VALUES of num. (Even though num is only a single number) To actually create an array of numbers, do something like this:
System.out.pritnln("Enter in numbers:");
String[] array = input.nextLine().split(", ");
An example input would be: "13, 12, 14, 14". Then the contents of the array would be those terms (And would remove spaces & commas). Your program should look something like this when finished:
public class CountMax {
public static void main(String [] args) {
//Create scanner object
Scanner input = new Scanner(System.in);
//Obtain user input
System.out.println("Enter numbers: ");
String[] array = input.nextLine().split(", ");
//Loop through array
int max = Integer.parseInt(array[0]);
int count = 0;
for (int i = 0; i < array.length; i++) {
if(Integer.parseInt(array[i]) > max) {
max = Integer.parseInt(array[i]);
} else if(Integer.parseInt(array[i]) == max) {
count++;
}
}
//Output
System.out.println("The largest number is " + max);
System.out.println("The occurrence count of the largest number is " + count);
}
}
Hope this helped :-)
Think more carefully about each step you need to take.
Do you know how many numbers will be entered by the user?
Right now you are only taking in one number because you are not looping on the input
int num = input.nextInt();
int array[] = new int[num];
Here, you are creating an array the size of whatever number the user entered. This is a correct approach, more typical of C, if the user will tell you "I will enter 10 numbers" and then enters the 10 numbers. This is convenient because you will know to loop 10 times, and you will need to count a maximum of 10 different numbers.
If we don't know how many numbers will be entered you will need to loop until EOF.. something like
while(input.hasNext()) {
int currentInt = input.next();
...
}
Now you have to consider how you will be counting these items.
I hope this gives you some things to think about towards your solution..