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

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.

Related

The while and do-while loops The smallest value

I need to write a program that a user inputs a long positive number m. I need to find out what is the smallest int number n such that n! > m.
So far I have written such a code:
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
long number = scanner.nextLong();
int fact = 1;
int count =1;
while (fact <= number) {
count ++;
fact *=count;
}
System.out.println(count);
}
}
Test input:
6188989133
Correct output:
13
Your code output:
My code output is empty. What I am missing here?
You have to use long for the fact variable. When you use int the possible values are between -2,147,483,648 and 2,147,483,647.
However, you will never exceed the input number 6,188,989,133, so your while(fact <= number) loop will never exits. Every integer value possible will be smaller than 6,188,989,133. This explains why your code output is "empty", as it doesn't reach that System.out.println(count); line at all.
Keep in mind that the long type has such a limit as well, values can only be between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807. When the input number is that big, you will not find the correct fact value which will be greater than the input because you are limited by the long type value range. As an example, for the input number 9,000,000,000,000,000,000 (which is inside the long type value range) the next factorial number is 51,090,942,171,709,440,000 (the value of 21!), which is outside the long type value range.
You can use the java.math.BigInteger class which has an "unlimited" range of possible values and do your math operations on BigInteger objects.
fact should be declared as long. Check the code below:
public class TestJava {
public static void main(String[] args) {
try{
System.out.println("Input number: ");
Scanner scanner = new Scanner (System.in);
long number = scanner.nextLong();
if(number >= 2432902008176640000L) {
// log an appropriate message like can not handle
// long value greater than 2432902008176640000L
return 21;
}
long fact = 1;
int count =1;
while (fact <= number) {
count ++;
fact *=count;
}
System.out.println("output: "+ count);
}catch(Exception e){
e.printStackTrace();
}
}
}
Update (Warning):
As #Pshemo mentioned, with out the if condition, the above code is fine till 20!, but after that it will cause the infinite loop problem. Hence this condition has to be taken care of. Code has been updated accordingly.
You need to change fact type to long

Do-while and Exception Hadnling

package learnjava;
import java.util.Scanner;
public class exception {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x =1;
do {
try {
System.out.println("Input first number : ");
int n1 = input.nextInt();
System.out.println("Input second number : ");
int n2 = input.nextInt();
int sum = n1 / n2;
System.out.println("result = "+sum);
x = 2;
} catch (Exception e) {
System.out.println("Error");
}
} while (x == 1);
}
}
I watched java tutorials in thenewboston.....
I want ask you...why x=2...?can you explain why?...thanks
This a code doesn't approach it's own concept well.
Nonetheless Do-While is a exit control loop and is keeps on executing the loop till x is not equal to any number except 1. That is if there is any change in x apart from being 'x = 1'then the loop would break as in the loop will stop functioning. Here we are using a try catch to prevent any number being divided by zero and we use x=2 to execute the loop once and exit.
Anyway this is concept builder, but this is not how one would approach this methodology.
do-while loop executes once without checking the condition.
In this case the condition to continue while loop is x == 1 . That is because you have set x = 1 in your code above.
While executing prior to checking the condition, using the scanner, you read 2 integers and done some operations on them and printed the result.
As the logic expects flow to stop here (that is just reading 2 integers and printing result), x has been set to 2 that is x = 2.
Now answering your question why x = 2. It can be anything other than 1 which will terminate the while loop and not allow any further iterations.
this code do division if you inter the n2 value to 0, exception happened and printed the error and the x=1 value was not changed the while condition is true and your code running again and want the input. if your input was true (n2!=0) your operation done and the x value changed to two x=2. when the while condition checked the result is false and break the do while loop.
I write some comment in your code.
package learnjava;
import java.util.Scanner;
public class exception {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x =1;
do {
try {
System.out.println("Input first number : ");
int n1 = input.nextInt();
System.out.println("Input second number : ");
int n2 = input.nextInt();
int sum = n1 / n2;//if your n2 input was 0 exception happened and go to catch block.
System.out.println("result = "+sum);
x = 2;// if one time your code execute without exception the x changed to 2. if exception happened your code execute again.
} catch (Exception e) {
System.out.println("Error");
}
} while (x == 1);
}
}
Its simple,
The do while works this way.
First the do part gets executes, if the condition in the while loop is satisfied, the do loop executes again. This will go on, till the condition in the while loop is not satisfied.
do {
//work is done.
//now lets us change the condition so that we can get out of this do-while loop.
// this condition is nothing but setting x equal to nay value other than 1. It can be 2 or 10000 or -1.
} while (x == 1);
So here once the functionlity of the do loop is satisfied, the x==2 is done. This makes sure that the condition in while is not satisfied and hence the code exists do-while loop.

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.

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

Java, Infinite loop- multiples of 2 only

I am asked to print multiples of 2 only with a never ending loop.
Attempt:
import java.util.Scanner;
public class Infiniteloop {
public static void main (String [] args)
{
Scanner input=new Scanner (System.in);
int number,x;
System.out.print("Enter a number");
number=input.nextInt();
if(number%2==0)
{
while(number>=0)
{
x= (++number);
System.out.println(x);
}
}
}
}
I can only use while-loop. So I tried to set the remainder of 2 equal to zero. I tried using the counter but it doesnt increment it. Keeps printing out zeros. I need some help. Thanks.
Supposing that you want to prompt the user for a start number and then print all the following even numbers:
number = input.nextInt(); //read the input
number += number % 2; //if input is odd, add 1
while (true)
{
System.out.println (number);
number += 2;
}
Supposing you want to check for even numbers:
while (true)
{
number = input.nextInt();
if (number % 2 == 0) System.out.println (number);
}
Or if you don't care about empty lines:
while (true) System.out.println (input.nextInt () % 2 == 0 ? "even" : "");
EDIT: Same thing for powers of two:
public static void main (String [] args)
{
Scanner input = new Scanner (System.in);
int number;
while (true)
{
System.out.print ("Enter a number");
number = input.nextInt ();
while ( (number & 1) == 0) number >>= 1;
if (number == 1) System.out.println ("Perfect divisor.");
}
I am surprised this compiles.
x= (++number)
has no semi-colon at the end.
also, move the if statement inside of the while. If you are checking for multiples of 2, you will want that check after each iteration of the loop
edit: you changed your original code. Please copy/paste from your source instead of re-typing.
Question is not very clear but may be something like this would help you:
Scanner input=new Scanner (System.in);
int number;
do {
System.out.print("Enter a number: ");
number=input.nextInt();
if(number%2==0)
System.out.println(number);
} while (number > 0);
An infinite loop does not need a counter. It can be written like this:
if((number % 2) != 0) {
number++;
}
while(true) {
System.out.println(number);
number = number + 2;
}
edit: Added infinitely finding multiples of 2
I'm guessing that this is a homework question, so perhaps explaining the methodology will help you more than a full answer.
Firstly, you can use a while loop to ensure that your code gets executed more than once:
while loop
A while loop will keep executing the code inside it while the given boolean condition evaluates to true. So, you can wrap up your code with:
while(true) {
//...
}
and anything between the brackets will continually execute (line by line) forever.
If you get a number from the user at the beginning of the loop, the loop will stop executing any further code until the user types something (it will be blocked, waiting on IO).
Once you get the number, the loop will start executing the rest of the code, before returning to the top of the loop and repeating the process.
while (true) {
//ask user for number
//print out the number
// check that it is even
// print whether it is even or odd
}
class Fordemo
{
public static void main(String args[])
{
int k,x=0;
for(k=1;k<=10;k++)
{
x=k*2;
System.out.println("multiple of 2 is "+x);
}}}

Categories

Resources