Determine whether or not a sequence is decreasing in java - java

I got this question on exam review "Write psuedocode for a program that reads a sequence of integer values and decides whether or not it is a decreasing sequence. The program will first read in the number of values to process, followed by the values themselves. The output will be “Yes” if the sequence is decreasing, and “No” otherwise."
Here is my code, but it sometimes does not stop,(for example, when you input 3 2 1). Can someone help me to figure out where I was wrong? Thank you!
import java.util.Scanner;
public class DecreasingOrNot {
public static void main(String[] args){
int number1, number2;
boolean decrease = true;
Scanner input = new Scanner(System.in);
System.out.println("Enter a sequence of numbers: ");
number2 = input.nextInt();
while (decrease && input.hasNext()){
number1 = number2;
number2 = input.nextInt();
if (number1 < number2){
decrease = false;
}
}
if (decrease){
System.out.println("Yes");
}
else{
System.out.println("No");
}
}
}

Right now, you have no way of breaking out of the loop if the user keeps adding decreasing numbers (which is why it won't break out of the loop if the user enters something like 3 2 1).

Related

Issue with do/while looping

I was trying to make a simple calculator but I'm kind of stuck. I have the majority of the programming there, but I don't understand why my do/while loop isn't working properly. I would like for the user to input 0 for exit, or 1~4 for the respective calculation.
However, despite my efforts I can't seem to get this working entirely. The problem is that instead of looping until the user inputs something desired, it just terminates entirely.
Any help would be greatly appreciated, thank you!
import java.util.*;
public class Main
{
public static void main(String[] args) {
//variable declare
double number1,number2,answer=0;
int choice;
//scanner to get input from user
Scanner sc = new Scanner(System.in);
do{
//ask user to input number
System.out.println("Welcome user \n---------------------------------");
System.out.println("Enter the first number");
number1 = sc.nextDouble();
System.out.println("Enter the second number");
number2 = sc.nextDouble();
//ask user to enter the choice
System.out.println("What would you like to do? \n1)Addtion\n2)Subtraction\n3)Multiplication\n4)Division\n0)Exit");
choice = sc.nextInt();
//condition to exit the do while loop
if(choice == 0){
break;
}
//switch condition to loop the choice
switch(choice){
case 1 : answer = calcSum(number1,number2);break;
case 2 : answer = calcSub(number1,number2);break;
case 3 : answer = calcMult(number1,number2);break;
case 4 : answer = calcDiv(number1,number2);break;
default : System.out.println("What would you like to do? \n1)Addtion\n2)Subtraction\n3)Multiplication\n4)Division\n0)Exit");break;
}
//print th result after every iteration
displayResult(answer);
}while(choice>0&&choice<5);
}
//calculate sum
static double calcSum(double a, double b){
return a+b;
}
//subtraction
static double calcSub(double a, double b){
return a-b;
}
static double calcMult(double a, double b){
return a*b;
}
//division
static double calcDiv(double a, double b){
return a/b;
}
//print result
static void displayResult(double result){
System.out.println("Result is "+result);
}
}
I would like for the program to validate that the user inputs something desired such as 0, 1, 2, 3 or 4. I'm sorry for the difficulty, I've been learning methods and I'm getting pretty confused.
OK, assuming the problem is that when one enters, e.g., "8" for the value, the program terminates, the issue is in the test.
So, the default in the switch will display the message (and then it will output garbage for the answer), but the check is (choice > 0 && choice < 5); which will fail if one enters "8".
Easy solution is to do change the default to put a value in the range.

How can I input an if statement inside a while loop?

import java.util.Scanner;
public class ex11
{
static Scanner type=new Scanner(System.in);
public static void main(String args[])
{
int fact=1;
System.out.println("Enter a natural number ");
int num=type.nextInt();
int i=1;
while(i<=num)
{
fact*=i;
i++;
}
System.out.println("Factorial of number " + num + " is " + fact);
}
}
I'm trying to place a conditional statement inside the while loop. The condition is to test for would be that of, if num is a negative number, S.O.P.("You entered a negative #"); in other words,
if(num<0)
S.O.P.("You entered a negative #");
However it doesn't print it properly.
If you check inside the loop then it will not work it will still multiply the fact. You need to make sure that the num is not negative before you start the while loop.
int num = 0;
do {
if (num<0){
System.out.println("You printed out a negative number");
}
System.out.println("Enter a natural number ");
int num=type.nextInt();
} while (num<0);
Also on a side note you should probably close your scanners when you are done using them.
The question is hard to understand but from what i read it appears you want a loop to run until a value is entered that meets your pre-condition of being positive
System.out.println("Enter a non negative number :: ");
int num = type.nextInt();
while(num < 0){
System.out.println("The number you entered was negative!");
System.out.println("Enter a non negative number :: ");
num = type.nextInt();
}
Loops like this are crucial to making sure the data that you are using is within the pre-condition of your operation which could cause DivideByZero errors or other problems. This loop should be placed before you ever use the value of num so you can make sure it is within context of your program.
The problem is that if the num is negative, it won't go inside the while loop that is because before the while loop you have initialize i=1, since any negative number is lesser than 1 the condition for while loop become false. If you want to check whether num is negative insert the if condition before the while loop as follows
import java.util.Scanner;
public class ex11
{
static Scanner type=new Scanner(System.in);
public static void main(String args[])
{
int fact=1;
System.out.println("Enter a natural number ");
int num=type.nextInt();
int i=1;
if(num < 0) {
System.out.println("You entered a negative #");
}
else{
while(i<=num)
{
fact*=i;
i++;
}
System.out.println("Factorial of number " + num + " is " + fact);
}
}
}
To answer your question .... like this:
int i = 1; // HERE
while (i <= num) {
if (num < 0) {
System.out.println("You entered a negative #");
}
fact *= i;
i++;
}
However that is not going to work.
Suppose that "num" that you read is less than zero.
At the statement labeled "HERE", we set "i" to one.
In the next statement, we test "i < num".
Since "num" is less than zero, that test gives "false" and we skip over the entire loop!
That means that your conditional statement in the loop body would not be executed ... if "num" is less than zero.
Since this is obviously homework, I will leave it to you to figure out what you should be doing here. But (HINT!) it is not putting the conditional inside the loop.
(Please note: I have corrected a number of style errors in your code. Compare your original version with mine. This is how you should write Java code.)
You basically have to check whether the number is less than 0. This is to be done while taking the input. You can just take the input inside a while loop in this manner:
System.out.println("Enter a natural #");
while(true){ //loop runs until broken
num = type.nextInt();
if(num>=0)
break;
System.out.println("Wrong input. Please enter a positive number");
}
The program control breaks out of the loop if num>=0, i.e., positive, else, it continues to the next part of the loop and displays the error message and takes the input again.
Please note that natural numbers are the ones >= 1. In your program, you are actually trying to input a whole number which is >= 0.

Could anyone tell me why my program doesn't work?

The program reads values from scanner until the value 0 is given, which finishes the process. The program will compile the sum only if all the numbers given are integers. In all the other situations (where not all of the values are integers) the program won't give anything out.
So i noticed my program gives out the sum of the integers even if there are other non integer values given and sometimes when they are all integers given it doesn't show the real sum just one of the numbers or something.
import java.util.Scanner;
public class Testing3{
public static void main(String[] args) {
int sum1 = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter number");
String number = input.nextLine();
int value =Integer.parseInt(number);
while(true) {
if (value!=0) {
number = input.nextLine();
if (Math.round(value)==value)//condition to integer{
sum1 = sum1 + value;
} else {
System.out.println(sum1);
break;
}
}
}
}
First of all, use while(true) or for(;;) to make in infinite loop
Second use nextInt() to read integers instead of doubles because you have no use for doubles. Alternatively, read strings with readLine and check their validity with Integer.parseInt.
Thirdly, you have a syntax error (so it shouldn't compile). You have an unmatched close brace near the else.
Lastly, remove the if (number != 0) because that will cause your program to continuously repeat in the loop without doing anything forever. Change the inside of the loop to:
number = input.nextInt();
if (number != 0){
sum1 = sum1 + number; //or use sum1 += number
} else {
System.out.println(sum1);
break;
}
I think your problem is at the place where you test for an integer. I don't think x mod 1 == 0 is correct suitable here. What I'll do when I am asked to check whether a number is an integer, I round the number and check if it equals to the original number.
Let's say we have a double variable called x and this evaluates to true if x is an integer:
Math.round(x) == x
I don't know whether there is a better way to do it but that's how I would do it and I like it.

Getting all possible odd numbers in the user input

I am having difficulties with finding all possible odd numbers for my program. I am required to use a while loop to find all the odd numbers but i am not sure how to print it out. I dont know if im doing anything wrong in this block while((num1+num2)%2==0) because that was just a guess. Outline of the program is to get the user to enter 2 numbers that is an even multiple of the other number. I am not sure how that part either. After finding 2 numbers that is an even multiple of the other number, i am supposed to display all the odd numbers between the two numbers. Thanks alot in advance.
import java.util.Scanner; //imports the java utillity scanner
public class MyPrompter{
public static void main(String[] args){
System.out.println("Odd number display");
Scanner input = new Scanner(System.in); //scans for user input and stores in "input"
int num1,num2; //declares the variables i need for the pgrm
try{ //try statement to check for user input errors
System.out.println("Please enter your first number: ");
num1 = input.nextInt(); //stores input for the first number
System.out.println("Please enter your second number: ");
num2 = input.nextInt(); //stores input for the second number
while((num1+num2)%2==0){ //while loop to find all the odd numbers between the 2 numbers
System.out.println();
}
}
catch(java.util.InputMismatchException e){ //if the above error is met, message will be sent to the user
System.out.println("Please enter a valid ROUNDED NUMBER!");
}
}
}
How about something like this:
int num1 = 10;
int num2 = 50;
int current = num1;
while (current < num2) {
if (current % 2 != 0) {
System.out.println(current);
}
current++;
}
Set current to equal num1, continue the loop while current is less than num2. For each iteration check if current is odd and output it if it is. Increment current by one.

Java: Storing numbers in vector, transfer to array, then take primes from array and store in another vector

I'm going to post the question and then the code that I currently have done. I feel like I'm pretty close to getting it but I'm stuck at one part I just can't seem to figure out. Here goes:
The question: Create a Vector that stores N numbers. Input N non-negative numbers through the console into the Array. Then create another Vector that stores only M prime numbers from the N numbers.
My code so far:
import java.util.*;
public class VectorPrimes {
public static Vector<Integer> inputVc = new Vector<Integer>();
public static Vector<Integer> primeVc = new Vector<Integer>(inputVc);
public static boolean isPrime(int n) {
boolean prime = true;
for (int i = 2; i * i <= n; i+= 2) {
if (n % i == 0) {
prime = false;
break;
}
}
return prime;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out
.println("This program will take input of positive numbers and output"
+ " prime numbers, if any, from the input numbers.");
System.out
.println("Input a positive number to check for prime numbers: ");
boolean looping = true;
while (looping) {
System.out
.println("Input '0' to finish inputting numbers and print the primes.");
String userin = scan.nextLine();
int input = Integer.parseInt(userin);
if (input != 0) {
System.out.println("Enter next number: ");
inputVc.add(input);
} else if (input == 0) {
//Integer[] inputArray = inputVc.toArray(new Integer[inputVc.size()]);
looping = false;
System.out.println(inputVc);
System.out.print(primeVc);
System.exit(0);
}
}
}
}
I'm sure it's not the best way to do it, but that's what I have so far. To be clear, I'm having trouble getting the inputted numbers from the input vector (inputVc) to go into the array (inputArray) and then storing the prime numbers in the prime vector (primeVc) and printing them. I have tried 3 or 4 different ways but I can't get anything to store in the primeVc vector, it just keeps printing blank.
I'm not asking for the code, what I'm trying to figure out is strictly how to get the prime numbers inputted into the primeVc vector and then print it. Of course the inputVc numbers need to be run through the isPrime method and then added to the primeVc vector if true, but I'm pretty sure that's where I'm having my problem.
What do you guys see?? I'm definitely missing something and cannot for the life of me figure it out.
Do something like:
//...
if (input != 0) {
System.out.println("Enter next number: ");
inputVc.add(input);
if (isPrime(input))
primeVc.add(input);
}
//...
Also you can create while(true) loop and simply break it when you will get 0.
first you have to call your functon isPrimethen if returned value is true then add it to your second list
and other thing, your function isPrime won't work, your initial value of 'i' is 2, then you are incrementing it by 2, so it will return value true for each odd number

Categories

Resources