I wanted to make an input which accepts numbers from 1 - 10 and prints the range.
I need to check if the input is an integer (check), check if the range is 0-10 (check), and if it's not any of those things, to ask the user again. So, a recursive method?
Currently I have this:
import java.util.Scanner;
import java.util.InputMismatchException;
public class FinalTest {
public static void main (String [] args) {
Scanner in = new Scanner(System.in);
int k = 0;
System.out.print("int - ");
try {
k = in.nextInt();
} catch (InputMismatchException e) {
System.out.println("ERR: Input");
System.exit(1);
}
if(k <= 10 && k > 0) {
for(int j=1; j <= k; j++) {
System.out.println(j);
}
} else {
System.out.println("ERR: Oob");
System.exit(1);
}
}
}
I would like to replace the "System.exit()" so that it re attempts to ask the user for input again.
calling main(); produces an error.
How do I correctly call the main method in this case?
Two choices here:
actually create a method and call that
simply use a loop
Loop could go like:
boolean askForInput = true;
while ( askForInput ) {
try {
k = in.nextInt();
askForInput = false;
} catch ...
print "not a number try again"
}
But beyond that: you still want to put this code into its own method. Not because that code should call itself, but for clarity reasons. Like:
public static int askForNumber(Scanner in) {
... code from above
return k;
}
And to answer your question: you do not want to use recursion here. You want to loop; and yes, recursion is one way to implement looping, but that is simply overkill given the requirement you want to implement here.
And for the record: when creating that helper method, you can actually simplify it to:
public static int askForNumber() {
while ( askForInput ) {
try ...
return in.nextInt();
} catch ...
print "not a number try again"
}
}
Beyond that: you typically use recursion for computational tasks, such as computing a factorial, or fibonacci number, ... see here for example.
for the part of the recursive method printing a range:
public void printAscending(int n) {
if (n > 0) {
printAscending(n - 1);
System.out.println(n);
}
}
I think using recursion is just too much for something that simple and would probably be more expensive. You can add a while loop around your scanning bit until the entered value is valid. I would also put the printing loop out of the while to not have to test a condition before printing since if you get out of the while loop, it means number if valid. You could test just the -1 value to exit process.
public class FinalTest
{
public static void main (String [] args)
{
Scanner in = new Scanner(System.in);
int k = 0;
do
{
System.out.print("int - ");
try
{
k = in.nextInt();
}
catch (InputMismatchException e)
{
System.out.println("ERR: Input");
System.exit(1);
}
}
while(!(k>0 && k<=10) && k!=-1);
if(k!=-1)
{
for(int j=1; j<=k; j++)
{
System.out.println(j);
}
}
else
{
System.out.println("Bye Bye.");
}
}
}
Okay, so what I personally do when I need to use recursion is I create a separate function/method for it. And when I need to restart the method, I just call it within itself. So it would be something like this:
private void recursiveMethod() {
// do stuff . . .
if (yourCondition) {
//continue to next piece of code
} else {
recursiveMethod();
}
}
But in big projects, try to stay away from recursion because if you mess up, it can
Related
What is the Java equivalent of the while/else in Python? Because it doesn't work in Java. The first chunk was my python code and the second portion is my attempt to translate it into Java. Edit: tring to replicate while-else
while temp.frontIsClear():
if temp.nextToABeeper():
temp.pickBeeper()
count += 1
temp.move()
else:
if temp.nextToABeeper():
temp.pickBeeper()
count += 1
print "The count is ", count
Java Attempt
Robot temp = new Robot();
int count = 0;
while (temp.frontIsClear())
{
if (temp.nextToABeeper())
{
temp.pickBeeper();
count += 1;
}
temp.move();
}
else
{
if (temp.nextToABeeper())
{
temp.pickBeeper();
count += 1;
}
}
print ("The count is ", count);
The closest Java equivalent is to explicitly keep track of whether you exited the loop with a break... but you don't actually have a break in your code, so using a while-else was pointless in the first place.
For Java folks (and Python folks) who don't know what Python's while-else does, an else clause on a while loop executes if the loop ends without a break. Another way to think about it is that it executes if the while condition is false, just like with an if statement.
A while-else that actually had a break:
while whatever():
if whatever_else():
break
do_stuff()
else:
finish_up()
could be translated to
boolean noBreak = true;
while (whatever()) {
if (whateverElse()) {
noBreak = false;
break;
}
doStuff();
}
if (noBreak) {
finishUp();
}
Just use one more if statement:
if (temp.nextToABeeper())
// pick beer
} else {
while (temp.frontIsClear()) { /* your code */ }
}
Or:
if (temp.frontIsClear())
while (temp.frontIsClear()) { /* your code */ }
} else if (temp.nextToABeeper()) {
// pick beer
}
If you look at the Java Backus–Naur form Grammar (Syntax Specification), else never follows a while.
Your solution needs to be modified accordingly. You can put the while in an else, that way you handle the if statement.
if temp.nextToBeeper() {
//handle
} else {
while(temp.frontIsClear()) {
//handle
}
}
Try this:
Robot temp = new Robot();
int count = 0;
if (temp.frontIsClear())
{
while (temp.frontIsClear())
{
if (temp.nextToABeeper())
{
temp.pickBeeper();
count += 1;
}
temp.move();
}
}
else if (temp.nextToABeeper())
{
temp.pickBeeper();
count += 1;
}
print ("The count is ", count);
In Java
if is a conditional statement .
But
while is loop that is iterate again an again and stop itself when falsecondition occurred .
I was recently trying to build a program that takes two inputs and checks whether they are equally represented in other bases(bases are up till 20). But i keep getting the index out of bounds exception at line number 28...what to do?
For example: 12(base 10) = 5(base 3) [both are represented as '12' in their respective bases.]
import java.util.Scanner;
import java.util.Arrays;
class Bases
{
public static void main()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter Two Numbers: ");
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println("Thank You for inputting the numbers!");
String basea[] = new String[20];
String baseb[] = new String[20];
int i=0 , j=0;
for( i=0;i<20;i++)
{
basea[i] = convert(a,i+1);
baseb[i] = convert(b,i+1);
}
for(i=0;i<=19;i++)
{
for(j=0;i<=19;j++)
{
if(basea[i].equals(baseb[j]))
{//this is where the exception keeps popping
break ;
}
}
}
if(i!=20){
if(i==0){
i=9;
System.out.println(a+"(base "+(i+1)+") ="+b+"(base "+(j+1)+")");
}
else
System.out.println(a+"(base "+(i+1)+") ="+b+"(base "+(j+1)+")");
}
else System.out.println("Numbers dont match at all till base 20!!");
}
private static String convert(int number,int base)
{
return Integer.toString(number,base);
}
}
for(j=0;i<=19;j++)
This above loop should be j <= 19
for(j=0;j<=19;j++)
for(i=0;i<=19;i++)
{
for(j=0;i<=19;j++)
{
if(basea[i].equals(baseb[j]))
{//this is where the exception keeps popping
break ;
}
}
}
You can see in this original snippet of code you had a typo
for(i=0;i<=19;i++)
{
for(j=0;i<=19;j++) <---- the middle parameter is 'i' instead of 'j'
{
Simply fix this by fixing your typo, and if you want to you can make it <20 for some added neatness.
for(i=0;i<20;i++)
{
for(j=0;j<20;j++)
{
I am trying to execute a program after taking user input from the console. [code block below]. However, I do not want to terminate after the program execution finishes. I want the console to always ask me the INITIAL_MESSAGE after the execution finishes. Effectively, after the execution of the program, I want the console to again ask me the INTIAL_MESSAGE so that I can again enter the inputs as I want and execute the program again.
I am actually calling the interactor() in this method, from the main method as the starting point.
Please tell me how do I achieve this
public class ConsoleInteraction {
/**
* #param args
*/
public static int numberOfJavaTrainees ;
public static int numberOfPHPTrainees ;
Barracks trainingBarrack = new Barracks();
public void interactor() throws IOException {
//reading capability from the consolemessages properties file
ResourceBundle bundle = ResourceBundle.getBundle("resources/consolemessages");
// Create a scanner so we can read the command-line input
Scanner scanner = new Scanner(System.in);
// Prompt for training or viewing camp
System.out.print(bundle.getString("INITIAL_MESSAGE"));
//Get the preference as an integer
int preference = scanner.nextInt();
//Show options based on preference
if(preference == 1)
{
//System.out.println("Whom do you want to train?\n 1.Java Guy \n 2.PHP Guy \n 3.Mix \n Enter You preference:");
System.out.print(bundle.getString("WHO_TO_TRAIN"));
int traineepreference = scanner.nextInt();
if (traineepreference == 1)
{
//System.out.println("How many Java guys you want to train ? : ");
System.out.print(bundle.getString("HOW_MANY_JAVA"));
numberOfJavaTrainees = scanner.nextInt();
trainingBarrack.trainTrainees(numberOfJavaTrainees, 0);
}
else if (traineepreference == 2)
{
//System.out.println("How many PHP guys you want to train ? : ");
System.out.print(bundle.getString("HOW_MANY_PHP"));
numberOfPHPTrainees = scanner.nextInt();
trainingBarrack.trainTrainees(0, numberOfPHPTrainees);
}
else if (traineepreference == 3)
{
System.out.print(bundle.getString("HOW_MANY_JAVA"));
numberOfJavaTrainees = scanner.nextInt();
System.out.print(bundle.getString("HOW_MANY_PHP"));
numberOfPHPTrainees = scanner.nextInt();
trainingBarrack.trainTrainees(numberOfJavaTrainees, numberOfPHPTrainees);
}
else
{
System.out.print(bundle.getString("ERROR_MESSAGE1"));
}
}
else if (preference == 2)
{
System.out.println("Showing Camp to You");
System.out.println("Java trained in Trainee Camp : "+ TraineeCamp.trainedJavaGuys);
System.out.println("PHP trained in Trainee Camp : "+ TraineeCamp.trainedPHPGuys);
}
else
{
System.out.print(bundle.getString("ERROR_MESSAGE2"));
}
scanner.close();
}
}
Consider these changes quickly drafted to your class. Might not compile. Might not work as you planned.
Some highlights of what I think you should change:
Use constants for the choice values. Makes your code way more better to read.
Initialize Bundle and Scanner outside of the method. Might be reused.
instead of coding lengthy parts of code inside of the if-else-if cascade, call methods there - angain increasing your readability a long way
public class ConsoleInteraction {
public static int numberOfJavaTrainees ;
public static int numberOfPHPTrainees ;
//Don't read that every time...
ResourceBundle bundle = ResourceBundle.getBundle("resources/consolemessages");
public static void main(String[] args) {
//Moving Scanner out of loop
try {
Scanner scanner = new Scanner(System.in);
ConsoleInteraction ci = new ConsoleInteraction();
//Loop until this returns false
while(ci.interactor(scanner)) {
System.out.println("=== Next iteration ===");
}
} catch (IOException e) {
e.printStackTrace();
}
}
//Constant values to make code readable
public final static int PREF_TRAINING = 1;
public final static int PREF_SHOW_CAMP = 2;
public final static int PREF_QUIT = 99;
public boolean interactor(Scanner scanner) throws IOException {
// Prompt for training or viewing camp
System.out.print(bundle.getString("INITIAL_MESSAGE"));
//Get the preference as an integer
int preference = scanner.nextInt();
//Show options based on preference.
if(preference == PREF_TRAINING) {
//LIKE YOU DID BEFORE OR calling method:
readTraining(scanner);
} else if (preference == PREF_SHOW_CAMP) {
//LIKE YOU DID BEFORE OR calling mathod:
showCamp();
} else if (preference == PREF_QUIT) {
//Last loop
return false;
} else {
System.out.print(bundle.getString("ERROR_MESSAGE2"));
}
//Next loop
return true;
}
}
I am new to Java. I am trying to create a Java Program that has the ability to retry itself when an exception occur in the program (which work fine). Now the problem I have now is in the for loop. In this code, when something went wrong in the for loop, the program itself will jump out of that loop and go to the catch method. After that if the retry is less than MAX_RETRIES, then the program will relaunch from the beginning. This is what I am struggling with. What I want is let say if there is an exception occur in the for loop when printing let say 5, I want the program to retry where the exception in the for loop occur not relaunch from the beginning. Are there ways to do it? I am struggling with this for a while and cannot seems to find a way to do it. Help and code for reference will be appreciated. This is the best way I can think of to simplify my code. In my real application, the for loop I have right now is to Iterate though a list of record from the database.
main.java
public class main {
private static int retryCounter = 1;
private static int MAX_RETRIES = 3;
public static void main(String[] args) {
int retry = 1;
try {
while (retry <= MAX_RETRIES) {
//method1
//stuff code
//more code
//method2
for (int i = 0; i < 11; i++) {
System.out.println("i");
}
}
System.out.println("-----Finish Process-----");
break;
} catch (Exception e) {
e.printlnStackTrace();
retry++;
if (retry == MAX_RETRIES) {
System.out.println("Program retried" + retry);
System.out.println("Program Terminated");
}
}
}
I think it solve your problem
public class main {
private static int retryCounter = 1;
private static int MAX_RETRIES = 3;
public static void main(String[] args) {
int retry = 1;
while (retry <= MAX_RETRIES) {
try {
//method1
//stuff code
//more code
//method2
int i=0;
while (i < 11) {
try {
System.out.println(i);
i++;
} catch (Exception e) {
e.printStackTrace();
i++;
if (i == MAX_RETRIES) {
System.out.println("Program retried" + retry);
System.out.println("Program Terminated");
}
}
}
retry++;
} catch (Exception e) {
e.printStackTrace();
retry++;
if (retry == MAX_RETRIES) {
System.out.println("Program retried" + retry);
System.out.println("Program Terminated");
}
}
}
System.out.println("-----Finish Process-----");
}
}
I have an idea that might help. I can't show any example code, but it might be possible to set up a flag/signal1 after you complete each step in executing the program. Then, when the program retries, it can automatically skip to that point in code where it last stopped.
1: I don't know what it's called in java
I am very close to finishing my task, but I can't figure out how to call findChange() correctly. My guess is that it needs to be in the main method. But when findChange(); call it, it asks for int, List<Integer>, List<Integer> so how do I do this "correctly" so to speak.
CODE
import java.io.*;
import java.util.*;
import java.lang.*;
public class homework5 {
public static int change;
public static void main(String[] args)
throws FileNotFoundException
{ //begin main
ArrayList<Integer> coinTypes = new ArrayList<Integer>();//array to store
//coin types
Integer i;
File f = new File (args[0]);
Scanner input = new Scanner(f); //initialize scanner
input.nextLine();
while(input.hasNextInt()) {
i = input.nextInt();
coinTypes.add(i);
}
change = coinTypes.get(coinTypes.size()-1); //this will add all ints
coinTypes.remove(coinTypes.size()-1);
System.out.println("Found change"); //used for debugging
System.out.println("Change: " + change);
//findChange(); ideal spot to call the method
//System.out.println(coinTypes);
}
boolean findChange(int change, List<Integer> coinTypes,
List<Integer> answerCoins)
{ //contains means of
//finding the change solutions
if(change == 0) {
return true; //a solution
}
if(change < 0) {
return false; //if negative it can't be a solution
} else {
for(Integer coin : coinTypes) {
if(findChange(change - coin, coinTypes, answerCoins)){
answerCoins.add(coin); //if it works out add it to the
return true; //solution List
}
}
}
List<Integer> answer = new ArrayList<Integer>();
boolean canFindChange = findChange(change, coinTypes, answer);
if(canFindChange) { //if there is a solution, print it
System.out.println(answer);
} else { System.out.println("No change found");
}
return false; //else return false
}
}
This program calculates all the different ways to show change for a certain amount of money ie: 143 ($1.43). All I gotta do is call findChange() to main and it should work, what am I missing?
EDIT I just realized I didn't specify the method call I need help with I apologize for any unclearness
INPUT FILE
// Coins available in the USA, given in cents. Change for $0.09?
1 5
9
CURRENT OUTPUT
Change: 9
WANT
Change: 9
['solutions to all possible combinations to make $0.09']