I want a program that repeatedly prompts the user to input a number and then prints whether that number is prime or not. This works once, then on the next iteration it gives a No Such Element Exception before the user can enter another input.
I've tried using IF statements with hasNext() or hasNextInt() but those never seem to be true for the same reason. I also tried using a FOR loop to iterate a fixed number of times but that gives the same error. Why is this allowing for user input the first time it loops through but not after that?
public static void primeChecker()
{
Scanner scan = new Scanner(System.in);
System.out.print("Please enter a number: ");
int number = scan.nextInt();
if (isPrime(number)) {
System.out.println(number + " is prime");
}
else {
System.out.println(number + " is not prime");
}
scan.close();
}
public static void main(String[] args)
{
int y=1;
while(y!=0)
{
primeChecker();
}
Remove scan.close();, as it is closing the scanner.
In order to repeatedly ask the user for a number without stopping, you need to put a while around the code.
Here is my take on this challenge:
public static void primeChecker() {
while(true) {
Scanner scan = new Scanner(System.in);
System.out.print("Please enter a number: ");
int number = scan.nextInt();
if (isPrime(number)) {
System.out.println(number + " is prime");
} else {
System.out.println(number + " is not prime");
}
}
}
public static void main(String[] args) {
primeChecker();
}
This code should repeatedly ask you for a number(after telling you what the previous answer was). It worked for me!
First of all what does your local variable have to do with the function? even if you pass it to function it won't change.
by looking at your code one thing you can do is safely remove y it has nothing to with it, and check in prime checker if number is equal to 0 System.exit(), this is one way to do it without changing much of this code.
while (true) {
primeChecker();
}
and inside primeChecker
int number = scanner.nextInt();
if (number == 0) {
System.exit(0);
}
it will terminate the programme when input is 0.
here you can learn more about System.exit:- https://www.baeldung.com/java-system-exit
Related
I'm new to Java and I'm trying to add a way to loop an if-else statement by asking the user if they want to try again at the end of the program, which I have attempted with a do-while loop. However, when compiling the program it outputs a java error stating that tryAgain cannot be resolved to a variable. Any help would be appreciated.
import java.util.Scanner;
public class Simple{
public static void main(String[] Args){
Scanner againScanner = new Scanner(System.in);
Scanner numberScanner = new Scanner(System.in);
do{
System.out.println("Please type an integer and I will determine whether it is odd or even.");
int number = numberScanner.nextInt();
if(number % 2 == 0){
System.out.println(number + " is an even number.");
}
else{
System.out.println(number + " is an odd number.");
}
numberScanner.close();
}
while (tryAgain = true);
System.out.println("Would you like to try again (type True or False)?");
Boolean tryAgain = againScanner.nextBoolean();
againScanner.close();
}
}
First of all, I must point out that the compilation of the java language is sequential, you must define before using any property or variable, and your tryAgain must be defined before using it.
Second, in java, any variable defined in the body of a loop is called a local variable, and it cannot be referenced by global code, so your code must be modified like this:
public class Simple{
public static void main(String[] Args){
Scanner againScanner = new Scanner(System.in);
Scanner numberScanner = new Scanner(System.in);
Boolean tryAgain=true;
do{
System.out.println("Please type an integer and I will determine whether it is odd or even.");
int number = numberScanner.nextInt();
if(number % 2 == 0){
System.out.println(number + " is an even number.");
}
else{
System.out.println(number + " is an odd number.");
}
System.out.println("Would you like to try again (type True or False)?");
tryAgain= againScanner.nextBoolean();
}
while (tryAgain);
againScanner.close();
numberScanner.close();
}
}
I'm looking to repeat a "game" if it is already satisfied in my case where user has to guess the random number. I can't understand where to to get back to the main game unless i have to create another "do - while" loop inside it and retype the game again in the section where it says: System.out.println("you have tried: " + count + " times. Would you like to play again? y/n"). Is there a way to just bring back to the actual guess loop rather than create another one?
Hopefully makes sense.
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class pass {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String pass = "password123";
String input;
int guess;
int count;
count = 0;
int num;
do {
System.out.print("Enter your password: ");
input = scanner.next();
} while (!input.equals(pass));
System.out.println("Correct! Now play the guess game! Guess a number between 1 - 10.");
do {
num = ThreadLocalRandom.current().nextInt(1,10);
guess = scanner.nextInt();
count++;
if (guess == num) {
System.out.println(" Well done!");
**System.out.println("you have tried: " + count + " times. Would you like to play again? y/n");**
}
else if (guess < num) {
System.out.println("your number is smaller than the number given");
}
else {
System.out.println("your guess is too high");
}
} while (guess != num);
}
}
The simplest solution would be to move the entire "guess loop" into a separate method. Then in the case when you want it to repeat, just call the method recursively.
If you want to reuse code you can make functions (or methods here, because we are inside a class). They can be used to encapsulate code and call it from anywhere to use it.
You can define a methods like that:
public static void methodName() {
// code go here
}
Then, you can call it from anywhere like that :
pass.methodName(); // It will execute the code inside methodName()
In reality, this is a lot more complex than that, you can give methods values and return others, change the scope of it to make it internal only or reachable by other classes. But I presume that you are a beginner so I keep it simple. I strongly recommend you to make a quick research about Object Oriented Programmation!
For your code, you can put the game's while loop in a method and call it at the beginning and each time the player wants to restart the game. Good luck with your game!
I manage to do this way. It seems working but one thing is letting me down at the very last when I key in "n" or other key than "y". Exception in thread "main" java.util.InputMismatchException. Is there a more softer way to finish it?
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class pass {
public static void randomnum(){
Scanner scanner = new Scanner(System.in);
int guess;
int count;
count = 0;
int num;
do {
num = ThreadLocalRandom.current().nextInt(1,10);
guess = scanner.nextInt();
count++;
if (guess == num) {
System.out.println(" Well done!");
System.out.println("you have tried: " + count + " times.");
String answer;
do{
System.out.println("Do you want to play again? y/n");
answer = scanner.next();
if (answer.equals("y")) {
System.out.println("let's play again");
randomnum();
System.out.println("Correct! Now play the guess game! Guess a number between 1 - 10.");
}
else {
System.out.println("you are logout!");
break;
}
}while (answer.equals("Y"));
randomnum();
}
else if (guess < num) {
System.out.println("your number is smaller than the number given");
}
else {
System.out.println("your guess is too high");
}
} while (guess != num);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String pass = "password123";
String input;
do {
System.out.print("Enter your password: ");
input = scanner.next();
} while (!input.equals(pass));
System.out.println("Correct! Now play the guess game! Guess a number between 1 - 10.");
randomnum();
}
}
I need a help trying to set my code to continuously receive user input for factorial numbers. It will produce a question and intake the user input but only once. I want it to continue asking the user for that input.
I tried to do a while loop however nothing shows up.
import java.util.Scanner;
public class FactorialRecursion
{
public static void main(String[] arg)
{
Scanner scan = new Scanner(System.in);
long userInput;
System.out.println("Please enter a number you would like find the factorial of.");
userInput = scan.nextLong();
long fc = FactorialRecursion.fact(userInput);
System.out.println("Factorial = " + fc);
}
public static long fact(long x)
{
if (x <= 0)
return 1;
else
return FactorialRecursion.fact(x - 1) * x;
}
}
The output is correct but I want my program to continue asking for that input.
public class Test{
public static void main(String []args) {
int num;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter numbers!");
while((num = scanner.nextInt()) > 0) {
System.out.println("Receiving...");
}
{
System.out.println("Negative number Stopping the system...");
System.exit(1);
}
}
}
Without knowing how you were looping before (my assumption is that you were including the scanner instantiation which might have caused an issue), here is an implementation that I believe will work for you. This will continue to scan for a number, unless a negative number is entered. Therefore you have an actual exit condition that doesn't make sense for factorial, and the user can repeatedly enter and find the factorial of positive numbers.
In order for this to work, I instantiated the userInput variable to be 0 so that the loop will run for the first time. You can alteratively use a do...While loop in stead, but I prefer this method generally.
public static void main(String[] arg)
{
Scanner scan = new Scanner(System.in);
long userInput=0;
while(userInput >=0)
{
System.out.println("Please enter a number you would like find the factorial of. Enter a negative number to exit.");
userInput = scan.nextLong();
long fc = FactorialRecursion.fact(userInput);
System.out.println("Factorial = " + fc);
}
}
If you would like to see what the do-while loop would look like, just comment and I'll put a little more time into answering this. Also any questions you have comment away!
Total newbie here, please forgive the silly question. As an exercise I had to make a program (using do and while loops) that calculates the average of the numbers typed in and exits when the user types 0. I figured the first part out :) The second part of the exercise is to change the program to display an error message if users types 0 before typing any other number. Can you kindly explain to me what is the easiest way to accomplish this? If you provide the code is great but I’d also like an explanation so I am actually understanding what I need to do.
Thank you! Here is the code:
import java.util.Scanner;
public class totalave1 {
public static void main(String[] args) {
int number, average, total = 0, counter = 0;
Scanner fromKeyboard = new Scanner(System.in);
do {
System.out.println("Enter number to calculate the average, or 0 to exit");
number = fromKeyboard.nextInt();
total = total + number;
counter = counter + 1;
average = (total) / counter;
} while (number != 0);
System.out.println("The average of all numbers entered is: " + average);
}
}
The second part of the exercise is to change the program to display
an error message if users types 0 before typing any other number.
It is not very clear :
Do you you need to display a error message and the program stops ?
Do you you need to display a error message and to force the input to start again ?
In the first case, just add a condition after this instruction : number=fromKeyboard.nextInt(); :
do{
System.out.println("Enter number to calculate the average, or 0 to exit");
number=fromKeyboard.nextInt();
if (number == 0 && counter == 0){
System.out.println("Must not start by zero");
return;
}
...
} while (number!=0);
In the second case you could pass to the next iteration to take a new input.
To allow to go to next iteration, just change the number from zero to any value different from zero in order that the while condition is true.
do{
System.out.println("Enter number to calculate the average, or 0 to exit");
number=fromKeyboard.nextInt();
if (number == 0 && counter == 0){
System.out.println("Must not start by zero");
number = 1;
continue;
}
...
} while (number!=0);
The good news is that you probably have done the hardest part. :) However, I don't want to give too much away, so...
Have you learned about control flow? I assume you might have a little bit, as you are using do and while. I would suggest taking a look at the following Java documentation first: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
Then, look at your current solution and try to think what conditions you have that would lead you to display the error message, using if statements. How do you know the user typed a 0? How do you know it's the first thing they entered? Are there any variables that you have now that can help you, or do you need to create a new one?
I know this is not a code answer, but you did well in this first part by yourself already. Let us know if you need further hand.
Don't go down code after reading and if you cant then see the code.
First you have to learn about the flow control. Second you have to check whether user entered 0 after few numbers get entered or not, for that you have to some if condition. If current number if 0 and it is entered before anyother number then you have to leave rest of the code inside loop and continue to next iteration.
import java.util.Scanner;
public class totalave1
{
public static void main (String[]args)
{
int number, average, total=0, counter=0;
boolean firstTime = true;
Scanner fromKeyboard=new Scanner (System.in);
do{
System.out.println("Enter number to calculate the average, or 0 to exit");
number=fromKeyboard.nextInt();
if(firstTime && number==0){
System.out.println("error enter number first");
number = -1;
continue;
}
firstTime = false;
total=total+number;
counter=counter+1;
average=(total)/counter;
} while (number!=0);
System.out.println("The average of all numbers entered is: "+average);
}
}
Here is a simple program that extends on yours but uses nextDouble() instead of nextInt() so that you can enter numbers with decimal points as well. It also prompts the user if they have entered invalid input (something other than a number):
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Java_Paws's Average of Numbers Program");
System.out.println("======================================");
System.out.println("Usage: Please enter numbers one per line and enter a 0 to output the average of the numbers:");
double total = 0.0;
int count = 0;
while(scanner.hasNext()) {
if(scanner.hasNextDouble()) {
double inputNum = scanner.nextDouble();
if(inputNum == 0) {
if(count == 0) {
System.out.println("Error: Please enter some numbers first!");
} else {
System.out.println("\nThe average of the entered numbers is: " + (total / count));
break;
}
} else {
total += inputNum;
count++;
}
} else {
System.out.println("ERROR: Invalid Input");
System.out.print("Please enter a number: ");
scanner.next();
}
}
}
}
Try it here!
I am trying to read an integer from the user, then print even if that number is an even number or odd otherwise. I have been told I can assume that the user types a valid integer. The input/output should match the following example:
Type a number: 14
even
What am I missing? Any ideas on how I can get the desired inputs and expected outputs? Test1[3][Test4]4
import java.util.Scanner;
public class evenOdd {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int even = scan.nextInt();
int odd = scan.nextInt();
if ((even%2)==0){
System.out.println("Type a number:"+ even);
}
else {
System.out.println("Type a number:"+ odd);
}
}
}
The problem is that you have all your variables and order of the flow of your program mixed up. In English this is what you are doing
Prompt user for an integer, call that integer "even"
Prompt user for an integer, call that integer "odd"
If the integer called "even" is divisible by 2 without a remainder then print "type a number" and then the value of the integer called "even"
Otherwise print "type a number" and then the value of the integer called "odd"
You only need to read a value from the user once, then decide which message to print based on that value:
import java.util.Scanner;
public class evenOdd {
public static void main(String[] args) {
System.out.println("Type a number:");
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
if ((number%2)==0){
System.out.println("even");
}
else {
System.out.println("odd");
}
}
}
I have pointed out some issues in your code. Please correct them.
import java.util.Scanner;
//follow java naming convention and name class as "EvenOdd"
public class evenOdd {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int number = scan.nextInt(); //renamed to number
int odd = scan.nextInt(); //do not need this variable
if ((number %2)==0){
System.out.println("Even");
}
else {
System.out.println("Odd");
}
}
}
Ask the user the question first so that he knows he has to input a number
System.out.println("Type a number: ");
You can simply just get 1 input from the user and store on the same variable
int input = scan.nextInt();
Then you would just check that 1 input with the if/else and display the correct output
if ((input%2)==0){
System.out.println(input + " is even.");
}
else {
System.out.println(input + " is odd.");
}