Using method to find an integer repeatedly - java

Hello my purpose is this:
Write a method that can accept values only between 10 and 50.Sample execution:Enter a number between 10 and 50Enter a number: 5Enter a number between 10 and 50Enter a number: 12Number Entered: 12.Enter a number: 0Good ByeSo as you can see it only finishes when user enters 0.And it says different things when number is between 10 and 50 or not.I deleted again my code and started but i got stuck on some points and i gave up.My final code was:
import java.util.Scanner;
public class A{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter case number: ");
int caseVal = scan.nextInt();
switch(caseVal){
case 1:
System.out.println("Enter a number between 10 and 50");
System.out.println("Enter a number: ");
int num = scan.nextInt();
betweenMethod(num);
if(num == 0){
System.out.println("Good Bye");
break;
}
while(num != 0){
betweenMethod(num);
}
break;
case 2:
System.out.println("Enter a number to display its divisors: ");
int x = scan.nextInt();
System.out.println("The divisors of " + x + " are:");
divisorsMethod(x);
break;
}
scan.close();
}
public static void divisorsMethod(int a){
if(a <= 0)
System.out.println("The number should be greater than 0");
else{
for(int b = 1; b <= a; b++){
if(a % b == 0 && b != a)
System.out.print(b + ", ");
else if(b == a)
System.out.println(b);
}
}
}
public static void betweenMethod(int a){
Scanner inputscan = new Scanner(System.in);
if(a >= 10 && a <= 50){
System.out.println("Enter a number:");
a = inputscan.nextInt();
}
else if((a < 10 || a > 50) && a != 0){
System.out.println("Enter a number between 10 and 50");
System.out.println("Enter a number:");
a = inputscan.nextInt();
}
else{
System.out.println("Good Bye");
}
inputscan.close();
}
}
Sorry for uncut version.It is case 1.Every time i tried it didnt work fully.If anyone can help i would appreciate it.I'm sorry if i didnt write this question in rules.(Sorry for the grammar as well)THIS IS WHERE I AM STUCK= When i type 0 it doesnt say GoodBye and end the loop.Thats where i need help.TO EVERYONE THAT NEEDS ANSWER TOO:I figured out what to do.Basically we say while its not equal to zero right?I wrote a new method that (after last inputscan for variable)checks if the number is zero and prints good bye.So with this way it prints good bye and it goes to starting.But it cannot do anythink else because we said while not equal to 0.Anyway thats one solution.

Don't close() System.in
When you call inputscan.close() that closes the underlying InputStream, which is System.in.
Return the Value
Your method should be prompting for input between two values and returning a single value. Also, you could move your Scanner to a static (or class) field. Something like
private static Scanner inputscan = new Scanner(System.in);
public static int betweenMethod(final int a, final int b) {
int min = Math.min(a, b);
int max = Math.max(a, b);
while (true) {
System.out.printf("Please enter a number between %d and %d%n", min, max);
int in = inputscan.nextInt();
if ((in == 0) || (in >= min && in <= max)) {
return in;
}
}
}
Primitives1 are Passed-By Value
You need to assign the result of the call back to your value when you loop. Something like,
int num = betweenMethod(10, 50);
while (num != 0) {
System.out.printf("Number Entered: %d.%n", num);
num = betweenMethod(num);
}
System.out.println("Good Bye");
break;
1and Everything Else in Java.

Related

I want to write a program that allows the user to guess a number between 0 and 100 in 7 attempts. I don't know why is this not working

public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int rnd = (int)(Math.random() * 101);
System.out.println("The program is going to give a number that is between 0 and 100 (including them). You can guess it by pressing Run.");
System.out.println("Enter your number:");
int num = scan.nextInt();
for (int count = 1; count <= 7; count++) {
while (num != rnd) {
if (num < rnd) {
System.out.println("Your guess is too low.");
}
if (num > rnd) {
System.out.println("Your guess is too high.");
}
if ((Math.abs(rnd - num) == 1) || (Math.abs(rnd - num) == 2)) {
System.out.println("But your guess is VERY close.");
}
num = scan.nextInt();
}
System.out.println("You got it right!");
}
System.out.println("You should guess it in 7 tries.");
}
}
So I used two loops and just nested them. Is that how it works for this? Right now the code is like starting with for loop and if that is true it goes to the while loop part where the guessing number takes place. Can this be fixed with just moving some codes and fixing minor areas around?
What you should do in a situation like this is do the code manually. Literally. Grab a piece of paper and pretend you're a computer. It's a good exercise, and it will help you figure out your problem.
The problem is your inner loop. It loops until they guess correctly regardless of the number of attempts. Then you force them to do it 6 more times with the outer loop.
You really only need 1 loop. I would have a single loop like this:
int attempts = 0;
int num = 0;
do {
num = scan.nextInt();
... most of the if code from your inner loop but not another scan.nextInt
} while (++attempts < 7 && num != rnd);
// and here you look at num == rnd to see if success or failures
I think you should rebuild you code to make it more clear.
Split the title (with description of the task)
Split main loop where you read user input and check it with expected number
Split output of the final result, where you print the result.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
final int rnd = new Random().nextInt(101);
final int maxAttempts = 7;
System.out.println("The program is going to give a number that is between 0 and 100 (including them).");
System.out.println("You can guess it within maximum " + maxAttempts + " attempts by pressing Run.");
boolean success = false;
for (int attempt = 1; attempt <= maxAttempts && !success; attempt++) {
System.out.format("(%s of %s) Enter your number: ", attempt, maxAttempts);
int num = scan.nextInt();
if (num == rnd)
success = true;
else {
System.out.print("Your guess is too " + (num > rnd ? "high" : "low") + '.');
System.out.println(Math.abs(rnd - num) <= 2 ? " But it's VERY close." : "");
}
}
System.out.println(success ? "You got it right!" : "Bad luck this time. Buy.");
}
import java.util.Scanner;
class Main {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int rnd = (int) (Math.random() * 101);
System.out.println("The program is going to give a number that is between 0 and 100 (including them). You can guess it by pressing Run.");
System.out.println("Enter your number:");
int num = scan.nextInt();
for(int count = 1; count <= 7; count++)
{
if (num < rnd)
{
System.out.println("Your guess is too low.");
}
else if (num > rnd)
{
System.out.println("Your guess is too high.");
}
else if ((Math.abs(rnd - num) == 1) || (Math.abs(rnd - num) == 2))
{
System.out.println("But your guess is VERY close.");
}
else
System.out.println("You got it right!");
System.out.println("Enter Next number: ");
num = scan.nextInt();
}
}
}
It should work Fine.Basically Your reasoning wass wrong because You are putting a while loop inside a for loop. What you want to do is you want only 7 iteration.In those 7 iterations you are checking the conditions based on user Input.

How am i going to use while loop and if else if user enter the same input twice and it will try again

I want to apply this function in java. Inside while loop, you need to input number of repetition you want to input a number. if you input a number that equals to the number that you enter previously, it will repeat a loop and enter a number again. This code is not finish yet. I hope u understand what i want to achive. thank you
System.out.print("Enter number of times: ");
int times = number.nextInt();
int i = 1;
while ( i <= times){
System.out.print("Enter a number : ");
int input = number.nextInt();
i++;
if( input == input){
System.out.println("It is already taken");
}
}
}
}
Let's use a temp variable to store the value of previous input. If new input is same as previous input, the iterator i should not increase, so we use i--
System.out.print("Enter number of times: ");
int times = number.nextInt();
int i = 1;
int temp=0;
int inputArray[] = new int[times];
while ( i <= times){
System.out.print("Enter a number : ");
int input = number.nextInt();
i++;
if( input == temp){
System.out.println("It is already taken");
i--;
}else {
inputArray[i-2]=input;
}
temp=input;
}
}
The thing with that solution is that is only checks for the number just entered before the current one. I understood that you want to check that the number the user entered is unique and it has to be checked against every number that he/she has entered before.
See the code for that:
import java.util.Scanner;
import java.util.ArrayList;
public class testMe{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of times: ");
int times = scanner.nextInt();
int i = 0;
ArrayList<Integer> listWithEntries = new ArrayList<Integer>();
while (i < times){
System.out.print("Enter a number : ");
int input = scanner.nextInt();
if(listWithEntries.size() == 0){
listWithEntries.add(input);
i++;
} else {
for(int j = 0; j < listWithEntries.size(); j++){
if(input == listWithEntries.get(j)){
System.out.println("It is already taken!");
break;
}
if(j == listWithEntries.size()-1 && input !=
listWithEntries.get(j)){
listWithEntries.add(input);
i++;
break;
}
}
}
}
}
}

How to use methods with a while loop

I want to get the output when I enter a odd number (eg. 3) it will be give the output '3' and if I enter a even number it will print 'wrong input'.
I know I can use if else but I want to use the while loop to get it.
I am a beginner in programming so I would appreciate if someone can help me thanks
This are my codes right now. When I run it there is an error.
import java.util.Scanner;
public class UserInput {
public static void main(String[] args) {
int num;
num = readOddNum();
System.out.println("The odd integer is" + num);
}
public static int readOddNum() {
int num = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter an odd number: ");
int num1 = sc.nextInt();
sc.close();
while ((num < 0) &&(num % 2 == 0)) {
System.out.println("Wrong input!");
}
return readOddNum();
}
}
You should change your code to
public static int readOddNum() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter an odd number: ");
int num1 = sc.nextInt();
while ((num1 < 0) || (num1 % 2 == 0)) {
System.out.println("Wrong input! - try again");
num1 = sc.nextInt();
}
sc.close();
return num1;
}
Change your readOddNum logic to this..
public static int readOddNum() {
int num;
Scanner sc = new Scanner(System.in);
num = readNumber(sc);
while ((num < 0) || (num % 2 == 0)) {
System.out.println("Wrong input!");
num = readNumber(sc);
}
sc.close();
return num;
}
public static int readNumber(Scanner sc){
System.out.print("Enter an odd number: ");
return sc.nextInt();
}
The code can be rewritten in the following way
import java.util.Scanner;
public class UserInput
{
public static void main(String[] args)
{
//int num;
readOddNum();
//System.out.println("The odd integer is" + num);
}
public static void readOddNum()
{
int num = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter an odd number: ");
int num1 = sc.nextInt();
sc.close();
while ((num1 < 0) ||(num1 % 2 == 0))
{
System.out.println("Wrong input!");
break;
}
System.out.println("The odd integer is" + num1);
// return readOddNum();
}
}
As you can see, I have directly called the method readOddNum(); and defined it as void instead of the earlier version. Also, notice the changes in the while loop. You were initialising num with 0 and using it in the while loop whereas the loop should run on num1 which is the actual user input, not num.
Next thing is you used &&(logical AND) instead of ||(logical OR) and both obviously have different meanings. && will mean that even if user enters an even number like 2 it should also be less than 0 which isn't the case. So you need to use ||. Also, you will need to use break to stop the loop once the statement is printed, else it will keep on executing infinitely as there's no other stopping condition. Remember that if else has been created for scenarios like these where you have to choose between two or more situations and execute only one, so while loop will work but it will also execute the print statement, thereby stating wrong input and odd number. This is the output you get
C:\Java\jdk1.8.0_141\bin>java UserInput
Enter an odd number: 3
The odd integer is3
C:\Java\jdk1.8.0_141\bin>java UserInput
Enter an odd number: 2
Wrong input!
The odd integer is2
Hope you understood the concept. Appreciate it, if you like it. Thank you.

if and else statements not working java

Hi I am trying to take in an integer between 1 and 10.
If the user does not do so would like the program to run again.
I believe that I need to use an else if statement that calls on my function but I do not know how to call functions in java.
Here is my code so far:
import java.util.Scanner;
public class NumChecker {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Enter a number between 1 and 10: ");
int num1 = in.nextInt();
if (num1 >= 1 && num1 <= 10); {
System.out.println("Input = " + num1);
}
else if {
???
}
}
}
if-else always work.
You made a mistake in the if statement.
there is no ; for an if
if (num1 >= 1 && num1 <= 10) {//no semicolon
System.out.println("Input = " + num1);
}
else if(num < 0) {//should have a condition
...
}
else
{
...
}
What happens if I put a semicolon at the end of an if statement?.
How do I ask the user again if the input is not in between 1 and 10?
Loop until you get what you want :)
Scanner sc = new Scanner(System.in);
int num = 0;
while(true)
{
num = sc.nextInt();
if(num > 0 && num < 11)
break;
System.out.println("Enter a number between 1 and 10");
}
System.out.println(num);
Since you are expecting a number between 1 to 10, but you don't know how many numbers you will get until you get a valid number, I'd suggest to use a while loop, like so:
import java.util.Scanner;
public class NumChecker {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Enter a number between 1 and 10: ");
int num1 = in.nextInt();
while (num1 < 1 || num1 > 10) {
System.out.print("Invalid number, enter another one: ");
num1 = in.nextInt();
}
System.out.println("Input = " + num1);
}
}

test for data type errors in loops java

Yes, this is a homework problem. I am a beginner in programming. I am good at using if/else with for loops, since my professor asked us to while loop. I am confused.This is the question...
Q1) Suppose you are writing a game-playing program that involves 2-digit numbers, each number being composed of 2 different digits. Test if whether numbers entered in a sequence are accepted to be used in this game. Test for errors in input (including type).
My while loop to check the data type works fine at first, but after an int has been entered and I can't check the data type. Can anyone explain the problem to me please? Thank you...
public static void main(String[] args){
int num = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter a 2-digit number. The digits should be different. zero to stop");
while(!input.hasNextInt()){
System.out.println("Not an integer,try again " + num);
input.next();
}
num = input.nextInt();
while(num != 0){
while(num < 10 || num >= 99){
System.out.println("NOT good for your game! " + num );
System.out.println("Enter a 2-digit number. The digits should be different. Zero to stop");
num = input.nextInt();
}
System.out.println("Good for your game! Play! " + num);
num = input.nextInt();
}
}
}
The while loop in the first checked the System.in is entering a digit (int) or not: while(!input.hasNextInt()), but when you first input a digit, the loop exit and it enter into the next 2 loops:
while(num != 0){
while(num < 10 || num >= 99){
and then in the end of the inner loop you have:
num = input.nextInt();
This means you already assume the next input would be an int. So if you enter a non-digit input, program will throw an exception.
I would suggest you to change the whole loop into:
public static void main(String[] args) {
int num = 1;
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter a 2-digit number. The digits should be different. zero to stop");
if (!input.hasNextInt()) {
System.out.println("Not an integer,try again " + num);
} else {
num = input.nextInt();
if (num < 10 || num >= 99) {
System.out.println("NOT good for your game! " + num);
} else {
System.out.println("Good for your game! Play! " + num);
}
}
} while(num != 0);
input.close();
System.out.println("game stop");
}
import java.util.Scanner;
public class Number1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String prompt = "Enter a 2-digit number. The digits should be different. Zero to stop:";
getInt(sc,prompt);
}
public static void getInt(Scanner sc,String prompt) {
System.out.println(prompt);
int num;
while (!sc.hasNextInt())
{
System.out.println("Not an integer, Try again");
sc.next();
}
num = sc.nextInt();
while(num != 0) {
if (num < 10 || num >= 99 || num == 0)
{
System.out.println("Not good for your game!");
}
else
{
System.out.println("Good for your game! Play!");
}
System.out.println(prompt);
num = sc.nextInt();
}
}
}

Categories