I have a program that reads a list of integers, and then display the number of even numbers and odd numbers. We assume that the input ends with 0. Here is the sample run of the program.
Input numbers: 1 2 3 4 5 6 7 8 9 0
Odd: 5 Even: 4
However, my result is
Odd: 5 and Even: 5.
The problem is that 0 is counted as an even number. This is my code
public class Q75 {
public static void main(String[] args){
java.util.Scanner input = new java.util.Scanner (System.in);
double [] numbers = new double[10];
System.out.print("Enter numbers: ");
for(int i = 0;i<numbers.length;i++){
numbers[i] = input.nextDouble();
}
int Evens = 0;
int Odd = 0;
for(int i = 0;i<numbers.length;i++){
if(numbers[i]%2 == 0){
Evens++;
}else{
Odd++;
}
}
System.out.println("The number of odd numbers: " + Odd);
System.out.println("The number of even numbers: " + Evens);
}
}
There are two options
A) Adding another branch in your if statements i.e.
if(number[i] > 0) {
if(number[i] % 2 >0)
Odd++;
else
Evens++;
}
NB: changing the else branch to else if(number[i] >0), you can do without the outer if condition.
B) Since the list of number ends with 0 you can put this as a condition in your for loop i.e.
for(int i =0; i < numbers.length && numbers[i] > 0 ; i++)
Also as a rule of thumb variable names in java start with a small letter
Just don't check the last element: Use i < numbers.length - 1
for(int i = 0;i < numbers.length - 1; i++) {
//
}
Related
Write a program to produce the following output for any given integer number between
1 and 9 inclusive.
Enter an integer value [1..9]: 6
1
12
123
1234
12345
123456
666666
66666
6666
666
66
6
I have done the top half but I can not figure out the bottom with the repeating user input.
package lab7;
import java.util.Scanner;
public class problem5 {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
System.out.println("Input an integer between 1 and 9");
int input = scan.nextInt();
while (input <= 9) {
for (int i = 1; i <= input; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j);
}
System.out.println();
}
break;
}
}
}
Expected result: included at the top; actual result so far (input of 5):
1
12
123
1234
12345
You're pretty close. You have a for loop that covers the first half of the output you want. You can add a second for loop to handle the second half of the output.
This is pretty similar to the first loop, but has a few small differences:
instead of the loop variable starting at 1 and increasing, this one starts at input and decreases each time through (i-- instead of i++)
instead of printing any of the loop variables (i or j), it prints the input value ("6" in your example)
for (int i = input; i > 0; i--) {
for (int j = 1; j <= i; j++) {
System.out.print(input);
}
System.out.println();
}
If I run that code locally – so your for loop, then this for loop, then the break statement – this is the output:
Input an integer between 1 and 9
6
1
12
123
1234
12345
123456
666666
66666
6666
666
66
6
I would prefer a more efficient algorithm, your current approach is O(n2); consider the digits '1' - '9'; if we store them in a String then we can take a simple substring of that String for each line at the top (for example, "123456789".substring(0, 3) -> "123") that can be used to generate the top through successive calls to substring. We can use a similar approach to build the bottom; use an array of all possible rows and iteratively call substring. Finally, don't forget to validate that input is between one and nine inclusive. Something like,
Scanner scan = new Scanner(System.in);
String digits = "123456789";
String[] btm = { "1", "22", "333", "4444", "55555",
"666666", "7777777", "88888888", "999999999" };
System.out.println("Input an integer between 1 and 9");
int input = scan.nextInt();
if (input < 1 || input > 9) {
System.err.printf("Invalid input: %d%n", input);
System.exit(1);
}
for (int i = 0; i < input; i++) {
System.out.println(digits.substring(0, i + 1));
}
for (int i = input - 1; i >= 0; i--) {
System.out.println(btm[input - 1].substring(0, i + 1));
}
So basically the assignment says i need to get a number 'n' from the user and for all the numbers between 1 to 'n' code the program to print all the numbers divided by 3 without residue && print ONLY the numbers that both (or one) of their digits equal to 5 or less, for example if the user give 22 the programs prints 3,12,21.
thats what ive done by now (the place i putted a question mark is where im having hard time to figure out what to do) so this code in not compiled yet :
public static void main(String[] args) {
Scanner get = new Scanner(System.in);
int num;
System.out.println("Enter A Random Number: ");
num = get.nextInt();
for (int i=1;i>0 && i<=num;i++) {
if (i%3==0 && ?)
System.out.println(i);
I'm a bit confused about the second part of your question but based on the first part and what I got from the second part ( that the sum of the digits of numbers that is equal or less to 5 should only be printed )
Here is the code for your program : (It should work perfectly, update me if you find any problems)
public static void main(String[] args) {
Scanner get = new Scanner(System.in);
int num;
System.out.println("User please enter a number of your choice : ");
num = get.nextInt();
for(int x = 1 ; x < num ; x++){
String number = ""+ x ;
int sum = 0 ;
for(int i = 0 ; i < number.length() ; i ++ ){
sum +=number.charAt(i)-'0' ; }
if(x % 3 == 0 && sum <= 5){
System.out.println(x) ; }
sum = 0 ;
}
}
divided by 3 without residue
If you understand what "without residue" means, then I assume you are familiar with modulo arithmetic. In programming, we have the modulo operator % which returns the remainder from a division. So 25 % 8 evaluates to 1. You can use this to get the digits of a number 21 % 10 evalutes to 1 which is exactly the ones digit. To get the the tens digit, we need to divide by 10 first 21 / 10 % 10 evaluates to 2. This works because integer division throws away the remainder.
This will do. So, you have to go through every digit so, I converted it into a string and then matched the regex for 1 to 5 on that character and then put it back in another string and it solves it.
public static void main(String[] args) {
Scanner get = new Scanner(System.in);
int num;
System.out.println("Enter A Random Number: ");
num =Integer.parseInt(get.nextLine());
for(int i =1;i<=num; i++){
if(i%3==0){
String input = Integer.toString(i);
String toPrint = "";
for(int j =0 ; j<input.length();j++){
if(Character.toString(input.charAt(j)).matches("^[1-5]$")){
toPrint+=Character.toString(input.charAt(j));
}
}
//check the length to avoid cases like 30,60 etc.
if(input.length()==toPrint.length()){
System.out.println(toPrint);
}
}
}
}
This is the question we were assigned :
Nine coins are placed in a 3x3 matrix with some face up and some face down. You can represent the state of the coins using a 3x3 matrix with values 0 (heads) and 1 (tails). Here are some examples:
0 0 0 1 0 1 1 1 0
0 1 0 0 0 1 1 0 0
0 0 0 1 0 0 0 0 1
Each state can also be represented using a binary number. For example, the preceding matrices correspond to the numbers:
000010000 101001100 110100001
There are a total of 512 possibilities, so you can use decimal numbers 0, 1, 2, 3,...,511 to represent all the states of the matrix.
Write a program that prompts the user to enter a number between 0 and 511 and displays the corresponding matrix with the characters H and T.
I want the method toBinary() to fill the array binaryNumbers. I realized that this does not fill in 0s to the left. I have to think that through but is that the only thing that is the problem?
//https://www.geeksforgeeks.org/java-program-for-decimal-to-binary-conversion/
import java.util.Scanner;
public class HeadsAndTails {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num = input.nextInt();
int[] binaryNumbers = toBinary(num);
for (int i = 0; i < 9; i++) {
printArr(binaryNumbers);
System.out.print(binaryNumbers[1]);
}
}
public static int[] toBinary(int inputtedNumber) {
int[] binaryNum = new int[9];
int i = 0;
while (inputtedNumber > 0) {
binaryNum[i] = inputtedNumber % 2;
inputtedNumber = inputtedNumber/2;
inputtedNumber++;
} return binaryNum;
}
public static void printArr(int[] arr) {
for (int i = 0; i < 9; i++) {
if (arr[i] == 0) {
System.out.print("H ");
} else {
System.out.print("T ");
}
if (arr[i+1] % 3 == 0) {
System.out.println();
} System.out.print(arr[i]);
}
}
}
Looks like you are incrementing the wrong variable in your while loop:
while (inputtedNumber > 0) {
binaryNum[i] = inputtedNumber % 2;
inputtedNumber = inputtedNumber/2;
i++; // NOT inputtedNumber
} return binaryNum;
Also note, a new int[9] is probably already initialized to 0, but if not, you could just loop 9 times, rather than until the inputtedNumber is 0:
for (int i = 0; i < 9; i++) {
binaryNum[i] = inputtedNumber % 2;
inputtedNumber = inputtedNumber/2;
}
return binaryNum;
Finally, I think your array might be backwards when you're done, so you may need to reverse it or output it in reverse order
I realize this is a homework assignment so you should stick with your current approach. However, sometimes it can be fun to see what can be achieved using the built in features of Java.
The Integer class has a method toBinaryString that's a good starting point:
int n = 23;
String s1 = Integer.toBinaryString(n);
System.out.println(s1);
Output: 10111
But as we can see, this omits leading 0s. We can get these back by making sure our number has a significant digit in the 10th place, using a little bit-twiddling:
String s2 = Integer.toBinaryString(1<<9 | n);
System.out.println(s2);
Output: 1000010111
But now we have a leading 1 that we don't want. We'll strip this off using String.substring, and while we're at it we'll use String.replace to replace 0 with H and 1 with T:
String s3 = Integer.toBinaryString(1<<9 | n).substring(1).replace('0','H').replace('1','T');
System.out.println(s3);
Output: HHHHTHTTT
Now we can print this string in matrix form, again using substring to extract each line and replaceAll to insert the desired spaces:
for(int i=0; i<9; i+=3)
System.out.println(s3.substring(i, i+3).replaceAll("", " ").trim());
Output:
H H H
H T H
T T T
If we're up for a bit of regex wizardry (found here and here) we can do even better:
for(String sl : s3.split("(?<=\\G.{3})"))
System.out.println(sl.replaceAll(".(?=.)", "$0 "));
Putting it all together we get:
int n = 23;
String s3 = Integer.toBinaryString(1<<9 | n).substring(1).replace('0','H').replace('1','T');
for(String s : s3.split("(?<=\\G.{3})"))
System.out.println(s.replaceAll(".(?=.)", "$0 "));
I need the program to run in a loop until 0 is entered. My code will end with 0 entered but when attempting to run the program with numbers entered it still ends the program. instead of running the numbers entered. The while loop is to keep the program running unless a 0 is entered.
import java.util.Scanner;
public class CountCompare {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the integers between 1 and 100 (0 to end, 0 < to exit): ");
int[] counts = new int[100];
// Count occurrence of numbers
count(counts);
while(counts[0] > 0){
// Display results
for (int i = 0; i < counts.length; i++) {
if (counts[i] > 0)
System.out.println((i + 1) + " occurs " + counts[i] +
" time" + (counts[i] > 1 ? "s" : ""));
}
System.out.print("Enter the integers between 1 and 100 : ");
// Count occurrence of numbers
count(counts);
}
System.out.print("\nEnd of run");
}
/** Method count reads integers between 1 and 100
* and counts the occurrences of each */
public static void count(int[] counts){
Scanner input = new Scanner(System.in);
int num; // holds user input
do {
num = input.nextInt();
if (num >= 1 && num <= 100)
counts[num - 1]++;
} while (num != 0);
}
}
I have posted the entire program.
output looks like this
Enter the integers between 1 and 100 (0 to end, <0 to exit):
23 23 4 5 6 7 8
0
4 occurs 1 time
5 occurs 1 time
6 occurs 1 time
7 occurs 1 time
8 occurs 1 time
23 occurs 2 times
Enter the integers between 1 and 100:
Your program still ends because:
int[] counts = new int[100];
You have defined the limit of the counts here. This means your loop will run
for (int i = 0; i < counts.length; i++)// counts.length=100;
So as far as you code suggest you want to end the user input when user input 0. So you might do this:
int x=1;
int y;
Scanner sc= new Scanner(System.in);
while(x!=0){
System.out.println("Enter your values");
y=sc.nextInt();
if(y==0){
x=0;
}
else{
System.out.println("You entered "+y);
}
int count=new Scanner(System.in).nextInt();
int myarray[]=new int[count];
for(int tmp=0; tmp<count;)
myarray[tmp]=++tmp;
while(count != 0){
for(int inc=1; inc<=count; inc++){
System.out.println(inc + "times occur");
}
System.out.println("Enter 0 to exit");
count=new Scanner(System.in).nextInt();
}
You should take a look at the line
while(counts[0] > 0) {
and try to figure out what is the purpose of this while loop in the main method.
Beginner here. So I want to write a program that prints out all the prime numbers up to the number the user entered. E.g., user enters 5, program prints out 2 and 3. That part I understand, however what I am struggling with, is what if I want the program to print out whether the number the user entered is a prime or not (simple yes or no) IF the entered number is bigger than, let's say, 50. Here is code for first part:
public class Primes {
public static void main(String args[]) {
System.out.println("All primes up to: ");
int num = new Scanner(System.in).nextInt();
System.out.println("Prime numbers from 1 to " + num + " are: ");
for(int number = 2; number<=num; number++){
if(isPrime(number)){
System.out.println(number);
}
}
}
public static boolean isPrime(int number){
for(int i=2; i<number; i++){
if(number%i == 0){
return false;
}
}
return true;
}
}
I honestly can't wrap my around as to what I should be doing next. My first program ever ("Hello world" does not count ;P).
Edit :
Your current code seems to work fine.
As per your doubt as mentioned in one of the comments : Yes, but where do I add if statement that does the following: if the number entered is below 50, then the program prints out all the prime numbers up to the entered number. If the number the user entered is bigger than 50, it tells only whether the entered number is prime or not ( simply "It's a prime" or "No, it's not a prime"). Hope that made things clearer
The check you need to put is after you take the input :
int num = new Scanner(System.in).nextInt();
if( number > 50 )
{
if(isPrime(number))
{
// print out is prime
}
// print out it is not prime
}
else
{
System.out.println("Prime numbers from 1 to " + num + " are: ");
for(int number = 2; number<=num; number++){
if(isPrime(number)){
System.out.println(number);
}
}
}
SUGESTIONS :
However, just to touch upon the algorithmic part, I would recommend using Sieve of Eratosthenes for picking out all the prime numbers within a given range, as you need in your case.
Example :
To find all the prime numbers less than or equal to 30, proceed as follows:
First generate a list of integers from 2 to 30:
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
Strike (sift out) the multiples of 2 resulting in:
2 3 5 7 9 11 13 15 17 19 21 23 25 27 29
The first number in the list after 2 is 3; strike the multiples of 3 from the list to get:
2 3 5 7 11 13 17 19 23 25 29
The first number in the list after 3 is 5; strike the remaining multiples of 5 from the list:
2 3 5 7 11 13 17 19 23 29
The first number in the list after 5 is 7, but 7 squared is 49 which is greater than 30 so the process is finished. The final list consists of all the prime numbers less than or equal to 30.
Here's the code attached for reference ( Disclaimer : I'm picking up this code here from this site. Just pasted it here for more immediate visibility).
Code :
public class PrimeSieve {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
// initially assume all integers are prime
boolean[] isPrime = new boolean[N + 1];
for (int i = 2; i <= N; i++) {
isPrime[i] = true;
}
// mark non-primes <= N using Sieve of Eratosthenes
for (int i = 2; i*i <= N; i++) {
// if i is prime, then mark multiples of i as nonprime
// suffices to consider mutiples i, i+1, ..., N/i
if (isPrime[i]) {
for (int j = i; i*j <= N; j++) {
isPrime[i*j] = false;
}
}
}
// count primes
int primes = 0;
for (int i = 2; i <= N; i++) {
if (isPrime[i]) primes++;
}
System.out.println("The number of primes <= " + N + " is " + primes);
}
}
Try this..
int j = 2; //variable
int result = 0; //variable
int number = 0; //variable
Scanner reader = new Scanner(System.in); //Scanner object
System.out.println("Please enter a number: "); //Instruction
number = reader.nextInt(); //Get the number entered
while (j <= number / 2) //start loop, during loop j will become each number between 2 and
{ //the entered number divided by 2
if (number % j == 0) //If their is no remainder from your number divided by j...
{
result = 1; //Then result is set to 1 as the number divides equally by another number, hergo
} //it is not a prime number
j++; //Increment j to the next number to test against the number you entered
}
if (result == 1) //check the result from the loop
{
System.out.println("Number: " + number + " is Not Prime."); //If result 1 then a prime
}
else
{
System.out.println("Number: " + number + " is Prime. "); //If result is not 1 it's not a prime
}
this is more efficient way tough:-
public boolean isPrime(int n) {
// fast even test.
if(n > 2 && (n & 1) == 0)
return false;
// only odd factors need to be tested up to n^0.5
for(int i = 3; i * i <= n; i += 2)
if (n % i == 0)
return false;
return true;
}
however what I am struggling with, is what if I want the program to print out whether the number the user entered is a prime or not (simple yes or no).
Your current isPrime function seems to work, so just ask for a number and test it.
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
System.out.println("Enter a number (is it prime): ");
int num = scanner.nextInt();
if (isPrime(num)) {
System.out.printf("%d yes%n", num);
} else {
System.out.printf("%d no%n", num);
}
}
Or with a ternary,
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
System.out.println("Enter a number (is it prime): ");
int num = scanner.nextInt();
System.out.printf("%d %s%n", num, isPrime(num) ? "yes" : "no");
}
Edit Based on your comment, move your print up sequence to a method
public static void primesUpTo(int num) {
System.out.println("Prime numbers from 1 to " + num + " are: ");
for (int number = 2; number <= num; number++) {
if (isPrime(number)) {
System.out.println(number);
}
}
}
Then
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
System.out.println("Enter a number (is it prime): ");
int num = scanner.nextInt();
if (num > 50) {
System.out.printf("%d %s%n", num, isPrime(num) ? "yes" : "no");
} else {
primesUpTo(num); // <-- call the method above.
}
}
If i understand the question right:
If user enteres number lesser than or equal to 50, then print all primes that are lesser than that number.
Otherwise, just write if inputted number is a prime.
With already existing isPrime() method:
int num = new Scanner(System.in).nextInt();
if (num <= 50) {
System.out.println("Prime numbers from 1 to " + num + " are: ");
for (int number = 2; number <= num; number++) {
if (isPrime(number)) {
System.out.println(number);
}
}
} else { //num > 50
if(isPrime(num)) {
System.out.println(num + " is prime.");
} else {
System.out.println(num + " isn't prime.");
}
}