Java, How to break a loop when input is empty? [duplicate] - java

This question already has answers here:
How to test for blank line with Java Scanner?
(5 answers)
Closed 3 years ago.
The goal of this is to let the user enter a number per line and when the user no longer wish to continue they should be able to enter a empty line and when that happens the program should you give you a message with the largest number.
Problem is I can't make the loop break with an empty line. I'm not sure how to. I've checked other questions for a solution but I couldn't find anything that helped. I also can't assign scan.hasNextInt() == null....
I'm sure there is a quick and logical solution to this that I'm not thinking of.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number and press [Enter] per line, when you no longer wish to continue press [Enter] with no input.(empty line)");
int x = 0;
while(scan.hasNextInt()){
int n = scan.nextInt();
if (n > x){
x = n;
}
}
System.out.println("Largets number entered: " + x);
}
}

This should solve your problem:
import java.util.Scanner;
public class StackOverflow {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number and press [Enter] per line, when you no longer wish to continue press [Enter] with no input.(empty line)");
int x = 0;
try {
while(!scan.nextLine().isEmpty()){
int num = Integer.parseInt(scan.nextLine());
if(num > x) {
x = num;
}
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
System.out.println("Largest number entered: " + x);
scan.close();
}
}

import java.util.*;
public class main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number and press [Enter] per line, when you no longer wish to continue press [Enter] with no input.");
String str = scanner.nextLine();
int x = 0;
try {
while(!str.isEmpty()){
int number = Integer.parseInt(str);
if (number > x){
x = number;
}
str = scanner.nextLine();
}
}
catch (NumberFormatException e) {
System.out.println("There was an exception. You entered a data type other than Integer");
}
System.out.println("Largets number entered: " + x);
}
}

Related

Why do I have to put an integer twice for my Scanner input to work?

I'm trying to make a simple program where you can put integers in, and it will tell you if it increased or decreased from the previous integer input. But when I run the code, I have to put an integer value twice, but I only want it put once.
The input and output should look like (numbers typed by me, words output by the program):
Starting...
5
Increasing
4
Decreasing
6
Increasing
etc. etc.
But instead it looks like:
Starting...
5
5
Increasing
Input Number:
1
2
Not Increasing
etc. etc.
This is my code:
import java.util.Scanner;
public class Prob1 {
public static void main(String[] args) {
System.out.println("Starting...");
int input;
int previousInput = 0;
Scanner scan = new Scanner(System.in);
while (!(scan.nextInt() <= 0)) {
input = scan.nextInt();
if (input > previousInput) {
System.out.println("Increasing");
previousInput = input;
} else {
System.out.println("Not Increasing");
previousInput = input;
}
System.out.println("Input Number:");
}
scan.close();
}
}
Why does this problem occur, and how can I fix it?
The loop behavior you are describing is:
read a numeric input value
do something with it (print a message)
if the loop value meets a condition (input is 0 or less), exit the loop
otherwise, repeat
Here's a "do-while" loop that reads like those steps above:
Scanner scan = new Scanner(System.in);
int input;
do {
input = scan.nextInt();
System.out.println("input: " + input);
} while (input > 0);
System.out.println("done");
And here's input+output, first entering "1", then entering "0":
1
input: 1
0
input: 0
done
while (!(scan.nextInt() <= 0)) { takes an int and then input = scan.nextInt(); takes another one. You need to change the while loop to use input.
modified based on your code
public static void main(String[] args) {
System.out.println("Starting...");
int input;
int previousInput = 0;
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Input Number:");
input = scan.nextInt();
if (input <= 0) {
System.out.println("app shut down");
break;
}
if (input > previousInput) {
System.out.println("Increasing");
} else {
System.out.println("Not Increasing");
}
previousInput = input;
}
scan.close();
}

how to loop, to ask user input for this Java program?

at this program once the exception is caught, the program displays the catch message and program terminates successfully by itself (I need to run the program again manually if want to ask the user input). I dont want the program to finish but automatically it should ask the user to enter a valid number and performs the functions from the beginning, how to write for this?
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
System.out.println("Enter a Whole Number to divide: ");
int x = sc.nextInt();
System.out.println("Enter a Whole number to divide by: ");
int y = sc.nextInt();
int z = x / y;
System.out.println("Result is: " + z);
}
catch (Exception e) {
System.out.println("Input a valid number");
}
finally{
sc.close();
}
}
}
Output
Enter a Whole Number to divide:
5
Enter a Whole number to divide by:
a
Input a valid number
Process finished with exit code 0
There are some issues with nextInt that you need to be careful about, You can check out this link: Scanner is skipping nextLine() after using next() or nextFoo()?.
For your program, use a while loop, and you need to be aware of Y could be 0, which would cause an ArithmeticException.
while (true) {
try {
System.out.println("Enter a Whole Number to divide: ");
// use nextLine instead of nextInt
int x = Integer.parseInt(sc.nextLine());
System.out.println("Enter a Whole number to divide by: ");
int y = Integer.parseInt(sc.nextLine());
if (y == 0) {
System.out.println("divisor can not be 0");
continue;
}
double z = ((double) x) / y
System.out.println("Result is: " + z);
break;
}
catch (Exception e) {
System.out.println("Input a valid number");
}
}
sc.close();

InputMismatchException help, how to override?

So, I've been stuck on this problem for a while and do not understand why my code is not working. I'm trying to teach myself Java and looking at conditionals and loops right now. So the program basically is just trying to read in an integer (int num), but if anything besides an int is entered have it ask for correct input and give a message describing what has been entered. I hope that makes sense. I'm not entirely sure if this is correct but I'm also very new to this and have been struggling to figure out what I'm missing.
Here's the code:
import java.util.Scanner;
public class LoopPrac{
public static void main (String [] args){
Scanner scan = new Scanner(System.in);
int num;
boolean bool = false;
System.out.println("Enter an Integer: ");
num = scan.nextInt();
scan.nextLine();
while(bool = false){
System.out.println("Enter an Integer: ");
num = scan.nextInt();
scan.nextLine();
if(scan.hasNextDouble()){
System.out.println("Error: Index is Double not Integer.");
}
if(scan.hasNext()){
System.out.println("Error: Index is String not Integer.");
}
if(scan.hasNextInt()){
bool = true;
}
}
System.out.println(num);
}
}
Your exception InputMismatchException is because you ask the scanner to scan the next integer scan.nextInt() but it found double or string or something else so it throws an exception that this input is not a integer.
So you can fix your code by first ask the scanner is next input is integer or not scan.hasNextInt(), it it int scan it, else check if it double or any type to print error message
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter an Integer: ");
if (scan.hasNextInt()) {
int Index = scan.nextInt();
System.out.println("Index = " + Index);
}
else if (scan.hasNextDouble()) {
System.out.println("Error: Index is Double not Integer.");
}
else {
System.out.println("Error: Index is not Integer.");
}
}

Strict integer-only if/then loops

Using Java to compile a code that takes in any input, from strings to doubles, floats, integers, etc., but can only process based on integers. If it receives a double, float, or a string, it will just produce a message prompting the user to try again. I'm not sure exactly how to get this rolling, so here's my current code.
import java.util.Scanner;
public class Sand
{
public static void main(String[] args)
{
int firstInt, secondInt, thirdInt;
Scanner keyboard = new Scanner(System.in);
System.out.println("Hi. I'm going to be asking you for three integers in just a moment.");
System.out.println("An integer is defined as a WHOLE number that's not a fraction or decimal.");
System.out.println("I swear to you, I will go off if you put in a non-whole number...");
System.out.println("Okay go ahead and type in the first of the three integers:");
if (keyboard.hasNextInt())
{
firstInt = keyboard.nextInt();
System.out.println("Red.");
System.out.println("So the first integer is " + firstInt);
System.out.println("Okay go ahead and type in the second of the three integers: ");
if (keyboard.hasNextInt())
{
secondInt = keyboard.nextInt();
System.out.println("Green.");
System.out.println("So the first and second integers are " + firstInt + " and " + secondInt);
}
else
{
System.out.println("Orange.");
System.out.println("Please try again.");
}
}
else
{
System.out.println("Blue.");
System.out.println("Please try again.");
}
}
}
I have orange and blue representing times in which there are some input errors, but it's not complete. I'm not sure how to approach this, be it a while loop or a for loop or a try/catch. I'm new when it comes to learning Java so some #notes would be helpful along the way. The code is to designed to read three numbers that are integers from the user in a string. That's straightforward, but analyzing the input is where I'm struggling.
This is not meant to answer your question totally but to point you in the right direction. There should be enough here to help you figure out what else is needed for your program.
import java.util.Scanner;
public class Sandbox {
// arguments are passed using the text field below this editor
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int num = 0;
System.out.println("enter an integer");
while (true) { //keep prompting the user until they comply
try {
num = Integer.parseInt(keyboard.nextLine());
keyboard.close();
break;
} catch (NumberFormatException e) {
System.out.println("You must enter an integer");
}
}
System.out.println("num: " + num);
}
}
I, personally, would use an array or arrayList (based on your needs) to store the int values and then use a while loop to check and accept the numbers. while (array.length < 3) do {int checking}. This way the script will not run if there are already 3 values in the array and will run until you get 3 values.
this should do the job..
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int[] intArray = new int[3];
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < intArray.length; i++) {
System.out.print("input integer #"+(i+1)+": ");
if (keyboard.hasNextInt()) {
intArray[i] = keyboard.nextInt();
System.out.println("value for #"+(i+1)+": " + intArray[i]);
} else
{
System.out.println("not an integer");
break;
}
}
keyboard.close();
}
}
or maybe another solution that asks again when the number was no integer
import java.util.Scanner;
public class Main2 {
public static void main(String[] args) {
int[] intArray = new int[3];
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < intArray.length; i++) {
boolean isInputCorrect = false;
do {
System.out.print("input integer #" + (i + 1) + ": ");
if (keyboard.hasNextInt()) {
intArray[i] = keyboard.nextInt();
System.out.println("value for #" + (i + 1) + ": " + intArray[i]);
isInputCorrect = true;
} else {
System.out.println("not an integer, try again");
keyboard.nextLine();
}
} while (!isInputCorrect);
}
keyboard.close();
}
}

Java Scanner Continuous User input?

For java practice, i am trying to create a program that reads integers from the keyboard until a negative one is entered.
and it prints the maximum and minimum of the integer ignoring the negative.
Is there a way to have continuous input in the same program once it runs? I have to keep running the program each time to enter a number.
Any help would be appreciated
public class CS {
public static void main(String []args) {
Scanner keys = new Scanner(System.in);
System.out.println("Enter a number: ");
int n = keys.nextInt();
while(true)
{
if(n>0)
{
System.out.println("Enter again: ");
n = keys.nextInt();
}
else
{
System.out.println("Number is negative! System Shutdown!");
System.exit(1);
}
}
}
}
Here is a part of my code - It works, but i think there is an easier way of doing what i want but not sure how!
import java.util.Scanner;
public class ABC {
public static void main(String []args) {
int num;
Scanner scanner = new Scanner(System.in);
System.out.println("Feed me with numbers!");
while((num = scanner.nextInt()) > 0) {
System.out.println("Keep Going!");
}
{
System.out.println("Number is negative! System Shutdown!");
System.exit(1);
}
}
}
You could do something like:
Scanner input = new Scanner(System.in);
int num;
while((num = input.nextInt()) >= 0) {
//do something
}
This will make num equal to the next integer, and check if it is greater than 0. If it's negative, it will fall out of the loop.
A simple loop can solve your problem.
Scanner s = new Scanner(System.in);
int num = 1;
while(num>0)
{
num = s.nextInt();
//Do whatever you want with the number
}
The above loop will run until a negative number is met.
I hope this helps you

Categories

Resources