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;
}
Related
I've copied part of the instructions below, and I can code pretty much every part on its own, but getting the control flow together is giving me massive doubts about my ability.
One of my biggest problems is the int gameChanger. Im supposed to immediately verify if it is a integer or not, and loop back if its not. But then Im also supposed to check to see if thebuser ever types "exit". But the input variable for my scanner instance is an integer... So Im stumped. I can use a try catch to check the missmatchexception once the input is being read in, but that doesnt solve the exit issue nor am I able to come up with solid logic to get the try catch to loop back if it indeed isnt an integer. Im thinking a do while loop but I havent gotten it to work.
Instructions:
You can whether the input is a number before attempting to consume it.
int num;
while (true) {
if (scanner.hasNextInt()) {
num = scanner.nextInt();
break;
} else {
// read whatever is there instead.
String line = scanner.nextLine();
if (line.equals("exit"))
System.exit(0);
System.out.println("Please enter a number");
}
}
System.out.println("Number entered " + num);
This gets the job done. Try it out.
import java.util.Scanner;
public class MyCode
{
public static void main(String[] args)
{
String gameInput = ".";
int gameNumber = 0;
boolean inputLoop = true;
Scanner input = new Scanner(System.in);
while(inputLoop == true)
{
try
{
System.out.print("Please enter a valid game number: ");
gameInput = input.next();
if(gameInput.equals("exit"))
{
System.out.println("Program will now end. Goodbye.");
inputLoop = false;
input.close();
}
gameNumber = Integer.parseInt(gameInput);
if(gameNumber >= 20001 && gameNumber <= 21230)
{
System.out.println("You have inputted a valid game number.");
inputLoop = false;
input.close();
}
}
catch(NumberFormatException e)
{
if(!gameInput.equals("exit"))
{
System.err.println("Invalid game number. Please try again.");
}
}
}
}
}
public static int atk = 5;
public static void main(String[] args){
System.out.println("DUNGEONS AND DWAGONS");
Scanner scan = new Scanner(System.in);
help();
String input = scan.next();
// when someone types help first it works, but when they type stats after it shows what would happen if someone typed help.
while(true){
if (input.equals("help")){
help();
scan.next();
}else if(input.equals("stats")){
stats();
scan.next();
}
}
}
static void help() {
System.out.println("type n,s,e,w to move in a direction");
System.out.println("type stats to see your stats");
System.out.println("type look and then a direction n,e,s,w see the sights");
System.out.println("if you wish to see this again type help");
}
static void stats(){
System.out.println("Health " + health);
System.out.println("Armour " + armour);
System.out.println("Attack " + atk);
}
}
// I have tried every thing and if you type anything after the first thig typed it will execute the same thing over and over again.
Just move scan.next outside of if/else and assign it to input variable like:
if (..) {
help();
} else {
stats();
}
input = scan.next();
And expect exit so you can come out of while loop and terminate your program gracefully.
My loop never stops, I can't seem to understand what is wrong. I'm doing
a project for my class and I'm new to loops so kind of confused. Please tell me how
to resolve this issue.
import java.util.Scanner;
public class FracCalc {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in); {
boolean Quit = true;
System.out.println("Welcome to FracCalc");
System.out.println("Type expressions with fractions, and I will evaluate them");
String answer = scan.nextLine();
while (Quit = true) {
if (answer.equals("Quit")){
System.out.println("Thanks forr running FracCalc!");
break;
} else {
System.out.println("I can only process 'Quit' for now");
}
}
}
}
}
Quit = true will assign true to Quit, and return true. Thus, you're doing while (true), a canonical infinite loop. And even if you were testing Quit == true (note double equality sign), you never assign it to false, as Izcd remarks. You could break out with your if, but answer is only assigned once, outside the loop.
Put String answer = scan.nextLine(); inside the loop.
Try the following:
import java.util.Scanner;
public class FracCalc {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to FracCalc");
System.out.println("Type expressions with fractions, and I will evaluate them");
String answer = scan.nextLine();
do {
if (answer.equals("Quit")) {
System.out.println("Thanks forr running FracCalc!");
break;
} else {
System.out.println("I can only process 'Quit' for now");
}
answer = scan.nextLine();
} while (true);
}
}
Can someone help me make this code neater. I would rather use parse int than a buffer reader. I want my code to loop until the user inputs a number. I couldn't figure out how to do this without the code printing out the same statement twice.
public void setAge()
{
try {
age = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
System.out.println("What is your age?");
this.setAge();
}
}
Alright, my question is unclear. I am unsure of how to handle the error that a scanner throws when you don't input an integer. How do I handle this? I found "NumberFormatException" in a different post, but I am unsure of what this does. Can anyone help me with this, or is my question still unclear?
Try this:
import java.util.InputMismatchException;
import java.util.Scanner;
public class TestScanner {
public static void main(String[] args) {
Scanner scanner = null;
int age = -1;
do {
try {
scanner = new Scanner(System.in);
System.out.println("What is your age?");
age = scanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("Please enter a number!");
}
} while (age == -1);
System.out.println("You are " + age + " years old.");
if (scanner != null)
scanner.close();
}
}
I get this output (the first time I enter abc instead of a number to make it retry):
What is your age?
abc
Please enter a number!
What is your age?
35
You are 35 years old.
Have fun!
Use scan.nextInt(); instead of scan.nextLine();
With this, you don't need to parse the line.
EDIT: Oops, i misread your question
Number Format Exception occurs in the java code when a programmer tries to convert a String into a number. The Number might be int,float or any java numeric values.
The conversions are done by the functions Integer.parseInt.Consider if you give the value of str is "saurabh", the function call will fail to compile because "saurabh" is not a legal string representation of an int value and NumberFormatException will occurs
You could use a scanner.
You'll need to;
import java.util.*;
static Scanner console = new Scanner(System.in);
You won't need the parse statement at all.
age = console.nextInt();
EDIT: Editing my answer after seeing your edit.
I would put the entire try in a do loop. Using a new boolean variable to control when you come out of it.
boolean excep;
do {
excep = false;
try {
age = console.nextInt();
}
catch (Exception exRef) {
System.out.println("Please input an integer");
console.nextLine();
excep = true;
}
} while (excep);
The console.nextLine() just clears a line so it doesnt re-read the last input. Sometimes it's needed.
Using this i don't receive any error notifications on the running of it.
Try this:
static boolean firstTime = true;
public static void main(String[] args) {
boolean firstTime = true;
setAge();
}
public static void setAge()
{
if(firstTime)
{
System.out.println("What is your age?");
firstTime = false;
}
Scanner scan = new Scanner(System.in);
try{
int age = scan.nextInt();
System.out.println(age);
}
catch(InputMismatchException e)
{
setAge();
}
}
if you want to print different messages you would have to do like:
import java.util.Scanner;
public class Numbers {
public static void main(String args[]) {
Numbers numbers = new Numbers();
numbers.setAge();
}
private boolean alrearyAsked = false;
private int age = 0;
static Scanner scan = new Scanner(System.in);
public void setAge()
{
try {
age = scan.nextInt();
} catch (NumberFormatException e) {
if (alrearyAsked) {
System.out.println("you typed a wrong age, please try again.");
}
else {
System.out.println("What is your age?");
}
this.setAge();
}
}
}
So I'm trying to use if-else statement dependant upon the user's input. It works when the user's input is only one word, however, multiple word inputs go unrecognized and triggers the else statement. How can i resolve this?
import java.util.Scanner;
public class MyFirstJavaClass {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner myScanner = new Scanner(System.in);
String answer;
System.out.println("Catch the tiger or run away?");
answer = myScanner.next();
if (answer.equals("Catch the tiger" )) {
System.out.println("You've been mauled by a tiger! What were you thinking?");
answer = myScanner.next();
} else {
System.out.println("run away");
}
}
}
Replace:
answer = myScanner.next();
With:
answer = myScanner.nextLine();
next will only read in the next value until it reaches a space or newline. You want to read in the full line before making the comparison
try this :
Scanner scanner = new Scanner(System.in);
int choice = 0;
while (scanner.hasNext()){
if (scanner.hasNextInt()){
choice = scanner.nextInt();
break;
} else {
scanner.next(); // Just discard this, not interested...
}
}
Reference :
Flush/Clear System.in (stdin) before reading
Try this
import java.util.Scanner;
public class MyFirstJavaClass {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner myScanner = new Scanner(System.in);
System.out.println("Catch the tiger or run away?");
if (myScanner.hasNext("Catch the tiger")) {
System.out.println("You've been mauled by a tiger! What were you thinking?");
} else {
System.out.println("run away");
}
}
}