Been studying Java for a few months now with no prior development experience, but I am determined to learn this. This is my first post. Here's the question:
Write a program that reads a sequence of integer numbers and outputs true if the sequence is ordered (in ascending or descending order), otherwise, false. Keep in mind, if a number has the same value as the following number, it does not break the order.
The sequence ends with 0. Do not consider this number as a part of the sequence. The sequence always has at least one number (excluding 0).
Sample Input 1:
9 8 7 6 5 4 3 2 1 0
Sample Output 1:
true
Sample Input 2:
1 2 3 3 9 0
Sample Output 2:
true
Sample Input 3:
1 2 5 5 2 3 0
Sample Output 3:
false
I've read other posts that addresses this issue, but my code is a representation of the concepts I've learned and quasi-understand thus far.
My intuition is that in order to iterate through all the values that are input BEFORE producing a 'true' or 'false', a list is probably needed. But, I'm unsure of how to utilize Scanner within a list and how to use a list within a 'for loop' &/or 'if' statements. Here is my code thus far, which is producing a error of time limit exceeded. Thank you in advance for your help.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int input = scanner.nextInt();
for (int i = 1; i > 0; i++) {
if (input >= i || input == i + 1) {
System.out.println(true);
}
else if (input <= i || input == i - 1) {
System.out.println(true);
}
else {
System.out.println(false);
}
}
}
}
Let's first read in all the numbers:
Scanner scanner = new Scanner(System.in);
List<Integer> numbers = new ArrayList<>(); //use a list to store
int number = -1;
while(number != 0) { //go until 0
System.out.println("Enter a positive int or 0 to stop!");
number = scanner.nextInt(); //read integer
if(number != 0) {
numbers.add(number); //save it, but only if it's not 0
}
}
Now we have all numbers in the list. Some methods can be writter to check if they are ascending:
public static boolean isAscending(List<Integer> numbers) {
int number, next;
if(numbers.size()==1) return true; // edge cases
if(numbers.size()==2) {
return numbers.get(0) <= numbers.get(1);
}
for(int i=0; i<numbers.size() - 2; i++) { //from first to one before last
number = numbers.get(i);
next = numbers.get(i+1);
if(next < number) { //next is NOT bigger then the current (equal accepted)
return false;
}
}
return true; //if we got here then it's ascending
}
The descending method is similar, but you use '>' when comparing the numbers. Then, it's just a matter of calling them on the input list:
boolean ascending = isAscending(numbers);
boolean descending = isDescending(numbers);
if(ascending || descending) {
//result is TRUE here
System.out.println("TRUE");
} else {
//result is FALSE here
System.out.println("FALSE");
}
Related
Sometimes, the normal if-else isn't enough. In such cases, we have what we call ladder if and else conditions. So here we'll learn to use them.
Given a positive integer N. Your task is to check if it divisible as given below:
If it is divisible by 2, print "Two".
If it is divisible by 3, print "Three".
If it is divisible by 11, print "Eleven".
If not follow above three rules, print "-1".
Note: If N is divisible by more than one of the above given numbers, print the one which is largest.
Input Format:
First line of input contains number of testcases T. For each testcases, there will be a single line containing N.
Output Format:
For each testcase, check divisibility and print statements accordingly as given in above steps (without quotes).
Your Task:
Your task is to complete the function to check divisibility as required.
Constraints:
1 <= T <= 10
1 <= N <= 106
Example:
Input:
2
3
11
Output:
Three
Eleven
** For More Input/Output Examples Use 'Expected Output' option **
class Geeks {
static void isDivisibleByPrime (int n)
{
//Your code here
Scanner sc=new Scanner(System.in);
int a[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
if(a[i]%2==0)
System.out.println("Two");
else if(a[i]%3==0)
System.out.println("Three");
else if(a[i]%11==0)
System.out.println("Eleven");
else
System.out.println("-1");
}
}
}
First use braces around every block of code. it is easier to reading for everyone.
Second the point in your spec was to print the largest value if divisible, so you
should start with checking if it divides by 11 first, then 3 and then 2.
Right code is here:
static void isDivisibleByPrime(int n) {
if (n % 11 == 0) {
System.out.println("Eleven");
} else if (n % 3 == 0) {
System.out.println("Three");
} else if (n % 2 == 0) {
System.out.println("Two");
} else {
System.out.println("-1");
}
System.out.println();
}
First things first - always use braces around every block of code - especially a beginner to the language. It will make your life easier, and anyone reading your code.
Second, the point in your spec was to print the largest value if divisible, so you should start with checking if it divides by 11 first, then 3 and then 2.
And lastly, I would get all the input first, and not in the isDivisibleByPrime method, and just call that method for each input.
So just leave your isDivisibleByPrime as
static void isDivisibleByPrime(int n) {
if (n % 11 == 0) {
System.out.println("Eleven");
} else if (n % 3 == 0) {
System.out.println("Three");
} else if (n % 2 == 0) {
System.out.println("Two");
} else {
System.out.println("-1");
}
}
And call it elsewhere with the values
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of test cases:");
int numOfTestCases = sc.nextInt();
for (int i = 0; i < numOfTestCases; i++) {
System.out.println("Enter value to check:");
int valueToCheck = sc.nextInt();
isDivisibleByPrime(valueToCheck);
}
Obviously there's no error handling or whatnot, but as you're likely new to this, I'm sure it's not a requirement.
Here's an online example.
My task is to write a java program that first asks the user how many numbers will be inputted, then outputs how many odd and even numbers that were entered. It is restricted to ints 0-100. My question is: What am I missing in my code?
import java.util.Scanner;
public class Clancy_Lab_06_03 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n;
System.out.println("How many numbers will be entered?");
n = input.nextInt();
while (n < 0 || n > 100) {
System.out.println("ERROR! Valid range 0-100. RE-Enter:");
n = input.nextInt();
n++;
}
int odd = 0;
int even = 0;
while (n >= 0 || n <= 100) {
n = input.nextInt();
if (n % 2 == 0) {
even++;
} else {
odd++;
}
}
System.out.println(even + "even" + odd + "odd");
}
}
Second while loop is infinite. Relplace it with something like this:
for (int i = 0; i < n; i++) {
int b = input.nextInt();
if (b % 2 == 0) {
even++;
} else {
odd++;
}
}
Also I don't understand why are you incrementing n in first loop. For example when you will first give -5, you will be asked to re-enter the number. Then you type -1, but it gets incremented and in fact program processes 0, altough user typed -1. In my opinion it is not how it suppose to work and you should just remove this n++.
As you asked in comment - the same using while loop:
while(n > 0) {
n--;
int b = input.nextInt();
if (b % 2 == 0) {
even++;
} else {
odd++;
}
}
Also it is good idea to close input when you no longer need it (for example at the end of main method)
input.close();
You had two issues - first you were incrementing n in the first loop, rather than waiting for the user to enter a valid number.
In the second loop, you weren't comparing the number of entries the user WANTED to make with the number they HAD made - you were over-writing the former with the new number.
This version should work, although I've not tested it as I don't have java on this machine.
Note that we now sit and wait for both inputs, and use different variable names for the "how many numbers will you enter" (n) and "what is the next number you wish to enter" (num) variables? Along with a new variable i to keep track of how many numbers the user has entered.
import java.util.Scanner;
public class Clancy_Lab_06_03
{
public static void main (String[] args)
{
Scanner input = new Scanner (System.in);
int n;
System.out.println ("How many numbers will be entered?");
n = input.nextInt();
//Wait for a valid input
while (n < 0 || n > 100)
{
System.out.println ("ERROR! Valid range 0-100. RE-Enter:");
n = input.nextInt();
}
//Setup variables for the loop
int odd = 0;
int even = 0;
int num;
//Keep counting up until we hit n (where n is the number of entries the user just said they want to make)
for(int i = 0; i < n; i++)
{
//Changed this, because you were over-writing n (remember, n is the number of entries the user wants to make)
//Get a new input
while (num < 0 || num > 100)
{
System.out.println ("ERROR! Valid range 0-100. RE-Enter:");
num = input.nextInt();
}
//Check whether the user's input is even or odd
if (num % 2 == 0)
{
even++;
}
else
{
odd++;
}
}
System.out.println(even + " even. " + odd + " odd.");
}
}
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) {
System.out.println("Enter an Integer number:");
Scanner input = new Scanner(System.in);
int num = input.nextInt();
if ( num % 2 == 0 )
System.out.println("Entered number is even");
else
System.out.println("Entered number is odd");
}
}
My suggestion to you is to have a clear separation of your requirements. From your post, you indicate you need to prompt the user for two distinct data items:
How many numbers will be entered (count)
The values to be analyzed
It is a good practice, especially when you are learning, to use meaningful names for your variables. You are using 'n' for a variable name, then reusing it for different purposes during execution. For you, it is obvious it was difficult to figure out what was 'n' at a particular part of the program.
Scanner input = new Scanner (System.in);
int count;
System.out.println ("How many numbers will be entered?");
count = input.nextInt();
//Wait for a valid input
while (count < 1 || count > 100)
{
System.out.println ("ERROR! Valid range 1-100. RE-Enter:");
count = input.nextInt();
}
Additionally, a count of zero should not be valid. It does not make sense to run a program to evaluate zero values (don't bother a program that does nothing). I believe the lowest count should be one instead.
int odd = 0;
int even = 0;
int value;
do
{
System.out.print("Enter a number between 0 and 100: ");
value = input.nextInt();
while (value < 0 || value > 100)
{
System.out.println ("ERROR! Valid range 0-100. RE-Enter:");
value = input.nextInt();
}
if (value % 2 == 0)
{
even++;
}
else
{
odd++;
}
count--; // decrement count to escape loop
} while (count > 0);
System.out.println(even + " even. " + odd + " odd.");
This example uses a do/while loop because in this case, it is OK to enter the loop at least once. This is because you do not allow the user to enter an invalid number of iterations in the first part of the program. I use that count variable directly for loop control (by decrementing its value down to 0), rather than creating another variable for loop control (for instance , 'i').
Another thing, slightly off topic, is that your requirements were not clear. You only indicated that the value was bounded to (inclusive) values between 0 and 100. However, how many times you needed to repeat the evaluation was not really clear. Most people assume 100 was also the upper bound for your counter variable. Because the requirement is not clear, checking a value greater or equal to 1 for the count might be valid, although highly improbable (you don't really want to repeat a million times).
Lastly, you have to pay attention to AND and OR logic in your code. As it was indicated, your second while loop:
while (n >= 0 || n <= 100) {}
Is infinite. Because an OR evaluation only needs one part to evaluate to TRUE, any number entered will allow the loop to continue. Obviously, the intent was not allow values greater than 100. However, entering 150 allows the loop to continue because 150 >= 0. Likewise, -90 also allows the loop to continue because -90 <= 100. This is when pseudocode helps when you are learning. You wanted to express "a VALUE between lower_limit AND upper_limit." If you reverse the logic to evaluate values outside the limit, then you can say " value below lower_limit OR above upper_limit." These pseudocode expressions are very helpful determining which logical operator you need.
I also took the liberty to add a message to prompt the user for a value. Your program expects the user to enter two numbers (count and value) but only one prompt message is provided; unless they enter an out of range value.
extract even numbers from arrayList
ArrayList numberList = new ArrayList<>(Arrays.asList(1,2,3,4,5,6));
numberList.stream().filter(i -> i % 2 == 0).forEach(System.out::println);
My assignment is to output decimals to binaries. An example would be inputting 100 and then the binary output would be 1100100.
My code:
import java.util.Scanner;
public class Dec2Bin {
public static void main(String[] args){
System.out.println("Welcome to Decimal Number to Binary Converter");
System.out.println("");
Scanner s = new Scanner(System.in);
System.out.println("Enter a decimal number (-1 to end):");
int input = s.nextInt();
for ( ; ; ){
if (input < 0)
break;
String bi = "";
while(input != 0){
bi = ((input % 2) + bi);
input = input / 2;
}
System.out.println("The binary number is:" + bi);
}
}
}
Right now my program gets stuck in an infinite loop and the binary number prints out to be 0010011. I cannot figure out how to stop the infinite loop and reverse my binary number so it is correct.
The reason your loop is running forever is because your break condition
if (input < 0)
break;
Will never be true. If you keep diving an integer by 2, it will converge to 0; however, 0 divided by 2 is still 0, so the integer will never fall below 0.
Consider changing the loop to this:
while(input > 0) {
// code here
}
This way, the loop will end when input is 0. You also won't need the inner while loop.
Although there are methods to actually build the binary number in the correct sequence, that is not your question. To see why it is building in reverse, just use your test case and trace the program:
--- input = 100
100 % 2 == 0;
bi = 0;
--- input = 50
50 % 2 == 0;
bi = 00;
--- input = 25
25 % 2 == 1;
bi = 001;
--- and so on
To reverse your string when the number is converted, either make your own function (should be relatively simple), or use a handy StringBuilder method like so:
String biReverse = new StringBuilder(bi).reverse().toString();
The following condition is the cause for your infinite loop.
if (input < 0)
break;
If you keep dividing, the answer won't go below zero/negative. It should be:
if (input == 0)
break;
(This condition can be modified into the for loop). Otherwise your program works. I'm not getting the response in reverse...
Also, to make it a proper menu-driven program, you'll again need to change the condition & put the int input = s.nextInt(); inside the for loop.
I am coding a program to factor a number into is prime factors. The program works as follows:
1) Input a number that you wish to factor (I will refer to is as "inputNumber")
2) Test to see if you can divide inputNumber by 2,3,5 and 7 (first 4 prime numbers). if you can divide by any of these, then do so as many times as you can (i.e. 12 can be divided by 2 twice, after this, there is a remainder of 3)
note every time I divide by a number, I store that number in an array list and I keep the remainder for further testing
3) Starting with i=11 (the next prime number) in a while loop, I do the following:
while (i < remainder+1) {
divides by i? yes: store i,
repeat until you cant divide by i. i=i+2,
divides by i? yes: store i, repeat until you can't divide by i.
i=i+4, same as before... i=i+2...
and finally stop the loop at i=i+2
}
this way, every successful iteration of the while loop will divide the remainder by numbers finishing by 1,3,7,9. We do not need to test even numbers since we divided by 2 already, nor do we need to test the ones ending by 5 since we already divided by 5. In the end, we
This is a very neat algorithm since it its much much faster than factoring a number by testing one number after the other, in fact, you only need to test 40% of all numbers.
My question is: When I tried factoring 84738329279, a number picked randomly, it omits to put the last prime factor in the list, I can't quite figure this out. the only factors that show up are 41, 61 and 61. Can someone help me find what I'm doing wrong? here is my code:
import java.util.Scanner;
import java.math.BigInteger;
public class Test {
public static void main(String[] args) {
// create a scanner object for inputs
Scanner in = new Scanner(System.in);
// prompt user for number to factor
System.out.print("enter a number to factor: ");
String digits = in.next();
BigInteger BigDigits = new BigInteger(digits);
BigInteger[] results = factor.factorThis(BigDigits);
System.out.print("Factors are ");
for (int i=0; i<results.length;i++){
System.out.print(results[i] + " ");
}
System.out.println("");
}
}
import java.util.ArrayList;
import java.math.BigInteger;
public class factor {
// Returns the prime factors of the BigInteger number
public static BigInteger[] factorThis(BigInteger number) {
BigInteger i = new BigInteger("11");
ArrayList<BigInteger> divisors = new ArrayList<BigInteger>(0);
BigInteger[] firstPrimes = new BigInteger[4];
firstPrimes[0] = new BigInteger("2");
firstPrimes[1] = new BigInteger("3");
firstPrimes[2] = new BigInteger("5");
firstPrimes[3] = new BigInteger("7");
// loop that test for first 4 prime numbers
for (int l=0;l<4;l++){
while ((number.mod(firstPrimes[l])).compareTo(BigInteger.ZERO) == 0) {
number = number.divide(firstPrimes[l]);
divisors.add(firstPrimes[l]);
}
}
// loop that factors only numbers finishing by 1,3,7,9
while (i.compareTo(number) == -1){
// check for ending by 1
if ((number.mod(i)).compareTo(BigInteger.ZERO) == 0) {
while (number.mod(i).compareTo(BigInteger.ZERO) == 0){
number = number.divide(i);
divisors.add(i);
}
}
else if ((number.mod(i)).compareTo(BigInteger.ZERO) != 0){
i=i.add(firstPrimes[0]);
}
// check for ending by 3
if ((number.mod(i)).compareTo(BigInteger.ZERO) == 0) {
while (number.mod(i).compareTo(BigInteger.ZERO) == 0){
number = number.divide(i);
divisors.add(i);
}
}
else if ((number.mod(i)).compareTo(BigInteger.ZERO) != 0){
i=i.add(firstPrimes[0].multiply(firstPrimes[0]));
}
//check for ending by 7
if ((number.mod(i)).compareTo(BigInteger.ZERO) == 0) {
while (number.mod(i).compareTo(BigInteger.ZERO) == 0){
number = number.divide(i);
divisors.add(i);
}
}
else if ((number.mod(i)).compareTo(BigInteger.ZERO) != 0){
i=i.add(firstPrimes[0]);
}
// check for ending by 9
if ((number.mod(i)).compareTo(BigInteger.ZERO) == 0) {
while (number.mod(i).compareTo(BigInteger.ZERO) == 0){
number = number.divide(i);
divisors.add(i);
}
}
else if ((number.mod(i)).compareTo(BigInteger.ZERO) != 0){
i=i.add(firstPrimes[0]);
}
}
// store prime factors into a BigInt array
String[] strArrayDivisors = divisors.toString().replaceAll("\\[", "").replaceAll("\\]","").replaceAll("\\s","").split(",");
BigInteger[] BigIntDivisors = new BigInteger[strArrayDivisors.length];
for(int j=0;j<strArrayDivisors.length;j++){
BigIntDivisors[j] = new BigInteger(strArrayDivisors[j]);
}
// returns all factors of "number"
return BigIntDivisors;
}
}
Thanks in advance.
First, 84738329279 = 41 * 61 * 61 * 555439. Your 41, 61, and 61 are correct.
But when your algorithm terminates, you are left with the last prime number still in number. You'll need to add code that tests number at the end: if it's 1, then you're already finished, else it needs to add it to divisors so it gets printed later.
I'm really new to this whole programming thing, and I'm trying to wrap my head around why the loop ends abruptly and does not continue to the final if statement. Can you guys help me figure out whats wrong?
import java.util.Scanner;
public class FunnyAverage {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("How many values to read? ");
int top = in.nextInt();
System.out.print("Enter Value: ");
int one = in.nextInt();
int number = 1;
int sum = 0;
sum = sum + one;
while (number <= top) {
if (one % 6 != 0 && one % 17 != 0) {
System.out.print("Enter Value: ");
one = in.nextInt();
number++;
} else if (one % 6 == 0 && one % 17 == 0) {
System.out.print("Enter Value: ");
one = in.nextInt();
number++;
}
}
if (sum / top != 0) {
System.out.print("Average: " + sum / top);
}
System.out.print("None Divisible");
}
}
The final if() condition executes if you give the right input values. I ran your code and gave the below inputs to execute the final if() statement.
How many values to read? 1
Enter Value: 1
Enter Value: 1
Average: 1None Divisible
I dont understand what are you trying in the code, but there are many things missing like i assume you want to capture the sum of the input numbers, but sum is not used in the while loop.
Looks like you end up in the non-present else case (within the while loop). Consequently, number isn't increased and you are stuck in the while loop.
Try reading one within the while loop. This way the user will be prompted to enter a new number in each loop.
Otherwise you will be stuck in the while loop once the user enters a number that isn't conform with your checks.