I'm new to programing and trying to solve this problem, but have no idea what I did wrong.
The program is supposed to take user input until 0 is entered and after that, print out information of occurrences of numbers user input - and here is my problem.
The program I wrote shows occurrences of all numbers (up to max number that can be input), not only those that user wrote.
My code:
package numbers;
import java.util.Scanner;
public class Numbers {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] occurences = new int[11];
int num = scan.nextInt();
while (num > 0 && num <= 11) {
occurences[num]++;
num = scan.nextInt();
}
for (int i = 0; i < 11; i++) {
System.out.print("Value: " + i + " Occurences: " + occurences[i] + " ");
}
}
}
Use if statement to print only numbers with occurences higher than 0.
Side notes:
Array values initialization is not needed:
for (int i = 0; i < 11; i++) {
occurences[i] = 0;
}
Value at each index is already 0, check this question.
While loop condition, does not make much sense
while (num > 0 && num <= 11) {
occurences[num]++;
num = scan.nextInt();
}
Array size is 11, meaning indexes range from 0 to 10 inclusive. Since you allow input 11, you will get ArrayIndexOutOfBoundsException.
You can make use of map.
Map<Integer, Integer> occ = new HashMap<>();
int num = scan.nextInt();
while (num > 0 && num <= 11) {
occ.put(num, occ.getOrDefault(num, 0)+1);
num = scan.nextInt();
}
for(int i : occ.keySet()){
System.out.print("Value: " + i + " Occurences: " + occ.get(i) + " ");
}
Related
How do I make the loop check if there is 16 digits in a string and reset the string if there is not enough. I am trying to make a credit card program that will calculate the check digit. I have everything else working I just cant get the program to check the number of digits in the user inputted string.Thanks for any and all help!
import java.util.Scanner;
public class LuhnAlgorithm {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number credit card number (Enter a blank line to quit: ");
String nums = input.nextLine();
int i = 0;
char chk = nums.charAt(15);
while(!nums .equals("") ) {
if (nums.length()<16 || nums.length() > 15){ //How do I get this line to reset the while loop?
System.out.println("ERROR! Number MUST have exactly 16 digits.");
}
int sum = 0;
for( i = 0; i < 15; i++) {
char numc = nums.charAt(i);
int num = Character.getNumericValue(numc);
if ( i % 2 == 0 ) {
num = num * 2;
if ( num >= 10) {
num = num - 9;
}
}
sum = num + sum;
}
int sum2 = sum % 10;
if (sum2 > 0) {
sum2 = 10 - sum2;
}
int chk2 = Character.getNumericValue(chk);
System.out.println("The check digit should be: " + sum2);
System.out.println("The check digit is: " + chk);
if ( sum2 == chk2) {
System.out.println("Number is valid.");
}
else {
System.out.println("Number is not valid. ");
}
System.out.print("Enter a number credit card number (Enter a blank line to quit:) ");
nums = input.nextLine();
}
System.out.println("Goodbye!");
input.close();
}
}
You can include your code that you only want done if the length ==16 in an if statement.
Meaning, instead of:
if (nums.length != 16) {
//code if there is an error
}
//code if there is no error
you can do:
if (nums.length == 16) {
//code if there is no error
} else {
//code if there is an error
}
(I also want to point out that you set chk = nums.charAt(15) before your while loop, but you don't reset it in the while loop for the next time the user inputs a new credit card number.)
You can bring the prompts and all your initialization except the scanner itself into the while loop. Then if they say "", break to exit the loop. If they say a number that is too short or too long, say continue to go back to the prompting.
Thus:
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Enter a number credit card number (Enter a blank line to quit: ");
String nums = input.nextLine().trim();
if (nums.length() == 0) {
break; //exits while loop
}
if (nums.length() != 16) { //How do I get this line to reset the while loop?
System.out.println("ERROR! Number MUST have exactly 16 digits.");
continue; //goes back to the beginning right away
}
//still here, process the number
char chk = nums.charAt(15);
int sum = 0;
for (int i = 0; i < 15; i++) {
char numc = nums.charAt(i);
int num = Character.getNumericValue(numc);
if (i % 2 == 0) {
num = num * 2;
if (num >= 10) {
num = num - 9;
}
}
sum = num + sum;
}
int sum2 = sum % 10;
if (sum2 > 0) {
sum2 = 10 - sum2;
}
int chk2 = Character.getNumericValue(chk);
System.out.println("The check digit should be: " + sum2);
System.out.println("The check digit is: " + chk);
if (sum2 == chk2) {
System.out.println("Number is valid.");
} else {
System.out.println("Number is not valid. ");
}
}
System.out.println("Goodbye!");
input.close();
}
}
I have an issue. My lecturer wants me to make a loop, with an input of JOptionPane and an output of console. How can I use loop for JOptionPane and send an output through console.
Here's my code:
int even = 0;
int odd = 0;
int e_e = 0;
int o_o = 0;
String a1 = JOptionPane.showInputDialog(null, "Type in 10 integer");
for (int counter = 0; counter < 10; counter++){
int a = Integer.parseInt(a1);
if (a % 2 == 0) {
even++;
e_e += a;
} else {
odd++;
o_o += a;
}
}
System.out.println("\n\nNumber of even numbers : " + even);
System.out.println("Number of odd numbers : " + odd);
System.out.println("Total of even numbers : " + e_e);
System.out.println("Total of odd numbers : " + o_o);
I would try using a DO-WHILE loop with and an int[], example:
int size = 10;
int count = 0;
int[] yourNumbers = new int[size];
do {
yourNumbers[count] = Integer.parseInt(JOptionPane.showInputDialog(null,
"Your message here."));
count++;
} while (count < 10);
This way you can loop through and grab all the numbers. Then you can use a FOR-LOOP to cycle through and print what you need
System.out.println("Even Numbers are: ");
for(int i = 0; i < yourNumbers.length; i++) {
if (yourNumbers[i] % 2 == 0) {
System.out.println(yourNumbers[i]);
}
}
System.out.println("Odd Numbers are: ");
for(int i = 0; i < yourNumbers.length; i++) {
if (yourNumbers[i] % 2 != 0) {
System.out.println(yourNumbers[i]);
}
}
The problem with your current code is that you only ask the user one time to input a number but you actually seem to want 10 values. So you parse ten times the same value.
The solution is simple, put the dialog inside the loop (only changed the lines with comments):
int even = 0;
int odd = 0;
int e_e = 0;
int o_o = 0;
// No return type, just a message
JOptionPane.showMessageDialog(null, "Type in 10 integer");
for (int counter = 0; counter < 10; counter++) {
// Dialog inside the loop, asking to
// input a number in every iteration
String value = JOptionPane.showInputDialog(null, "Type in "
+ (counter + 1) + ". value");
int a = Integer.parseInt(value);
if (a % 2 == 0) {
even++;
e_e += a;
} else {
odd++;
o_o += a;
}
}
System.out.println("\n\nNumber of even numbers : " + even);
System.out.println("Number of odd numbers : " + odd);
System.out.println("Total of even numbers : " + e_e);
System.out.println("Total of odd numbers : " + o_o);
Thanks for the answers guys, didn't expect getting answers so fast.
Ok so in this code at the final stage it is meant to count how many odd and evens numbers there are in the array length you decide.
If you for example type in 10 it prints out 10 random numbers between the intervall of 0-999 and then it seperates the odd and even numbers
In the last stage it's meant to calculate how many odd and even numbers there are like ''out of the 10 numbers 4 of them were even numbers and 6 were odd numbers''
Right now in the last stage it just prints out numbers randomly and doesen't calculate how many odd and even numbers there are. I don't know how to fix it.
I have ran out of ideas about it so hopefully someone here can make it work properly.
import java.util.Scanner;
public class Uppgift4 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int length;
while (true)
{
System.out.print(" \n\nHow many numbers do you want in the intervall 0-999?(turn off with -1 or 1000):");
length = scan.nextInt();
if (length>999)
{
System.out.print("\nValue outside intervall restart programm");
break;
}
if (length<0)
{
System.out.print("\nValue outside intervall restart programm");
break;
}
System.out.println("\n Here are the random numbers:");
int [] ar1 = new int[length];
for(int i = 0; i < length; i++) {
ar1[i] = (int)(Math.random() * 1000);
{
System.out.print(" "+ar1[i]);
}
}
System.out.println(" \n");
System.out.println(" Here are the numbers divided between even and odd numbers:");
System.out.print(" ");
for(int i = 0 ; i < length ; i++)
{
if(ar1[i] % 2 == 0)
{
System.out.print(ar1[i]+" ");
}
}
System.out.print("- ");
for(int i = 0 ; i < length ; i++)
{
if(ar1[i] % 2 != 0)
{
System.out.print(ar1[i]+" ");
}
}
System.out.println(" \n");
System.out.print(" Of the above numbers "+ length + " so ");
System.out.print("where ");
for(int evennumbers = 1 ; evennumbers < length ; evennumbers++)
{
if(ar1[evennumbers] % 2 == 0)
{
System.out.print(evennumbers+" ");
}
}
System.out.print(" of the numbers even and odd numbers were ");
for(int oddnumbers = 1 ; oddnumbers < length ; oddnumbers++)
{
if(ar1[oddnumbers] % 2 != 0)
{
System.out.print(oddnumbers+" ");
}
}
}
}
You need to count the number of even and odd number:
int even = 0;
int odd = 0;
// Loop through the final array
for(int i = 0 ; i < length ; i++)
{
if(ar1[i] % 2 == 0)
{
even++;
} else {
odd++;
}
}
Even simpler:
for(int i = 0 ; i < length ; i++)
{
odd += (ar1[i] % 2)
}
even = length - odd;
just make two global variables to count the odd and even and put them into the condition where you are checking for odd and even.
code
Why not just make use of bitwise AND and remove those conditionals like so:
int odd = 0;
int even = 0;
for(int i=0;i<length;i++){
odd+=ar1[i]&1;
even+=((ar1[i]+1)&1);
}
you can use this way , very simple
public static void main(String []args){
Integer[] arr = new Integer[] { 1,2,3,4,5};
int oddCount =0; int evenCount=0;
for ( int i=0; i< arr.length ;i++){
if( ( arr[i] % 2) == 0 )
evenCount++;
if( arr[i] % 2 != 0 )
oddCount++;
}
System.out.println( "oddCount in Array :" + oddCount + " EvenCount in Array : " + evenCount);
}
This code is designed to list off the prime numbers between a minimum and maximum input by the user. When the numbers are output at the end of the code, they are all on the same line. I would like there to be ten numbers per line, so I assume that it takes a loop of some kind to indent every ten numbers, however I don't know how to do this. While I have the code posted here, other, unrelated feedback would be helpful.
String primenumbers = "";
System.out.println("Prime Number Generator.");
System.out.print("Minimum: ");
int oldmin = s.nextInt();
s.nextLine();
int min = oldmin;
System.out.print("Maximum: ");
int max = s.nextInt();
s.nextLine();
System.out.println();
for (min = min; min <= max; min++)
{
int counter=0;
int num = min;
for(num = min; num >= 1; num--)
{
if(min % num == 0)
{
counter = counter + 1;
}
}
if (counter == 2)
{
primenumbers = primenumbers +min+ " ";
}
}
System.out.println("Primes Between "+oldmin+" & "+max+":");
System.out.print(primenumbers);
Instead of concatinating prime numbers into a string, you can add them into a list and iterate the list in the end, e.g.:
primenumbers = primenumbers +min+ " "; will be replaced with
List<Integer> primenumbers = new ArrayList<>();
primenumbers.add(min);
After System.out.println("Primes Between "+oldmin+" & "+max+":"); statement, you can do the following:
for(int i=0 ; i < primenumbers.size() ; i++){
System.out.print(primenumbers.get(i) + " ");
if(i+1 % 10 == 0){
System.out.println();
}
}
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
int[] array = new int[5];
System.out.print("Please enter five numbers. \na=");
array[0] = input.nextInt();
System.out.print("\nb=");
array[1] = input.nextInt();
System.out.print("\nc=");
array[2] = input.nextInt();
System.out.print("\nd=");
array[3] = input.nextInt();
System.out.print("\ne=");
array[4] = input.nextInt();
boolean totalIsZero = false;
for (int i=0;i<array.length ;i++) {
for (int j=1;i>j ;j++ ) {
if ((array[i] + array[j])==0) {
System.out.println("The numbers " + array[i] + " and " + array[j] + " have a total sum equal to 0.");
totalIsZero = true;
}
}
}
if (!totalIsZero) {
System.out.print("None of the numbers have a total sum of 0 with each other. ");
}
}
Here is some simple code I just wrote. Its task is to check if the sum between every two numbers in an array (consisting of five numbers) is equal to zero.
The problem I have is that when there are two pairs of numbers, both equal to 0, at the end of the program there is a message for one of the pairs only, not for both, as I expected.
How can I fix that, so the user can read that there are two pairs of numbers equal to 0?
Not sure if this will work perfectly because I haven't tested it and I haven't used java in a while, but just create the array the same way you do it in your post, but try the rest for the actual bulk of the function.
// various input calls above^ to create array
int count = 0;
for(int i = 0; i < array.length; i++)
{
for(int j = i + 1; j < array.length; j++)
{
if(array[i] + array[j] == 0)
{
System.out.println("The numbers " + array[i] + " and " +
array[j] +
" have a sum equal to zero.");
count++;
}
}
}
if(count == 0)
{
System.out.println("No sum between any numbers is equal to 0");
}