Java help regarding loops - java

I'm basically new to this programming stuff. There is a part of the code that I couldn't understand and don't know how to do. Probably what our instructor didn't discuss. What I want to happen is that when I input "Y", it would retry the whole program. If I input "N", it would exit. Here is the code
import java.io.*;
import javax.swing.JOptionPane;
public class Doge {
public static void main(String[] args)
{
int start = 0;
int end = 0;
int step = 0;
String input = "";
BufferedReader in = new BufferedReader (
new InputStreamReader (System.in));
try
{
System.out.println("Input starting number: ");
input = in.readLine();
start = Integer.parseInt(input);
System.out.println("Input ending number: ");
input = in.readLine();
end = Integer.parseInt(input);
System.out.println("Input step number: ");
input = in.readLine();
step = Integer.parseInt(input);
}
catch (IOException e)
{
System.out.println("Error");
}
System.out.println("");
if (start>=end)
{
System.out.println("Starting number should be lesser than the ending number.");
}
while (start<=end)
{
System.out.println(start);
start = start+step;
}
String result = "";
char y = 'Y';
char n = 'N';
BufferedReader it = new BufferedReader (
new InputStreamReader(System.in));
try
{
System.out.print("Do you want to retry (Y/N)? ");
result = it.readLine();
}
catch(IOException e)
{
System.out.println("Error");
}
start = 0;
end = 0;
step = 0;
input = "";
BufferedReader in2 = new BufferedReader (
new InputStreamReader (System.in));
while ("y".equals(result))
{
try
{
System.out.println("Input starting number: ");
input = in2.readLine();
start = Integer.parseInt(input);
System.out.println("Input ending number: ");
input = in2.readLine();
end = Integer.parseInt(input);
System.out.println("Input step number: ");
input = in2.readLine();
step = Integer.parseInt(input);
}
catch (IOException e)
{
System.out.println("Error");
}
System.out.println("");
while (start<=end)
{
System.out.println(start);
start = start+step;
}
}
if ("n".equals(result))
System.exit(0);
}
}
I'm quite confused. I was thinking of writing the same codes but the input starting number line loops after placing a value for the step number.

Understand do..while loop in Java....here
Problems I found in your code
BufferedReader no reuse
Your retry result only check once but not everytime it finsh one loop of process
String compare with "y" but not the char y = 'Y'; you defined. char y = 'Y'; should be String y = "Y"; (The comparison with .equals() is case-sensitive. So if you want include 'y' into your consideration, you can use .equalsIgnoreCase()
{ and } not pairing well to display statement in same scope (ease reading)
I rewrite your code, hope can help you understand more
import java.io.*;
import javax.swing.JOptionPane;
public class Doge {
public static void main(String[] args)
{
int start = 0;
int end = 0;
int step = 0;
String input = "";
String result = "";
boolean invalidInput = false;
//String y = "Y";
//String n = "N";
//reuse same BufferedReader
BufferedReader in2 = new BufferedReader (
new InputStreamReader (System.in));
//use do while to have statement run once then only check retry
do
{
try
{
do
{
System.out.println("Input starting number: ");
input = in2.readLine();
start = Integer.parseInt(input);
System.out.println("Input ending number: ");
input = in2.readLine();
end = Integer.parseInt(input);
if (start >= end)
{
System.out.println("Starting number should be lesser than the ending number.");
invalidInput = true;
}
else
invalidInput = false;
} while (invalidInput); //loop as long as the start >= end
System.out.println("Input step number: ");
input = in2.readLine();
step = Integer.parseInt(input);
}
catch (IOException e)
{
System.out.println("Error");
}
System.out.println("");
while (start<=end)
{
System.out.println(start);
start = start+step;
}
try
{
System.out.print("Do you want to retry (Y/N)? ");
result = in2.readLine();
//it will exit if answer is "N" or "n"
//check whether result is String n (ignore case)
//if (n.equalsIgnoreCase(result))
//only accept "n"
if ("n".equals(result))
System.exit(0);
}
catch(IOException e)
{
System.out.println("Error");
}
//} while (y.equalsIgnoreCase(result)); //loop if "y" or "Y"
} while ("y".equals(result));
//if here have other process, then your result that is neither 'Y' nor 'N' will run here
}
}
After run, I only know .equals() and .equalsIgnoreCase() can only be used on String but not char

Related

Java Conditional Statement Exercises: Input numbers from keyboard and find their sum and use input "EXIT "to break the loop

I'm trying to create a loop by entering the number to be added and then blocking the loop with a "exit" input from the user..but it's not working properly.
import java.util.Scanner;
public class main {
public static void main(String[] args)
{
int i,n=0,s=0;
double avg;
{
System.out.println("Input the numbers : ");
}
for (i=0;i<100;i++)
{
String input = new java.util.Scanner(System.in).nextLine ();
if(input.equals("exit")){
break;
}
Scanner in = new Scanner(System.in);
n = in.nextInt();
s +=n;
}
System.out.println("The sum of numbers is : " +s);
}
}
You have a couple of problems. One (minor) is that you are creating two scanners. Another (medium) is that your loop is set up to only go up to 100 - this is a magic number, and there's no reason to put in this artificial constraint. But your biggest problem is that you are ignoring the first entry in the loop if it is a number and not 'exit'
{
int i,n=0,s=0;
double avg;
boolean adding = true;
System.out.println("Input the numbers : ");
Scanner sc = new java.util.Scanner(System.in);
while(adding)
{
String input = sc.nextLine ();
if(input.equals("exit")){ // should proably be "EXIT" or equalsIgnoreCase
adding = false;
} else {
try {
int val = Integer.parseInt(input);
s += val;
} catch (NumberFormatException nfe) {
System.err.println ("expecting EXIT or an integer");
}
}
}
System.out.println("The sum of numbers is : " +s);
}
After this line your console does not have any next line or entry to read.
String input = new java.util.Scanner(System.in).nextLine ();

How to check that the entered input is an integer or not in java?

How to check in this code that the entered input is integer or not if not then ignore the non-integer values and display the rest numbers.
I have done the full coding but for checking the input is integer or not and then printing the value. How should I do it?
import java.util.Scanner;
class ques2
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int i,j;
System.out.print("how many number you want to enter= ");
i=sc.nextInt();
int input[]=new int[i];
System.out.println("Numbers should be great then 3");
for(j=0;j<i;j++)
{
input[j]=sc.nextInt();
}
System.out.println("Number entered are:");
for(j=0;j < i;j++)
{
System.out.println(input[j]);
}
System.out.println("Odd numbers are:");
for(j=0;j < i;j++)
{
if(input[j] % 2 != 0)
{
System.out.println(input[j]);
}
}
System.out.println("Palindrome numbers are:");
for(j=0;j < i;j++)
{
int rev=0,n,num;
n=input[j];
while(input[j] > 0)
{
num=input[j] % 10;
rev=num+(rev*10);
input[j]=input[j]/10;
}
if(n == rev)
{
System.out.println(n);
}
}
}
}
You could take a helper function:
public static boolean checkMe(String s) {
boolean amIValid = false;
try {
Integer.parseInt(s);
// s is a valid integer!
amIValid = true;
} catch (NumberFormatException e) {
//not an integer but you could continue with the rest numbers
}
return invalid;
}
You can check it by comparing the ASCII value whether it lies between 91 to 100.
If yes then it will be an Integer.
You can try to use String in lieu of int. Then, you can go ahead with again int using Integer.parseInt(x) because it's already been verified as being valid integer after do-while
String num;
String regex = "[0-9]+"; // to check the string only is made up of digits
Scanner input = new Scanner(System.in);
do {
System.out.println("Please input an integer");
num = input.next();
} while (!num.matches(regex));
int validNumber = Integer.parseInt(num);
/* .
.
. *\
You're already using sc.nextIn() which internally perform a regex-check as in #snr's post and a Integer.parseInt as in charly1212's post.
The only thing you should add is wrap it in a
try {
int i = sc.nextInt();
} catch(InputMismatchException e) {
//skip or repeat?
}
To deal with all cases, where the input is not an int (which includes values > Integer.MAX_VALUE and < Integer.MIN_VALUE)
The solution could look like this method, encapsulating all the input reading
private static int[] readNumbers() {
Scanner sc = new Scanner(System.in);
int i = -1;
while(i < 0){
try {
System.out.print("how many number you want to enter? ");
i=sc.nextInt();
} catch (InputMismatchException e){
System.out.println(sc.next() + " is not a number, try again");
}
}
List<Integer> numbers = new ArrayList<>();
System.out.println("Numbers should be greater then 3");
for(int j = 0; j < i; j++){
try {
numbers.add(sc.nextInt());
} catch (InputMismatchException e){
System.out.println("Skipping input " + sc.next());
}
}
return numbers.stream().mapToInt(Integer::intValue).toArray();
}
...
int input[] = readNumbers();
Please not, that the exception blocks invoke sc.next() to read the current line (which is not integer) and proceed with the next line (the new input), otherwise the scanner would not proceed its position.

Why is my try and catch stuck in a loop?

I want the user to enter integers into an array. I have this loop I wrote which has a try and catch in it, in case a user inserts a non integer. There's a boolean variable which keeps the loop going if is true. This way the user will be prompted and prompted again.
Except, when I run it, it gets stuck in a loop where it repeats "Please enter # " and "An Integer is required" without letting the user input a new number. I reset that number if an exception is caught. I don't understand.
import java.util.*;
public class herp
{
//The main accesses the methods and uses them.
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Hello and welcome!\n");
System.out.print("This program stores values into an array"+" and prints them.\n");
System.out.println("Please enter how many numbers would like to store:\n");
int arraysize = scan.nextInt();
int[] mainarray = new int[arraysize+1];
int checkint = 0;
boolean notint = true;
int prompt = 1;
while (prompt < mainarray.length)
{
// Not into will turn true and keep the loop going if the user puts in a
// non integer. But why is it not asking the user to put it a new checkint?
while(notint)
{
try
{
notint = false;
System.out.println("Please enter #"+ prompt);
checkint = scan.nextInt();
}
catch(Exception ex)
{
System.out.println("An integer is required." +
"\n Input an integer please");
notint = true;
checkint = 1;
//See, here it returns true and checkint is reset.
}
}
mainarray[prompt] = checkint;
System.out.println("Number has been added\n");
prompt++;
notint = true;
}
}
}
Once the scanner has thrown an InputMismatchException it cannot continue to be used. If your input is not reliable, instead of using scanner.nextInt() use scanner.next() to obtain a String then convert the string to an int.
Replace:
checkint = scan.nextInt();
With:
String s = scan.next();
checkint = Integer.parseInt(s);
I have corrected it like below. I don't rely on exception, but check if the next Scanner input is int (using hasNextInt()). If not int, just consume Scanner token and wait for the next user input.
Looks like it is working, apart from 0 being inserted as a first array element, because you started indexing prompt from 1.
public class Herp {
//The main accesses the methods and uses them.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Hello and welcome!\n");
System.out.print("This program stores values into an array" + " and prints them.\n");
System.out.println("Please enter how many numbers would like to store:\n");
int arraysize = scan.nextInt();
int[] mainarray = new int[arraysize + 1];
int checkint = 0;
boolean notint = true;
int prompt = 1;
while (prompt < mainarray.length) {
while (notint) {
notint = false;
System.out.println("Please enter #" + prompt);
// check if int waits for us in Scanner
if (scan.hasNextInt()) {
checkint = scan.nextInt();
} else {
// if not, consume Scanner token
scan.next();
System.out.println("An integer is required."
+ "\n Input an integer please");
notint = true;
}
}
mainarray[prompt] = checkint;
System.out.println("Number has been added\n");
prompt++;
notint = true;
}
for (int i : mainarray) {
System.out.print(i + " ");
}
}
}

How to loop user input until an integer is inputted?

I'm new to Java and I wanted to keep on asking for user input until the user enters an integer, so that there's no InputMismatchException. I've tried this code, but I still get the exception when I enter a non-integer value.
int getInt(String prompt){
System.out.print(prompt);
Scanner sc = new Scanner(System.in);
while(!sc.hasNextInt()){
System.out.println("Enter a whole number.");
sc.nextInt();
}
return sc.nextInt();
}
Thanks for your time!
Take the input using next instead of nextInt. Put a try catch to parse the input using parseInt method. If parsing is successful break the while loop, otherwise continue.
Try this:
System.out.print("input");
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter a whole number.");
String input = sc.next();
int intInputValue = 0;
try {
intInputValue = Integer.parseInt(input);
System.out.println("Correct input, exit");
break;
} catch (NumberFormatException ne) {
System.out.println("Input is not a number, continue");
}
}
Shorter solution. Just take input in sc.next()
public int getInt(String prompt) {
Scanner sc = new Scanner(System.in);
System.out.print(prompt);
while (!sc.hasNextInt()) {
System.out.println("Enter a whole number");
sc.next();
}
return sc.nextInt();
}
Working on Juned's code, I was able to make it shorter.
int getInt(String prompt) {
System.out.print(prompt);
while(true){
try {
return Integer.parseInt(new Scanner(System.in).next());
} catch(NumberFormatException ne) {
System.out.print("That's not a whole number.\n"+prompt);
}
}
}
Keep gently scanning while you still have input, and check if it's indeed integer, as you need:
String s = "This is not yet number 10";
// create a new scanner
// with the specified String Object
Scanner scanner = new Scanner(s);
while (scanner.hasNext()) {
// if the next is a Int,
// print found and the Int
if (scanner.hasNextInt()) {
System.out.println("Found Int value :"
+ scanner.nextInt());
}
// if no Int is found,
// print "Not Found:" and the token
else {
System.out.println("Not found Int value :"
+ scanner.next());
}
}
scanner.close();
As an alternative, if it is just a single digit integer [0-9], then you can check its ASCII code. It should be between 48-57 to be an integer.
Building up on Juned's code, you can replace try block with an if condition:
System.out.print("input");
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter a whole number.");
String input = sc.next();
int intInputValue = 0;
if(input.charAt(0) >= 48 && input.charAt(0) <= 57){
System.out.println("Correct input, exit");
break;
}
System.out.println("Input is not a number, continue");
}

Handling Exceptions in Java - How to give user another chance?

Hey guys so i've been trying to answer this question for hours:
Write a program that asks the user to input a set of floating-point values. When the
user enters a value that is not a number, give the user a second chance to enter the
value. After two chances, quit reading input. Add all correctly specified values and
print the sum when the user is done entering data. Use exception handling to detect
improper inputs.
I've tried a few different things but i always have the same problem. Once something that isn't a number is given as input, the program outputs the message prompting for another input however the chance is not given, that is to say after 1 incorrect input it prints that message and jumps straight to printing the sum. The best i could do is below i'm just not sure how to approach this problem. Any help is greatly appreciated.
import java.util.Scanner;
import java.util.InputMismatchException;
public class q6{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
boolean firstChance = true;
boolean secondChance = true;
double sum = 0;
while (secondChance){
try{
while (firstChance){
try{
System.out.print("Please enter a number: ");
double input = in.nextDouble();
sum = sum + input;
}
catch (InputMismatchException ex){
firstChance = false;
}
System.out.print("Please enter a number to continue or something else to terminate: ");
double input = in.nextDouble();
sum = sum + input;
firstChance = true;
}
}
catch (InputMismatchException e){
secondChance = false;
}
}
System.out.print("The sum of the entered values is " + sum);
}
}
i'm just not sure how to approach this problem
Pseudocode could be as follows:
BEGIN
MAX_INPUT = 2;
i = 0;
WHILE i < MAX_INPUT
TRY
num = GET_NUM();
CATCH
continue;
FINALLY
i++
END WHILE
END
Since the parsing of input to double is not successful, the scanner does not go past the given input. From javadoc Scanner
Scans the next token of the input as a double. This method will throw
InputMismatchException if the next token cannot be translated into a
valid double value. If the translation is successful, the scanner
advances past the input that matched.
Since the translation is not successful, it does not advance. So, in the catch block you could call in.next() to skip the token.
You could use an integer counter instead of the boolean variables firstChance and secondChance and do something like:
int attempts = 0;
while(attempts < 2) {
try {
//Get user input - possible exception point
//Print sum
} catch(InputMismatchException e) {
attempts++;
//Continue?
}
}
import java.util.*;
public class q6 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double inputNumber, sum = 0.0;
int correctCount = 0, wrongCount = 0;
while(wrongCount <=1) {
System.out.println("Please enter a numeric floating value:");
try {
inputNumber = in.nextDouble();
correctCount++;
sum += inputNumber;
if(correctCount >= 2)
break;
} catch(InputMismatchException e) {
wrongCount++;
in = new Scanner(System.in);
continue;
}
}
System.out.println(sum);
}
}
You need to break your while loop when you encounter a "bad" input. Then, you'll need to set firstChance to true again, so you can access the second while, you also will need a counter that counts the number of the attempts (I named it chances):
int chances = 0;
while (secondChance){
firstChance = true;
try{
while (firstChance){
try{
System.out.print("Please enter a number: ");
double input = in.nextDouble();
sum = sum + input;
}
catch (InputMismatchException ex){
chances ++;
in = new Scanner(System.in);
firstChance = false;
}
if(!firstChance && chances < 2)
break;
if(chances >= 2) {
System.out.print("Please enter a number to continue or something else to terminate: ");
double input = in.nextDouble();
sum = sum + input;
firstChance = true;
}
}
}
catch (InputMismatchException e){
secondChance = false;
}
}
As stated in my comment, in order to not deal with Scanner wrong read, it would be better to use Scanner#nextLine() and read the data as String, then try to parse it as double using Double#parseDouble(String) since this method already throws NumberFormatException and you can handle this error. Also, it would be better that your code could handle more than 1 request (if your teacher or somebody else asks to do this):
final int REQUEST_TIMES = 2;
double sum = 0;
for(int i = 1; i <= REQUEST_TIMES; i++) {
while (true) {
try {
if (i < REQUEST_TIMES) {
System.out.print("Please enter a number: ");
} else {
System.out.print("Please enter a number to continue or something else to terminate: ");
}
String stringInput = in.nextLine();
double input = Double.parseDouble(stringInput);
sum += input;
} catch (NumberFormatException nfe) {
System.out.println("You haven't entered a valid number.");
break;
}
}
}
The logic is to read the input once, if it is correct then display the sum, else read the input again and display the sum if the input is correct.
public class q6 {
static int trial = 0;
public static void main(String[] args) {
double sum = 0;
while (trial <= 2) {
Scanner in = new Scanner(System.in);
try {
trial++;
System.out.print("Please enter a number: ");
double input = in.nextDouble();
sum = sum + input;
trial=3;
} catch (InputMismatchException ex) {
trial++;
if (trial == 4){
System.out.println("You have entered wrong values twice");
}
}
}
if (trial <= 3){
System.out.print("The sum of the entered values is " + sum);
}
}
The above program is just a rough idea, you can improve this to adapt to your need.

Categories