I'm trying to test if an input is odd or even. The program says that if the input is even keep going, until the input is odd. When it is odd, it stops the program. But the program isn't stopping. Has anyone any idea?
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
while (isEven()) {
if (isEven()) {
isEven();
} else {
System.out.println(" You added an odd number, done!");
return;
}
}
}
public static boolean isEven(){
int a = scanner.nextInt();
if (a%2 ==0){
System.out.println("You added an even number, go on");
}
return true;
}
}
You'd better simplify all of this, you don't need to call your method multiple times :
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (writeAndCheckEven(Integer.parseInt(scanner.nextLine()))) {
System.out.println("You added an even number, go on");
}
System.out.println("You added an odd number, done!");
}
private static boolean writeAndCheckEven(int number) {
return number % 2 == 0;
}
you don't need to use a return if there is no more code after
you can directly use the scanner in the parameter
don't use both while and if it won't do what you want
You should rewrite this code, because code contains incorrect logic.
Correct code for your requirements:
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
while (true) {
int number = scanner.nextInt();
if (isEven(number)) {
System.out.println("You added an even number, go on");
} else {
System.out.println(" You added an odd number, done!");
return;
}
}
}
private static boolean isEven(int number) {
return number % 2 == 0;
}
Related
public class Main {
public static void main(String[] args) {
System.out.println("Please enter a math value.");
Scanner sayiyaz = new Scanner(System.in);
if(sayiyaz.hasNextInt()) {
int sayi1 = sayiyaz.nextInt();
}
else {
System.out.println("I wish u could know what is a math value .");
}
}
}
In the else block of code i want to restart the "main" method from the beginning and ask the same question.
But how to do that ?
You can call it if you want to (like Sudhakar sugested) but i assume that you just want to request the input until you get something that fits your needs in that case you have a better solution
public static void main(String[] args) {
boolean done = false;
Integer sayi1 = null;
do {
System.out.println("Please enter a math value.");
Scanner sayiyaz = new Scanner(System.in);
if (sayiyaz.hasNextInt()) {
sayi1 = sayiyaz.nextInt();
done = true;
} else {
System.out.println("Input is wrong ");
}
} while (!done);
System.out.println("Here is youre input " + sayi1);
}
The answer is that you don't want to restart main. This is the entry point used by the Java Virtual machine to start your application. The simplest way to do what you want is to use a loop, so something like:
while (true) {
System.out.println("Please enter a math value");
// The rest of your code.
if (finished)
break;
}
This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 5 years ago.
I'm new to Java and I want to make a program that reads an int from keyboard. If you enter a non-int value, it throws an exception and reads again until you enter an int.
The code is:
package Exceptie;
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int n=0;
while(n==0){
try {
n=Integer.parseInt(input.nextLine());
if (n==0) break;
}catch(Exception e){
System.out.println("not int, read again");
}
}
}
}
Can you suggest an approach that doesn't require n to be initialized?
There are many ways this is the simple way, you can use another boolean variable for example :
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n;//no need to initialize n
boolean b = false;
while (!b) {//repeat until b = true
try {
n = Integer.parseInt(input.nextLine());
if (n == 0) {
b = true;//if n == 0 then b = true
}
} catch (NumberFormatException e) {
System.out.println("not int, read again");
}
}
}
You should have used Boolean instead of an integer. Try this.
package Exceptie;
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int n;
boolean isInt = false;
while(!isInt){
try {
n=Integer.parseInt(input.nextLine());
isInt = true;
}catch(Exception e){
System.out.println("not int, read again");
}
}
}
}
so I am fairly new to Java, and most of my previous knowledge is with Python and C++ so I am not really sure how to store data that is inputted so it can be compared. So essentially I am looking to have the user input a bunch of integer values - whatever number they would like. However, when they keep entering these values what will happen is when it is descending (if it descends 3 times in a row) it will break the loop and the program will end. I am not sure how to make the inputted data be stored so it can be compared to the previous entry, or if there is a way to do this without using lists (as I would do in python).
So far what I have is very basic and I need to figure out how to make the if statement in the while loop to be able to compare the previous inputs.
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your number: ");
int n = keyboard.nextInt();
while (true) {
if (n > 0) {
System.out.println("Enter your new number: ")
int n = keyboard.nextInt();
}
}
}
Sorry if this isn't a lot to go on, but I really do not know where to start in terms of comparing the values that are entered in - only really know how to get them to be entered in.
I missed the comment, that you only want to know how to check if the list is sorted. So I wrote some code that solves your issue :) You may compare it to your solution:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Test {
public static final int SIZE = 3;
private static List<Integer> lastThreeValues;
public static void addNewValue(int value) {
if (isFull()) {
lastThreeValues.remove(0);
}
lastThreeValues.add(value);
}
public static boolean isFull() {
return lastThreeValues.size() == SIZE;
}
public static boolean isDescending() {
int prev = Integer.MAX_VALUE;
for (int value : lastThreeValues) {
if (prev > value) {
prev = value;
} else {
return false;
}
}
return true;
}
public static boolean close() {
if (isFull()) {
return isDescending();
}
return false;
}
public static void main(String[] args) {
lastThreeValues = new ArrayList<>(SIZE);
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your number: ");
int n = keyboard.nextInt();
addNewValue(n);
do {
addNewValue(n);
if (n > 0) {
System.out.println("Enter your new number: ");
n = keyboard.nextInt();
}
} while (!close());
keyboard.close();
System.out.println("closed");
}
}
Some more thoughts:
close the Scanner after usage: keyboard.close()
there are some utils for checking if a List is sorted. See How to determine if a List is sorted in Java?
It seems like there is no problem with this code (here it is):
import java.util.*;
public class NumberGuessingGame {
static int randomNumber = (int) (Math.random() * 11);
static Scanner userInput = new Scanner(System.in);
static int guessedNumber = userInput.nextInt();
public static void main(String[] args) {
start: {
while (guessedNumber != randomNumber) {
System.out.println("I'm thinking of a number in my mind between 0 and 10. ");
delay(1500);
System.out.print("Try to guess it: ");
if (guessedNumber == randomNumber) {
System.out.print("Congradulations! ");
delay(800);
System.out.println("The number really was " + randomNumber);
} else {
break start;
}
}
}
}
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
}
}
}
If you couldn't tell already I'm a beginner trying to create a basic number guessing game. So I successfully coded it but now every time I execute it this happens:
It just freezes. Why?
The issue is that you're putting the userInput.nextInt() call in the initializer for a static field; so it gets called (and the program pauses for input) as your class is loading, before it can pribt a prompt requesting the input. So it looks like it froze, but if you enter a number it will then proceed.
You want the nextInt() call to be inside your method after the calls that prompt for input
The error is because your program is waiting for an user input. According to the docs, a Scanning operation may block waiting for input
The solution is implementing a do/while and userInput and guessedNumber initialized when they are required.
NumberGuessingGame:
import java.util.*;
public class NumberGuessingGame {
static int randomNumber = (int) (Math.random() * 11);
static Scanner userInput;
static int guessedNumber;
public static void main(String[] args) {
System.out.println("I'm thinking of a number in my mind between 0 and 10. ");
do
{
delay(1500);
System.out.print("Try to guess it: ");
userInput = new Scanner(System.in);
guessedNumber = userInput.nextInt();
if (guessedNumber == randomNumber) {
System.out.print("Congratulations! ");
delay(800);
System.out.println("The number really was " + randomNumber);
} else {
System.out.println("Error, try again! ");
delay(800);
}
}
while (guessedNumber != randomNumber);
}
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
}
}
}
Documentation:
do-while statement
its probably waiting for you to enter a number. I conformed its not hanging. its waiting for user input. try entering a number.
I am new to java programming, I have programmed in C and C++ but have moved to Java recently, So I am a bit confuse about how things are in Java. I am calling a function inside my main but the program gets terminated, I don't know why its happening and can't figure it out. Here is my program
package Prime;
import java.util.Scanner;
public class isprime
{
public static boolean isPrime (int n)
{
int flag=0;
for (int i=2;i<=n;i++)
{
if(i%n==0)
{
flag=1;
}
}
if(flag==1)
{
return false;
}
else
{
return true;
}
}
public static void main(String[] args)
{
int n;
System.out.println("Please enter a number you want to test");
Scanner sc = new Scanner(System.in);
sc.close();
isPrime(n);
}
n = sc.nextInt();
}
Your n = sc.nextInt(); is outside the scope of main() function. Moreover your are closing the scanner first.
You called isPrime(n); which returns boolean but you did not catch the return value.
You want to do something like:
public static void main(String[] args) {
int n;
System.out.println("Please enter a number you want to test");
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
if (isPrime(n)) {
System.out.println("prime");
} else {
System.out.println("not prime");
}
sc.close();
}
Finally, your prime calculation is wrong. A prime number is divisible by itself, so change
for (int i=2;i<=n;i++)
to
for (int i=2;i < n;i++)
^^^