Making loops in order to test values [duplicate] - java

This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 7 years ago.
I need help making a loop that looks at each value from 1 to number-1.
Also how to test each value to see if it is a
divisor of number, and if it is, adding it to the sum.
This is what I have so far:
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Please enter a positive integer: ");
int n = input.nextInt();
while (n < 0) {
System.out.println(n + " is not positive.");
System.out.print("Please enter a positive integer: ");
n = input.nextInt();
}
}

You can use this as a starting block for your application:
package Testers;
import java.io.Console;
public class Application {
public static void main(String[] args)
{
Console console = System.console();
if (console == null)
{
System.err.println("No console.");
System.exit(1);
}
boolean keepRunning = true;
while (keepRunning)
{
String name = console.readLine("Type your positive integer");
try{
int integer = Integer.parseInt(name);
if(integer < 0){
System.out.println("You must specify a positive integer!");
}
for(int i = 1; i<integer; i++){
// our variable "i" is smaller than "integer". This will parse all the numbers between one and "integer" -1.
if(i % 2 == 0){
//"i" IS divisible by 2. Of course, you can change this value to what you want to change it to.
//Here you can add it to a sum
}else{
//"i" is not divisible by 2. Of course, you can change this value to what you want to change it to.
}
}
}catch(NumberFormatException e){
System.out.println("You must specify a positive integer!");
}
}
}
}

If you want to do something for a known number of times, it is mostly a good idea to use a for loop. If you want to do something for number 1 to n-1, the loop could look like
for(int i = 1; i < n; i++) { // do stuff }
Note that it starts counting from 1 and stops as soon as i is greater or equal than n.
In order to know whether a number, say n, is divisible by some number, say k, the modulo-operator % could be used. If n % k == 0 this means that n is divisible by k. With an if-statement this can be tested and when you have some sum variable you can add whatever you want to that variable to sum things up.
Hope that helps

Related

I have a problem with splitting up my Java program into separate methods within the same class, could I have some advice on how to go about it?

I was given the task of splitting my program which which allows the user to enter an array of numbers and after an odd number between 1 and 10 to check whether the odd number is a factor of each of the 5 numbers in the array. I keep on trying out different ways but none seem to work. Could someone help me out or send a sample of how I should sort it? This is the program:
import java.util.Scanner;
public class CheckboxExample{
public static void main(String args[]) {
CheckBox c = new CheckBox();
new CheckboxExample(); // links to checkbox class
Scanner s = new Scanner(System.in);
int array[] = new int[10];
System.out.println ("Please enter 10 random numbers"); // prompts the user to enter 10 numbers
int num; // declares variable num
try{
for (int i = 0; i < 10; i++) {
array[i] = s.nextInt(); // array declaration
}
}catch (Exception e){
System.out.println ("You have an error");
}
System.out.println ("Please enter an odd number between 1 and 10");
try{
num = s.nextInt ();
if (num % 2 == 0){
do{
System.out.println ("\nYour number is even, enter an odd one");
num = s.nextInt ();
}while (num % 2 == 0);
}
if (num < 0 | num > 10){
do{
System.out.println ("Your number is outside of the range, try again");
num = s.nextInt ();
}while (num < 0 | num > 10);
}
for (int i = 0; i < 5 ; i++){
if (array[i] % num == 0) {
System.out.println("Your number is a factor of " + array[i] );
}
}
}catch (Exception e){
System.out.println ("error");
}
}
}
A method should ideally be responsible for one task. In your case you should think about the different things your code try to do and organize them in a sense that each of the methods you call does one thing of the list of things you try to do.
As an example: As far as I understand your code does the following things:
Read an array of 10 values
Read an odd number
Verify the number is odd
Verify the number is in range
Calculate if the number is a factor of one of the 10 numbers in the array
Now one possible approach would be to separate your code in 5 methods that do exactly these things.
At first you call the method that reads the 10 numbers.
Then you call the method to read the odd number.
3. and 4. are actually part of reading the number, since you need to retry on an invalid input, so you could write your method for inputting the odd number in a way that it uses the methods for verifying the input.
Finally when you have all the valid input, you call the method which produces your result (ie. if the number is a factor of the numbers in the list).
A general outlier for your code could look like:
public class CheckboxExample {
public static void main(String args[]) {
CheckBox c = new CheckBox();
new CheckboxExample(); // links to checkbox class
Scanner s = new Scanner(System.in);
int array[] = readInputArray();
int number = readOddValue();
calculateFactors(array, number);
}
private int[] readInputArray() {...}
private int readOddValue() {...}
private void calculateFactors(int[] array, int number) {...}
//additional methods used by readOddValue which verify if the value is actually odd
}
Please note that this is just one way to split your code into methods and there are several ways to design and implement each of these methods.

Product of Number input by user, program stops when user inputs 0

i want to make a program reads integers from the user one by one, multiply them and shows the product of the read integers. The loop for reading the integers
stops when the user presses 0. If the user enters a 0 as the first number, then user would not be able to provide any other numbers (Not adding the last 0 in the product). In this case, the program should display “No numbers entered!”
Heres my code right now
ProductNumbers.java
package L04b;
import java.lang.reflect.Array;
import java.util.Scanner;
public class ProductNumbers {
public static void main(String[] args) {
int num = -1;
boolean isValid = true;
int numbersEntered = 0;
int product = -1;
Scanner scnr = new Scanner(System.in);
System.out.println(
"This program reads a list of integers from the user\r\n"
+ "and shows the product of the read integers");
while (num != 0) {
System.out.print("Enter number = ");
int curNum = scnr.nextInt();
if (curNum == 0)
break;
numbersEntered++;
product *= num;
}
if (numbersEntered == 0) {
System.out.println("No numbers entered!");
} else {
System.out.println(product);
}
}
}
I know this is completely wrong, i usually setup a template, try to figure out what needs to be changed, and go by that way, i also need to start thinking outside the box and learn the different functions, because i dont know how i would make it end if the first number entered is 0, and if the last number is 0, the program stops without multiplying that last 0 (so that the product doesnt end up being 0)... i need someone to guide me on how i could do this.
Heres a sample output of how i want it to work
This program reads a list of integers from the user
and shows the product of the read integers
Enter the number:
0
No numbers entered!
and
This program reads a list of integers from the user
and shows the product of the read integers
Enter the number:
2
Enter the number:
-5
Enter the number:
8
Enter the number:
0
The product of the numbers is: -80
You have a nested for loop, why?
You only need the outer while loop that gets the user's input until the input is 0.Also this line:
product *= i;
multiplies i, the for loop's counter to product and not the user's input!
Later, at this line:
if (isValid = true)
you should replace = with ==, if you want to make a comparison, although this is simpler:
if (isValid)
Your code can be simplified to this:
int num = -1;
int product = 1;
int counter = 0;
Scanner scnr = new Scanner(System.in);
System.out.println(
"This program reads a list of integers from the user\r\n"
+ "and shows the product of the read integers");
while (num != 0) {
System.out.print("Enter a number: ");
num = scnr.nextInt();
scnr.nextLine();
if (num != 0) {
counter++;
product *= num;
System.out.println(product);
}
}
if (counter == 0)
System.out.println("No numbers entered");
else
System.out.println("Entered " + counter + " numbers with product: " + product);
One way to solve this is to utilize the break; keyword to escape from a loop, and then you can process the final result after the loop.
Something like this:
int numbersEntered = 0;
while (num != 0) {
int curNum = // read input
if (curNum == 0)
break;
numbersEntered++;
// do existing processing to compute the running total
}
if (numbersEntered == 0)
// print "No numbers entered!
else
// print the result
I think the key is to not try and do everything inside of the while loop. Think of it naturally "while the user is entering more numbers, ask for more numbers, then print the final result"

how to properly use math.pow java function?

here's what I'm trying to do:
get two inputs from user and validate them. 1 is a random number between 1 and 20, the other is the times it should multiply itself over ( a number between 1 and 10 which I expressed through exponentiation)
what I don't understand - math.pow only works with doubles? Also, is it possible that the user inputs "wrong" values and instead of terminating, the program asks for inputs again?
I have this:
import java.util.Scanner;
public class P01Multiplicador {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("insert number and how many times it will multiply itself over");
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int nReps = in.nextInt();
if(n<1 || n>20 || nReps<1 || nReps>10){
System.out.println("values are not accepted, please insert again");
}
else{
do Math.pow(n, nReps);
while(n>1 && n<20 && nReps>1 && nReps<20);
}
in.close();
}
it asks for the values but doesn't run properly(or, at all for that matter), i'm guessing I'm either using the wrong statements or wrong variable type. java newbie here. suggestions?
You need to fix your code so it is valid code.
Math.pow uses doubles as it produces both large and tiny numbers depending on the inputs. e.g. even 4^20 will not fit in an int.
If you want to round the result to a long you can use Math.round(x)
Something like this:
boolean accepted = false;
do{
System.out.println("insert number ....
if(n<1 || n>20 || nReps<1 || nReps>10){
System.out.println("values are not accepted, please insert again");
}else{
accepted = true;
}
}while( !accepted )
Math.pow accepts doubles and returns double as per the doc.
For your code to take new inputs when wrong numbers are entered, you can add a while(true) loop.
while(true){
if(n<1 || n>20 || nReps<1 || nReps>10){
System.out.println("values are not accepted, please insert again");
n = in.nextInt();
nReps = in.nextInt();
}
else{
System.out.println(Math.pow(n, nReps));
break;
}
}
I have used break to end the loop when correct values are given, but you could get new inputs instead of breaking (as it seems from your code). You need to then have some other break condition otherwise it will be an infinite loop again.
Use below code inside your main method
System.out.println("insert number and how many times it will multiply itself over");
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int nReps = in.nextInt();
while (true) {
if (n < 1 || n > 20 || nReps < 1 || nReps > 10) {
System.out.println("values are not accepted, please insert again");
System.out.println("insert number and how many times it will multiply itself over");
n = in.nextInt();
nReps = in.nextInt();
} else {
System.out.println("" + Math.pow(n, nReps));
break;
}
}

Why is this method returning 0 no matter what the user inputs are?

The method CountQiftPositiv is returning 0 no matter what inputs I type. What am I doing wrong here?
import java.util.Scanner;
public class QiftPositivCount
{
public static void main(String [] args)
{
Scanner scan = new Scanner(System.in);
final int SENTINEL = -9999;
int x = 0;
int count = 0;
do
{
System.out.print("Type numbers (-9999 to end) : ");
x = scan.nextInt();
if(x == SENTINEL)
{
break;
}
count++;
}while (x != SENTINEL);
if(count == 0)
{
System.out.println("You didnt type any number");
}
else
{
System.out.println("There are " + count + " numbers typed , and the numbers that fulfill the conditon are "
+ CountQiftPositiv(x));
}
}
private static int CountQiftPositiv(int nr)
{
int poz = 0;
if(nr % 2 == 0 && nr % 3 == 0 && nr > 0)
{
poz++;
}
return poz;
}
}
Your do-while loop throws out all user input except the last integer entered (if any). Since the only way out of that loop (not counting exceptions) is the sentinel value -9999, that is the only value you will ever assign to x and pass to CountQiftPositiv.
CountQiftPositiv, meanwhile, only returns 1 if for positive integers divisible by 6. For every other value, including your sentinel, it returns 0.
Other Sentinel Problems
The use of a sentinel value is almost always a mistake (unless that's specifically part of your assignment). Sooner or later, that "impossible" input will actually show up.
Since your goal is to continue the loop until the user is done (a "yes or no" question), use a local Boolean variable, and test that. Also, java.util.Scanner has lots of useful methods for exactly this kind of situation, for example:
boolean done = false;
while (! done) {
if (scan.hasNextInt()) {
// Store scan.nextInt() for use later. See below.
} else {
// No more (valid) inputs.
done = true;
}
}
This loop could actually be shortened to just while (scan.hasNextint()) { ... }, but storing your loop's continue-or-end condition in a variable is handy for more complex exit decisions.
Storing User Input
You aren't storing more than one user input, ever. Create a List of some sort to store them, and then operate on that list.
java.util.List<Integer> numbers = new java.util.LinkedList<Integer>();
Later, in the "while not done" loop:
if (scan.hasNextInt()) {
numbers.add(scan.nextInt());
} else {
done = true;
}
Counting User Inputs
No need for count --- your collection of integers will store that for you:
if (numbers.size() == 0) {
System.out.println("You didn't type any numbers!");
}
Printing Output
Finally, output each number only if it fulfills that weird condition. This assumes you rewrite CountQiftPositiv to return a boolean (which it almost does already):
for (int number : numbers) {
if (CountQiftPositiv(number)) {
System.out.println(number);
}
}
You'll probably want to rename that method now that it no longer counts anything.
I leave the rest to you.
PS: It's almost always a good idea to separate input, processing, and output into (at least) three different methods, especially when you're learning. It's vastly easier to understand a bunch of short methods than one do-it-all method, and makes debugging problems like this much easier.
You have return 0 because last input is -9999 a negative number, and this condition if(nr % 2 == 0 && nr % 3 == 0 && nr > 0) is usually false.
Try to change the SENTINEL nymber:
You're using CountQiftPositiv(x) outside of the while loop.
With the code you have, it's the same thing as you call CountQiftPositiv(-9999)
I'm suggesting you to do something like:
do {
System.out.print("Type numbers (-9999 to end) : ");
x = scan.nextInt();
if(x == SENTINEL) {
break;
}
if (CountQiftPositiv(x) > 0) {
count++;
}
} while (x != SENTINEL);
I suggest also to rework your loop since the break is not required if you use the x = scan.nextInt(); wisely.
CountQiftPositiv(x) sends -9999 in because its the last x value always -> as you stop taking inputs when x = -9999
nr < 0 -> poz will stay at 0
I've made a temp variable which will take your input, if the input is not equal to the SENTINEL variable, it will set x = temp thus removing the -9999 value from being passed into CountQiftPositiv().
Also when you are checking for a number that is a factor for multiple numbers, all you have to do is multiply the numbers together and check the mod for that number.
For 2 and 3, all you have to check is 6.
import java.util.Scanner;
public class QiftPositivCount {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
final int SENTINEL = -9999;
int temp;
int x = 0;
int count = 0;
do {
System.out.print("Type numbers (-9999 to end) : ");
if((temp = scan.nextInt()) == SENTINEL){
break;
}else {
x = temp;
count++;
}
} while (temp != SENTINEL); // not really needed as you have the break statement
if (count == 0) {
System.out.println("You didnt type any number");
} else {
System.out.println("There are " + count + " numbers typed , and the numbers that fulfill the conditon are "
+ CountQiftPositiv(x)); // This was sending -9999 which will always evaluate to false in the function
//poz will stay at 0 the entire time
}
}
private static int CountQiftPositiv(int nr) {
int poz = 0;
//if(nr % 6 && nr > 0){
if (nr % 2 == 0 && nr % 3 == 0 && nr > 0) {
poz++;
}
return poz;
}
}

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