I want to exit a loop just by pressing Enter. How to do this? Now the loop exits when I enter any nonnumeric value and press Enter. How to exit by entering nothing and pressing Enter?
ArrayList<Integer> numbers = new ArrayList<Integer>();
int numberIn;
Scanner scan = new Scanner(System.in);
System.out.println("Enter numbers!");
while (scan.hasNextInt()) {
numberIn = scan.nextInt();
numbers.add(numberIn);
}
System.out.println("Numbers: " + numbers + ".");
This works for me:
ArrayList<Integer> numbers = new ArrayList<Integer>();
int numberIn;
Scanner scan = new Scanner(System.in);
System.out.println("Enter numbers!");
String input;
while (!(input = scan.nextLine()).isEmpty()) {
numberIn = Integer.parseInt(input);
numbers.add(numberIn);
}
System.out.println("Numbers: " + numbers + ".");
Try hasNext():
while (scan.hasNext("\\d+")) {
numberIn = scan.nextInt();
numbers.add(numberIn);
}
ArrayList<Integer> numbers = new ArrayList<Integer>();
int numberIn;
Scanner scan = new Scanner(System.in);
System.out.println("Enter numbers!");
String input;
while (!(input = scan.nextLine()).isEmpty()) {
numberIn = Integer.parseInt(input);
numbers.add(numberIn);
}
System.out.println("Numbers: " + numbers + ".");
Related
I've been instructed to create a code that takes a user's first 5 inputs (doubles) and finds the average. My only problem is creating an exception if a user inputs anything other than a number. Could someone show how I can add this exception to my code?
import java.util.*;
public class Test1
{
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args)
{
Scanner numbers = new Scanner(System.in);
System.out.println("Please enter a number: ");
double first = numbers.nextInt();
System.out.println("Please enter a number: ");
double second = numbers.nextInt();
System.out.println("Please enter a number: ");
double third = numbers.nextInt();
System.out.println("Please enter a number: ");
double fourth = numbers.nextInt();
System.out.println("Please enter a number: ");
double fifth = numbers.nextInt();
System.out.println("The average is\t" + ((first + second + third + fourth + fifth)/5)+"\t");
}
}
This will handle the user typing non Integers.
It also removes the static Scanner userInput which isn't being used.
public class HelloWorld
{
public static void main(String[] args)
{
Scanner numbers = new Scanner(System.in);
int total =0;
int numberOfQuestion = 5;
for (int i = 0; i < numberOfQuestion ; i ++) {
System.out.println("Please enter a number: ");
while (!numbers.hasNextInt()) {
System.out.println("Input was not a number, please enter a number: ");
numbers.next();
}
total = total + numbers.nextInt();
}
System.out.println("The average is\t" + (total/numberOfQuestion)+"\t");
}
}
I have some issue using Scanner
That's the problematic code:
public static void main(String[] args) {
System.out.println("Chose 1 or 2 = ");
Scanner scan = new Scanner(System.in);
byte a = scan.nextByte();
scan.close();
if (a==1) HW();
else if (a==2) {
System.out.print("Calculation program ... !\nInput Number 1st number = ");
Scanner Catch = new Scanner(System.in);
int x = Catch.nextInt();
System.out.println("");
System.out.print("Input Operand +,-,*,/ = ");
Scanner Catchc = new Scanner (System.in);
char z = Catchc.next().charAt(0);
System.out.println("");
System.out.print("Input 2nd number = ");
Scanner Catch2 = new Scanner (System.in);
int y = Catch2.nextInt();
Catch.close();
Catchc.close();
Catch2.close();
calc(x,y,z);
}
else System.out.println("Please input number 1 or 2 ");
}
}
Thats a simple calculator and i got no errors and the program didn't terminate but it do debug instead. It shows "no such element exception"
Calc method:
public static void calc(int x, int y, char z) {
int result;
result = 0;
switch (z) {
case '+': result = x + y;
case '-': result = x - y;
case '/': result = x / y;
case '*': result = x * y;
}
System.out.println("Result of " + x + " " + z + " " + y + " is..." + " " + result);
}
When working with Scanners, you should only create 1 and NEVER close them until your program is done. This is because closing a scanner closes the passed in InputStream, and this inputstream is the input of your program, so you program doesn't cant recieve anymore input after that points.
Rewrite your code to only create 1 scanner, and pass that to other functions:
public static void main(String[] args) { // TODO Auto-generated method stub
System.out.println("Chose 1 or 2 = ");
Scanner scan = new Scanner(System.in);
byte a = scan.nextByte();
if (a==1)
HW();
else if (a==2) {
System.out.print("Calculation program ... !\nInput Number 1st number = ");
int x = scan.nextInt();
System.out.println("");
System.out.print("Input Operand +,-,*,/ = ");
char z = scan.next().charAt(0);
System.out.println("");
System.out.print("Input 2nd number = ");
int y = scan.nextInt();
calc(x,y,z);
}
else
System.out.println("Please input number 1 or 2 ");
}
this is my code:
public static void main(String[] args) {
System.out.println("Please enter the number of values you would like to enter: ");
Scanner scan = new Scanner(System.in);
int intNumberOfNumbers = scan.nextInt();
for (int i = 0; i < intNumberOfNumbers; i++) {
System.out.println("Please enter a value for index " + i + ":");
int intValue = scan.nextInt();
}
}
What I'm trying to do is create a scanner that asks how many values they want to enter and whatever that value is, that's how many times it asks for number input. The problem is after I ask the question how can I add the number to an array list?
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int numOfInput=sc.nextInt();
ArrayList<Integer> array=new ArrayList<Integer>();
while(numOfInput-->0){
array.add(sc.nextInt());
}
}
public static void main(String[] args) {
System.out.println("Please enter the number of values you would like to enter: ");
Scanner scan = new Scanner(System.in);
int intNumberOfNumbers = scan.nextInt();
ArrayList<Integer> myArray= new ArrayList<>();
for (int i = 0; i < intNumberOfNumbers; i++) {
System.out.println("Please enter a value for index " + i + ":");
int intValue = scan.nextInt();
myArray.add(intValue);
}
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I've been trying to make a basic calculator, but the thing is every time I use if else, it either says I have to remove it due to syntax error or the green underline thing shows up and it says dead code. Could someone help me?
import java.util.Scanner;
public class additionCalculator {
public static void main(String[] args) {
int addresult;
int subtractresult;
int divideresult;
int multiplyresult;
String addition = null;
String subtraction = null;
String division = null;
String multiplication = null;
Scanner reader = new Scanner(System.in);
System.out.println("Do you want to do subtraction, division, multiplication, or addition?");
String i = reader.next();
if(i == addition) {
Scanner additioncalc = new Scanner (System.in);
System.out.println("Enter a number");
int add1 = reader.nextInt();
Scanner additioncalc2 = new Scanner (System.in);
System.out.println("Enter another number");
int add2 = reader.nextInt();
addresult = add1 + add2;
System.out.println("The sum is " +addresult);
} else if (i == multiplication) {
Scanner multiplicationcalc = new Scanner (System.in);
System.out.println("Enter a number");
int multiply1 = reader.nextInt();
Scanner multiplcationcalc2 = new Scanner (System.in);
System.out.println("Enter another number");
int multiply2 = reader.nextInt();
multiplyresult = multiply1 * multiply2;
System.out.println("The product is " +multiplyresult);
} else if (i == division) {
Scanner divisioncalc = new Scanner (System.in);
System.out.println("Enter a number");
int div1 = reader.nextInt();
Scanner divisioncalc2 = new Scanner (System.in);
System.out.println("Enter another number");
int div2 = reader.nextInt();
divideresult = div1 * div2;
System.out.println("The product is " +divideresult);
} else if (i == subtraction) {
Scanner subtractioncalc = new Scanner (System.in);
System.out.println("Enter a number");
int subtract1 = reader.nextInt();
Scanner subtractioncalc2 = new Scanner (System.in);
System.out.println("Enter another number");
int subtract2 = reader.nextInt();
subtractresult = subtract1 - subtract2;
System.out.println("The difference is " +subtractresult);
}
}
// Addition calculator
// Scanner reader = new Scanner(System.in);
// System.out.println("Please enter a number.");
// int i = reader.nextInt();
// Scanner reader2 = new Scanner(System.in);
// System.out.println("Please enter another number.");
// int j = reader2.nextInt();
// sum = i + j;
// System.out.println("The sum of the two numbers is " +sum);
}
You should be using string comparison function from java.lang.String.
Note:
== tests for reference equality.
.equals() tests for value equality.
The only thing i am missing is to use a sentinel value, like zero, to quit the loop when the user wants, even without enter any gussing.
import java.util.Scanner;
import java.util.Random;
public class RandomGuessing {
//-----------------------------------------------------------------------------------------------
//This application prompt to the user to guess a number. The user can still playing until
//guess the number or want to quit
//-----------------------------------------------------------------------------------------------
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
Random rand = new Random();
int randNum = rand.nextInt(100) + 1;
System.out.println(randNum);
System.out.println("\t\tHi-Lo Game with Numbers\t\t\n\t Guess a number between 1 and 100!!!\n");
String ans;
int attemptsCount = 0;
do {
System.out.print("Guess the number: ");
int input = scan.nextInt();
while(input != randNum){
attemptsCount++;
if(input < randNum){
System.out.println();
System.out.print("low guessing\nEnter new number: ");
input = scan.nextInt();
}
else{
System.out.println();
System.out.print("high guessing\nEnter new number: ");
input = scan.nextInt();
}
}
System.out.println();
System.out.println("Congrats!!! You guess right\nAttempts: "+attemptsCount);
System.out.println();
System.out.print("You want to play again (yes/no): ");
ans = scan.next();
randNum = rand.nextInt(100) + 1; //generate new random number between same above range,
//if the user wants to keep playing.
}while (ans.equalsIgnoreCase("yes"));
}
}
Here's a simple approach:
// inside do loop
System.out.print("Guess the number (-1 to quit): ");
int input = scan.nextInt();
if (input == -1) {
break;
}
Try using this code for exiting totaly:
System.exit(0);