How can I find out why my Java program keeps crashing? - java

I have been learning Java for a week, I have no other experiences. The program keeps crashing, I would like to be automatically asked again in the event of an incorrect entry.
import java.util.Scanner;
public class test {
public static void main(String[] args) {
boolean error;
Scanner scan = new Scanner(System.in);
do {
error = false;
System.out.print("Tell me the Year: ");
if (scan.hasNextInt()) {
int jahr = scan.nextInt();
scan.close();
if (schaltjahre(jahr)) {
System.out.println("Please enter the leap year ");
} else {
System.out.println("It is not a leap year");
}
} else {
System.err.println("enter an integer year!");
error = true;
scan.close();
}
}while (error);
}
public static boolean schaltjahre(int jahr) {
// Aufgabe 1
if (jahr % 400 == 0) {
return true;
} else if (jahr % 100 == 0) {
return false;
} else if (jahr % 4 == 0) {
return true;
}
return false;
}

You should instantiate the scanner inside the loop and don't close it in the else statement.
Your code should be something like this :
public static void main(String[] args) {
boolean error;
Scanner scan ;
do {
error = false;
scan = new Scanner(System.in);
System.out.print("Tell me the Year: ");
if (scan.hasNextInt()) {
int jahr = scan.nextInt();
scan.close();
if (schaltjahre(jahr)) {
System.out.println("Please enter the leap year ");
} else {
System.out.println("It is not a leap year");
}
} else {
System.err.println("enter an integer year!");
error = true;
}
} while (error);
}

Related

Java - Continue a game

I made some command line games and at the end of the game I want to ask if the player wants to play again. You can see in the code how I made but it's not working and I don't know why.
Can anybody help me?
import java.util.Scanner;
//WIP
public class GuessingGame2 {
static Scanner userInput = new Scanner(System.in);
static int randNumber;
static int guessNumber;
static boolean gameStatus;
static void checkNum(int x) {
guessNumber++;
if(x == randNumber) {
gameStatus = true;
} else if(x < randNumber) {
System.out.println("Too small!");
} else {
System.out.println("Too big!");
}
}
static void checkAnsw() {
if(userInput.hasNextLine()) {
if(userInput.nextLine() == "Y" || userInput.nextLine() == "y") {
guessGame();
} else if(userInput.nextLine() == "N" || userInput.nextLine() == "n") {
} else {
System.out.print("Y or N ");
checkAnsw();
}
} else {
System.out.print("Y or N ");
userInput.next();
checkAnsw();
}
}
static void guessGame() {
randNumber = (int) (Math.random() * 1000);
guessNumber = 0;
gameStatus = false;
System.out.println("Try to guess a number from 1 to 1000!");
while(gameStatus == false) {
System.out.print("Your guess: ");
if(userInput.hasNextInt()) {
checkNum(userInput.nextInt());
} else {
System.out.println("You need to choose a number!");
userInput.next();
}
}
System.out.println("You guessed the number in " + guessNumber + " tries.");
System.out.print("Do you want to play again? Y or N ");
checkAnsw();
}
public static void main(String[] args) {
guessGame();
}
}
Change your checkAnsw method to this:
static void checkAnsw() {
if(userInput.hasNextLine()) {
if(userInput.nextLine().equalsIgnoreCase("y")) {
guessGame();
} else if(userInput.nextLine().equalsIgnoreCase("n")) {
} else {
System.out.print("Y or N ");
checkAnsw();
}
} else {
System.out.print("Y or N ");
userInput.next();
checkAnsw();
}
}
You cannot compare Strings with the = as they are objects. Use the .equals method to compare Strings.
Your code works fine, I have copied and pasted it in Eclipse and this is the output:
Try to guess a number from 1 to 1000!
Your guess: eeeee
You need to choose a number!
Your guess: 1
Too small!
Your guess: 2
Too small!
Your guess: 2
I don't understand which is your problem, try to explain better

Unexpected Error (Global Variable/Enum)

I have written the following piece of code:
import java.util.Scanner;
public class Congress {
public static int age;
public static int ctzn;
public static boolean eligibleForSenate() {
if ( age >= 25 && ctzn >= 7) {
return true;
} else {
return false;
}
}
public static boolean eligibleForHouse() {
if ( age >= 30 && ctzn >= 9) {
return true;
} else {
return false;
}
public static void main(String[] args) {
System.out.print("Enter age of candidate: ");
Scanner sc = new Scanner(System.in);
age = sc.nextInt();
System.out.println();
System.out.print("Enter years of U.S. Citizenship: ");
ctzn = sc.nextInt();
}
}
}
It gives me an error on the main line. I believe it has something to do with the global variables. How can I fix it?
There is a typo ::
Change code as follow ::
import java.util.Scanner;
public class Congress {
public static int age;
public static int ctzn;
public static boolean eligibleForSenate() {
if ( age >= 25 && ctzn >= 7) {
return true;
} else {
return false;
}
}
public static boolean eligibleForHouse() {
if ( age >= 30 && ctzn >= 9) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
System.out.print("Enter age of candidate: ");
Scanner sc = new Scanner(System.in);
age = sc.nextInt();
System.out.println();
System.out.print("Enter years of U.S. Citizenship: ");
ctzn = sc.nextInt();
}
}
Your braces are not matching, add one closing brace } before your main and remove one from the last line.

I keep getting NoSuchElement exception in my Java code. What's wrong with my code?

My Java 1.7 program performs various mathematical functions. I have separated the functions into methods and they work ok on their own. I also made a prompt method that asks the users if they want to continue. However, I keep on getting NoSuchElement exception after inputting a number. "Try again? (n/y) " prints, but it doesn't wait for user input and errors automatically. Eclipse Luna highlights this line:
String response = scanner.next();
Here's the main method:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Please input a number: ");
int x = scanner.nextInt();
System.out.println(chooseOperation(x));
do_Continue();
if (do_Continue() == false) {
break;
}
}
scanner.close();
}
Here's the operation chooser method:
public static int chooseOperation(int n) {
Scanner scanner = new Scanner(System.in);
System.out.print("Factorial, Fibonacci, or Pisano? ");
String response = scanner.next();
scanner.close();
if (response.equalsIgnoreCase("factorial")) {
return factorial(n);
} else if (response.equalsIgnoreCase("fibonacci")) {
return fibonacci(n);
} else if (response.equalsIgnoreCase("pisano")) {
return pisano(n);
} else {
System.out.print("Invalid response. ");
chooseOperation(n);
return n;
}
}
And here's the prompt method:
public static boolean do_Continue() {
Scanner scanner = new Scanner(System.in);
System.out.print("Try again? (n/y): ");
String response = scanner.next();
scanner.close();
if (response.equalsIgnoreCase("n")) {
return false;
} else if (response.equalsIgnoreCase("y")){
return true;
} else {
System.out.print("Invalid response. ");
do_Continue();
}
return false;
}
If this helps, here are the methods for the math functions:
public static int factorial(int n) {
if (n==1 || n==0) {
return 1;
} else {
return n*factorial(n-1);
}
}
public static int fibonacci(int n) {
if (n==1 || n==0) {
return n;
} else {
return fibonacci(n-1) + fibonacci(n-2);
}
}
public static int pisano(int n) {
if (n==1 || n==0) {
return n;
} else {
return (fibonacci(n-1) + fibonacci(n-2)) % 7;
}
}
As you can see, except for the main method, all my methods are recursive.
Thanks! :)
Do not call
scanner.close();
When you do that, you close() System.in! Then when you attempt to construct your new Scanner(System.in); it doesn't work (because System.in is closed).

Correct code will not compile?

This code seems perfectly fine for me (CS101) but my IDE throws up the error "This method must return a result of type boolean"
I don't want any tips on how to streamline my code or anything like that just want a reason for / solution as to why this is happening
public static boolean validation(String correct1, String correct2)
{
Scanner in = new Scanner(System.in);
boolean correctInput = false;
String userInput;
while (correctInput == false)
{
System.out.print("Type in " + correct1 + " or " + correct2);
userInput = in.next();
if ( userInput.equals(correct1) )
{
return true;
}else if ( userInput.equals(correct2) )
{
return false;
}else
{
System.out.println("Try again!");
}
}
}
Question is now solved, anyone interested why i needed this full code below:
import java.util.*;
public class CheckingInput
{
public static void main(String args[])
{
System.out.println("What is 1+1?");
boolean answer = validation("two", "three");
if(answer == true)
{
System.out.print("Correct!");
}else if(answer == false)
{
System.out.print("Wrong!");
}
}
public static boolean validation(String correct1, String correct2)
{
Scanner in = new Scanner(System.in);
boolean correctInput = false;
String userInput;
while (correctInput == false)
{
System.out.print("Type in " + correct1 + " or " + correct2 + ": ");
userInput = in.next();
if ( userInput.equals(correct1) )
{
correctInput = true;
return true;
}else if (userInput.equals(correct2))
{
correctInput = true;
return false;
}else
{
System.out.println("Try again!");
correctInput = false;
}
}
return false;// Doesn't really matter, loop will never reach here
}
I'm assuming the infinite loop is intentional, as you're awaiting a response from your user, so try the following:
public static boolean validation(String correct1, String correct2)
{
Scanner in = new Scanner(System.in);
String userInput;
while (true)
{
System.out.print("Type in " + correct1 + " or " + correct2);
userInput = in.next();
if ( userInput.equals(correct1) )
{
return true;
}
else if ( userInput.equals(correct2) )
{
return false;
}
else
{
System.out.println("Try again!");
}
}
return false; // Doesn't really matter, loop will never reach here
}
A return true; or return false statement is missing before the end of the function, in case the loop exits.

Boolean bug (FibonacciNumbers)

First of all I am not asking anyone to do anything just need a little help to fix this bug with boolean. I put false but the program stops. I got two parts to the program.
First part where i did the calculations:
class FibonacciNumbers {
FibonacciNumbers() {} //default constructor
public int fOf(int n) {
if (n == 0) //the base case
{
return 0;
} else if (n == 1) {
return 1;
} else {
return fOf(n - 1) + fOf(n - 2);
}
}
}
Second where the main method is:
import java.util.*;
public class FibonacciNumbersTesters {
public static void main(String[] args) {
FibonacciNumbers fNumbers = new FibonacciNumbers(); //creates new object
Scanner in = new Scanner(System.in);
String again;
String test;
boolean IsRepeat = true;
boolean isQuit;
try {
isQuit = false;
while (!isQuit) {
System.out.print("Enter the number you want to convert to Fibanocci('q' to quit): ");
int n = in.nextInt();
System.out.print("The Fibanocci number for " + n + " is: ");
n = fNumbers.fOf(n);
System.out.println(n);
System.out.print("Do you want to run again? (Y or N): ");
again = in.next();
if (again.equalsIgnoreCase("N")) {
System.out.println("Thank you! Please terminate the program by entering 'Q' or 'q' OR you can cotinue by entering anything else: ");
String toQuit = in.next();
if ((toQuit.charAt(0) == 'q') || (toQuit.charAt(0) == 'Q')) {
System.out.println("Good-bye!");
isQuit = true;
}
} else {
IsRepeat = true;
}
}
} catch (InputMismatchException ex) {
test = in.nextLine();
if ((test.charAt(0) == 'q') || (test.charAt(0) == 'Q')) {
System.out.println("Good-bye!");
isQuit = true;
} else {
System.out.println("Invalid input!");
System.out.println("Try again! ");
isQuit = false;
}
}
}
}
This part where i put isQuit = false; at the end it just stops. I want it to continue.
Try putting your try catch statement inside of your while loop.

Categories