How to run while loop till user enter input? - java

I am trying to run while loop for each input user enter but don't know how to stop if user is not entering input.
I need help in stopping while loop if user doesn't enter input.
Code:
import java.util.*;
class petrol{
public static void main(String[] args){
int vehicle_counter=0,petrol_counter=0;
System.out.println("Enter quantity of petrol to be filled in vehicles seperated by space:");
Scanner s1 = new Scanner(System.in);
ArrayList<Integer> array = new ArrayList<Integer>();
while(true){
if(petrol_counter<=200 && array.size()<50){
int input = s1.nextInt();
petrol_counter=petrol_counter+input;
vehicle_counter++;
array.add(input);
}
else{
System.out.println("Quantity Excedded then 200 Litres or no of Vehicles excedded then 50.");
break;
}
}
System.out.println("Hii");
}
}
e.g: If I enter 2 3 4 2 and press enter loop should stop.
Problem with possible solution :
If I use while(s1.nextInt().equals(true)) I get an error.
How do I use break?

So, you can try something like this. Instead of Scanner, use BufferedReader to parse the input since all you need is a single line input. Also, BufferedReader is faster compared to Scanner.
Here is the code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Petrol {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int vehicle_counter=0,petrol_counter=0;
System.out.println("Enter quantity of petrol to be filled in vehicles seperated by space:");
String input = br.readLine();
String[] values = input.split(" ");
if(values.length>50){
System.out.println("Vehicles exceeded 50");
}else{
for(int i=0;i<values.length;i++){
int ip = Integer.parseInt(values[i]);
petrol_counter+=ip;
vehicle_counter++;
if(petrol_counter>200){
System.out.println("Petrol Quantity exceeded 200L");
}
}
}
System.out.println(petrol_counter+" Litres "+ " Vehicles "+vehicle_counter);
}
}

If you want to keep the Scanner you could also make the input as char and having a if statement that will exit the loop when you press a certain character.
import java.util.*;
public class petrol {
public static void main(String[] args) {
int vehicle_counter = 0, petrol_counter = 0;
System.out.println("Enter quantity of petrol to be filled in vehicles seperated by space:");
Scanner s1 = new Scanner(System.in);
ArrayList<Integer> array = new ArrayList<Integer>();
while (true) {
if (petrol_counter <= 200 && array.size() < 50) {
char input = s1.next().charAt(0); // use char instead
if (input == 'q' || input == 'Q') { //if user enters q or Q
System.out.println("Quantity Excedded then 200 Litres or no of Vehicles excedded then 50.");
break;
}
petrol_counter = petrol_counter + input;
vehicle_counter++;
array.add((int) input); //Cast to int
}
}
System.out.println("Hii");
}
}

Related

How to make the program to check the instance of a letter in java?

I am creating a cash register where I have to use a scanner and can only have 5 input amounts. It has to also include hst and that is by only having a "h" after or before an amount. My question is how would the program recognize that I have put an "h" after or before an amount? This seems to be done only using a string variable, so how would I accomplish that? I have to store the inputs in an array, and so I got that to work.
My Code:
// Import scanner class
import java.util.Scanner;
// Create class and method
class Main {
public static void main(String[] args) {
// Declare the scanner object and create scanner variables
Scanner inp = new Scanner(System.in);
System.out.println("Press any key to start");
String key = inp.nextLine();
System.out.println("\nEnter the amount of each item");
System.out.println("Upto 5 inputs are allowed!\n");
// Define an array double variable, set the limit to 5 inputs
double[] numbers = new double[5];
// Create a for loop to input any numbers 5 times
for (int i = 0; i < numbers.length; i++){
// Add a scanner input to let the user type out the values
numbers[i] = inp.nextDouble();
}
}
}
below code asks the user input for 5 times , and only valid values will be in the Array , Vald values are the values with 'h' at start or end and should only occur once. i.e. at 'h' at both end and start or more than once is invalid.
public static void main(String[] args) throws ParseException {
int counter = 1;
Double[] result = new Double[5];
int index = 0;
while(counter <= 5) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an Amount ");
String value = scanner.nextLine();
int indexOfH = value.indexOf("h");
int lastIndexOfH = value.lastIndexOf("h");
boolean containsHatstartsOrEnd = indexOfH == 0 || indexOfH == (value.length()-1);
if(containsHatstartsOrEnd && indexOfH==lastIndexOfH){ //Validate h at begins or end and should contains only once
result[index] = Double.parseDouble(value.replace("h", ""));
index++;
}
counter++;
}
System.out.println("Printing Valid values");
for(int i=0; i< result.length; i++) {
if(result[i]!=null) {
System.out.println(result[i]);
}
}
}
input & result
Enter an Amount 13.45h
Enter an Amount 55h.65
Enter an Amount 32h.33h
Enter an Amount h100.23
Enter an Amount h20
Printing Valid values
13.45
100.23
20.0

For loop: populate array from user input [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 4 years ago.
I was setting up a small app that asks a user to determine the array size and then populate it. The used "for" loop skips the index 0; but I'm uncertain why.
If you run this code with 1 as the array size it skips over the user inputting the first word.
The issue is certainly on the for-loop but it is so simple that I don't see it.
Thanks!
import java.util.Scanner;
public class WordRandomizerAdvanced {
public static void main(String[] args) {
int arrayDimesion;
Scanner sc = new Scanner(System.in);
System.out.println("****************************************************");
System.out.println("******** Welcome to Word Randomizer ADVANCED********");
System.out.println("****************************************************");
//Get array size
System.out.println("How many words would you like to enter?");
arrayDimesion = sc.nextInt();
String[] wordArray = new String[arrayDimesion];
//Populate with user input
for (int i=0; i<arrayDimesion; i++) {
System.out.println("Please enter a word");
wordArray[i] = sc.nextLine();
}
//Print all entered Strings
System.out.println("This are the words you entered: ");
for(int i = 0; i < wordArray.length; i++) {
System.out.println(wordArray[i]);
}
//Print random string from array
int r = (int)(Math.random() * wordArray.length);
System.out.println("The random word is: " + wordArray[r]);
}
}
Change your
arrayDimesion = sc.nextInt();
to
arrayDimesion = Integer.parseInt(sc.nextLine());
Reason: sc.nextInt() doesn't consume the newline character that you give after taking arrayDimesion input. This later on gets consumed in the next sc.nextLine() call.
PS: It might throw NumberFormatException. So you can handle it like :
try {
arrayDimesion = Integer.parseInt(sc.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
The below code is clean, easy to read and handles the edge cases.
import java.util.Scanner;
public class WordRandomizerAdvanced {
public static void main(String[] args) {
int numOfWords;
Scanner scanner = new Scanner(System.in);
System.out.println("****************************************************");
System.out.println("******** Welcome to Word Randomizer ADVANCED********");
System.out.println("****************************************************");
//Get array size
System.out.println("How many words would you like to enter?");
numOfWords = Integer.parseInt(scanner.nextLine());
String[] wordArray = new String[numOfWords];
//Populate with user input
System.out.println("Please enter the word(s)");
for (int i = 0; i < numOfWords; i++) {
wordArray[i] = scanner.nextLine();
}
//Print all entered Strings
System.out.println("These are the words you entered: ");
for (int i = 0; i < numOfWords; i++) {
System.out.println(wordArray[i]);
}
//Print random string from array
if (numOfWords == 0) {
System.out.println("You didn't enter a word");
} else {
int r = (int) (Math.random() * numOfWords);
System.out.println("The random word is: " + wordArray[r]);
}
}
}

Word Count: user defined [duplicate]

I attempted to create a calculator, but I can not get it to work because I don't know how to get user input.
How can I get the user input in Java?
One of the simplest ways is to use a Scanner object as follows:
import java.util.Scanner;
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a number: ");
int n = reader.nextInt(); // Scans the next token of the input as an int.
//once finished
reader.close();
You can use any of the following options based on the requirements.
Scanner class
import java.util.Scanner;
//...
Scanner scan = new Scanner(System.in);
String s = scan.next();
int i = scan.nextInt();
BufferedReader and InputStreamReader classes
import java.io.BufferedReader;
import java.io.InputStreamReader;
//...
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
int i = Integer.parseInt(s);
DataInputStream class
import java.io.DataInputStream;
//...
DataInputStream dis = new DataInputStream(System.in);
int i = dis.readInt();
The readLine method from the DataInputStream class has been deprecated. To get String value, you should use the previous solution with BufferedReader
Console class
import java.io.Console;
//...
Console console = System.console();
String s = console.readLine();
int i = Integer.parseInt(console.readLine());
Apparently, this method does not work well in some IDEs.
You can use the Scanner class or the Console class
Console console = System.console();
String input = console.readLine("Enter input:");
You can get user input using BufferedReader.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String accStr;
System.out.println("Enter your Account number: ");
accStr = br.readLine();
It will store a String value in accStr so you have to parse it to an int using Integer.parseInt.
int accInt = Integer.parseInt(accStr);
Here is how you can get the keyboard inputs:
Scanner scanner = new Scanner (System.in);
System.out.print("Enter your name");
String name = scanner.next(); // Get what the user types.
The best two options are BufferedReader and Scanner.
The most widely used method is Scanner and I personally prefer it because of its simplicity and easy implementation, as well as its powerful utility to parse text into primitive data.
Advantages of Using Scanner
Easy to use the Scanner class
Easy input of numbers (int, short, byte, float, long and double)
Exceptions are unchecked which is more convenient. It is up to the programmer to be civilized, and specify or catch the exceptions.
Is able to read lines, white spaces, and regex-delimited tokens
Advantages of BufferedInputStream
BufferedInputStream is about reading in blocks of data rather than a single byte at a time
Can read chars, char arrays, and lines
Throws checked exceptions
Fast performance
Synchronized (you cannot share Scanner between threads)
Overall each input method has different purposes.
If you are inputting large amount of data BufferedReader might be
better for you
If you are inputting lots of numbers Scanner does automatic parsing
which is very convenient
For more basic uses I would recommend the Scanner because it is easier to use and easier to write programs with. Here is a quick example of how to create a Scanner. I will provide a comprehensive example below of how to use the Scanner
Scanner scanner = new Scanner (System.in); // create scanner
System.out.print("Enter your name"); // prompt user
name = scanner.next(); // get user input
(For more info about BufferedReader see How to use a BufferedReader and see Reading lines of Chars)
java.util.Scanner
import java.util.InputMismatchException; // import the exception catching class
import java.util.Scanner; // import the scanner class
public class RunScanner {
// main method which will run your program
public static void main(String args[]) {
// create your new scanner
// Note: since scanner is opened to "System.in" closing it will close "System.in".
// Do not close scanner until you no longer want to use it at all.
Scanner scanner = new Scanner(System.in);
// PROMPT THE USER
// Note: when using scanner it is recommended to prompt the user with "System.out.print" or "System.out.println"
System.out.println("Please enter a number");
// use "try" to catch invalid inputs
try {
// get integer with "nextInt()"
int n = scanner.nextInt();
System.out.println("Please enter a decimal"); // PROMPT
// get decimal with "nextFloat()"
float f = scanner.nextFloat();
System.out.println("Please enter a word"); // PROMPT
// get single word with "next()"
String s = scanner.next();
// ---- Note: Scanner.nextInt() does not consume a nextLine character /n
// ---- In order to read a new line we first need to clear the current nextLine by reading it:
scanner.nextLine();
// ----
System.out.println("Please enter a line"); // PROMPT
// get line with "nextLine()"
String l = scanner.nextLine();
// do something with the input
System.out.println("The number entered was: " + n);
System.out.println("The decimal entered was: " + f);
System.out.println("The word entered was: " + s);
System.out.println("The line entered was: " + l);
}
catch (InputMismatchException e) {
System.out.println("\tInvalid input entered. Please enter the specified input");
}
scanner.close(); // close the scanner so it doesn't leak
}
}
Note: Other classes such as Console and DataInputStream are also viable alternatives.
Console has some powerful features such as ability to read passwords, however, is not available in all IDE's (such as Eclipse). The reason this occurs is because Eclipse runs your application as a background process and not as a top-level process with a system console. Here is a link to a useful example on how to implement the Console class.
DataInputStream is primarily used for reading input as a primitive datatype, from an underlying input stream, in a machine-independent way. DataInputStream is usually used for reading binary data. It also provides convenience methods for reading certain data types. For example, it has a method to read a UTF String which can contain any number of lines within them.
However, it is a more complicated class and harder to implement so not recommended for beginners. Here is a link to a useful example how to implement a DataInputStream.
You can make a simple program to ask for user's name and print what ever the reply use inputs.
Or ask user to enter two numbers and you can add, multiply, subtract, or divide those numbers and print the answers for user inputs just like a behavior of a calculator.
So there you need Scanner class. You have to import java.util.Scanner; and in the code you need to use
Scanner input = new Scanner(System.in);
Input is a variable name.
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name : ");
s = input.next(); // getting a String value
System.out.println("Please enter your age : ");
i = input.nextInt(); // getting an integer
System.out.println("Please enter your salary : ");
d = input.nextDouble(); // getting a double
See how this differs: input.next();, i = input.nextInt();, d = input.nextDouble();
According to a String, int and a double varies same way for the rest. Don't forget the import statement at the top of your code.
Also see the blog post "Scanner class and getting User Inputs".
To read a line or a string, you can use a BufferedReader object combined with an InputStreamReader one as follows:
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
String inputLine = bufferReader.readLine();
Here, the program asks the user to enter a number. After that, the program prints the digits of the number and the sum of the digits.
import java.util.Scanner;
public class PrintNumber {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num = 0;
int sum = 0;
System.out.println(
"Please enter a number to show its digits");
num = scan.nextInt();
System.out.println(
"Here are the digits and the sum of the digits");
while (num > 0) {
System.out.println("==>" + num % 10);
sum += num % 10;
num = num / 10;
}
System.out.println("Sum is " + sum);
}
}
Here is your program from the question using java.util.Scanner:
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
int input = 0;
System.out.println("The super insano calculator");
System.out.println("enter the corrosponding number:");
Scanner reader3 = new Scanner(System.in);
System.out.println(
"1. Add | 2. Subtract | 3. Divide | 4. Multiply");
input = reader3.nextInt();
int a = 0, b = 0;
Scanner reader = new Scanner(System.in);
System.out.println("Enter the first number");
// get user input for a
a = reader.nextInt();
Scanner reader1 = new Scanner(System.in);
System.out.println("Enter the scend number");
// get user input for b
b = reader1.nextInt();
switch (input){
case 1: System.out.println(a + " + " + b + " = " + add(a, b));
break;
case 2: System.out.println(a + " - " + b + " = " + subtract(a, b));
break;
case 3: System.out.println(a + " / " + b + " = " + divide(a, b));
break;
case 4: System.out.println(a + " * " + b + " = " + multiply(a, b));
break;
default: System.out.println("your input is invalid!");
break;
}
}
static int add(int lhs, int rhs) { return lhs + rhs; }
static int subtract(int lhs, int rhs) { return lhs - rhs; }
static int divide(int lhs, int rhs) { return lhs / rhs; }
static int multiply(int lhs, int rhs) { return lhs * rhs; }
}
Scanner input = new Scanner(System.in);
String inputval = input.next();
Scanner input=new Scanner(System.in);
int integer=input.nextInt();
String string=input.next();
long longInteger=input.nextLong();
Just one extra detail. If you don't want to risk a memory/resource leak, you should close the scanner stream when you are finished:
myScanner.close();
Note that java 1.7 and later catch this as a compile warning (don't ask how I know that :-)
Here is a more developed version of the accepted answer that addresses two common needs:
Collecting user input repeatedly until an exit value has been entered
Dealing with invalid input values (non-integers in this example)
Code
package inputTest;
import java.util.Scanner;
import java.util.InputMismatchException;
public class InputTest {
public static void main(String args[]) {
Scanner reader = new Scanner(System.in);
System.out.println("Please enter integers. Type 0 to exit.");
boolean done = false;
while (!done) {
System.out.print("Enter an integer: ");
try {
int n = reader.nextInt();
if (n == 0) {
done = true;
}
else {
// do something with the input
System.out.println("\tThe number entered was: " + n);
}
}
catch (InputMismatchException e) {
System.out.println("\tInvalid input type (must be an integer)");
reader.nextLine(); // Clear invalid input from scanner buffer.
}
}
System.out.println("Exiting...");
reader.close();
}
}
Example
Please enter integers. Type 0 to exit.
Enter an integer: 12
The number entered was: 12
Enter an integer: -56
The number entered was: -56
Enter an integer: 4.2
Invalid input type (must be an integer)
Enter an integer: but i hate integers
Invalid input type (must be an integer)
Enter an integer: 3
The number entered was: 3
Enter an integer: 0
Exiting...
Note that without nextLine(), the bad input will trigger the same exception repeatedly in an infinite loop. You might want to use next() instead depending on the circumstance, but know that input like this has spaces will generate multiple exceptions.
import java.util.Scanner;
class Daytwo{
public static void main(String[] args){
System.out.println("HelloWorld");
Scanner reader = new Scanner(System.in);
System.out.println("Enter the number ");
int n = reader.nextInt();
System.out.println("You entered " + n);
}
}
Add throws IOException beside main(), then
DataInputStream input = new DataInputStream(System.in);
System.out.print("Enter your name");
String name = input.readLine();
It is very simple to get input in java, all you have to do is:
import java.util.Scanner;
class GetInputFromUser
{
public static void main(String args[])
{
int a;
float b;
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
s = in.nextLine();
System.out.println("You entered string " + s);
System.out.println("Enter an integer");
a = in.nextInt();
System.out.println("You entered integer " + a);
System.out.println("Enter a float");
b = in.nextFloat();
System.out.println("You entered float " + b);
}
}
import java.util.Scanner;
public class Myapplication{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int a;
System.out.println("enter:");
a = in.nextInt();
System.out.println("Number is= " + a);
}
}
You can get user input like this using a BufferedReader:
InputStreamReader inp = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(inp);
// you will need to import these things.
This is how you apply them
String name = br.readline();
So when the user types in his name into the console, "String name" will store that information.
If it is a number you want to store, the code will look like this:
int x = Integer.parseInt(br.readLine());
Hop this helps!
Can be something like this...
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter a number: ");
int i = reader.nextInt();
for (int j = 0; j < i; j++)
System.out.println("I love java");
}
You can get the user input using Scanner. You can use the proper input validation using proper methods for different data types like next() for String or nextInt() for Integer.
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
//reads the input until it reaches the space
System.out.println("Enter a string: ");
String str = scanner.next();
System.out.println("str = " + str);
//reads until the end of line
String aLine = scanner.nextLine();
//reads the integer
System.out.println("Enter an integer num: ");
int num = scanner.nextInt();
System.out.println("num = " + num);
//reads the double value
System.out.println("Enter a double: ");
double aDouble = scanner.nextDouble();
System.out.println("double = " + aDouble);
//reads the float value, long value, boolean value, byte and short
double aFloat = scanner.nextFloat();
long aLong = scanner.nextLong();
boolean aBoolean = scanner.nextBoolean();
byte aByte = scanner.nextByte();
short aShort = scanner.nextShort();
scanner.close();
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Welcome to the best program in the world! ");
while (true) {
System.out.print("Enter a query: ");
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
if (s.equals("q")) {
System.out.println("The program is ending now ....");
break;
} else {
System.out.println("The program is running...");
}
}
}
}
This is a simple code that uses the System.in.read() function. This code just writes out whatever was typed. You can get rid of the while loop if you just want to take input once, and you could store answers in a character array if you so choose.
package main;
import java.io.IOException;
public class Root
{
public static void main(String[] args)
{
new Root();
}
public Root()
{
while(true)
{
try
{
for(int y = 0; y < System.in.available(); ++y)
{
System.out.print((char)System.in.read());
}
}
catch(IOException ex)
{
ex.printStackTrace(System.out);
break;
}
}
}
}
I like the following:
public String readLine(String tPromptString) {
byte[] tBuffer = new byte[256];
int tPos = 0;
System.out.print(tPromptString);
while(true) {
byte tNextByte = readByte();
if(tNextByte == 10) {
return new String(tBuffer, 0, tPos);
}
if(tNextByte != 13) {
tBuffer[tPos] = tNextByte;
++tPos;
}
}
}
and for example, I would do:
String name = this.readLine("What is your name?")
Keyboard entry using Scanner is possible, as others have posted. But in these highly graphic times it is pointless making a calculator without a graphical user interface (GUI).
In modern Java this means using a JavaFX drag-and-drop tool like Scene Builder to lay out a GUI that resembles a calculator's console.
Note that using Scene Builder is intuitively easy and demands no additional Java skill for its event handlers that what you already may have.
For user input, you should have a wide TextField at the top of the GUI console.
This is where the user enters the numbers that they want to perform functions on.
Below the TextField, you would have an array of function buttons doing basic (i.e. add/subtract/multiply/divide and memory/recall/clear) functions.
Once the GUI is lain out, you can then add the 'controller' references that link each button function to its Java implementation, e.g a call to method in your project's controller class.
This video is a bit old but still shows how easy Scene Builder is to use.
The most simple way to get user input would be to use Scanner. Here's an example of how it's supposed to be used:
import java.util.Scanner;
public class main {
public static void main(String[]args) {
Scanner sc=new Scanner(System.in);
int a;
String b;
System.out.println("Type an integer here: ");
a=sc.nextInt();
System.out.println("Type anything here:");
b=sc.nextLine();
The line of code import java.util.Scanner; tells the program that the programmer will be using user inputs in their code. Like it says, it imports the scanner utility. Scanner sc=new Scanner(System.in); tells the program to start the user inputs. After you do that, you must make a string or integer without a value, then put those in the line a=sc.nextInt(); or a=sc.nextLine();. This gives the variables the value of the user inputs. Then you can use it in your code. Hope this helps.
Using JOptionPane you can achieve it.
Int a =JOptionPane.showInputDialog(null,"Enter number:");
import java.util.Scanner;
public class userinput {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Name : ");
String name = input.next();
System.out.print("Last Name : ");
String lname = input.next();
System.out.print("Age : ");
byte age = input.nextByte();
System.out.println(" " );
System.out.println(" " );
System.out.println("Firt Name: " + name);
System.out.println("Last Name: " + lname);
System.out.println(" Age: " + age);
}
}
class ex1 {
public static void main(String args[]){
int a, b, c;
a = Integer.parseInt(args[0]);
b = Integer.parseInt(args[1]);
c = a + b;
System.out.println("c = " + c);
}
}
// Output
javac ex1.java
java ex1 10 20
c = 30

allow only chars as user input and assign them to variables?

I have this task where I have to handle some user input. The user should only be able to enter a,b,c,d,e,f,g,h,i,j,k,l and after the user input I want to assign a,b,c..l to variables 0,1,2,3,4..,11. Every other input, except for capital letters should give an error - but how can I do this?
I got as far as this:
int number;
public String playerInput;
public void start()
{
Scanner scn = new Scanner( System.in );
System.out.println("please enter input:");
playerInput = scn.nextLine();
System.out.println("scn.nextLine() = " +playerInput);
}
I really don't know how I would be able to just store mentioned letters and assign them to variables, can someone help?
Since it unclear what you meant by Assiging it to variable from number.
so here i'm giving you idea how to just input char between a-l and then you can do the things with you input
public class CharInput {
public static void main(String... str) throws IOException {
// open Scanner for input
Scanner keyboard = new Scanner(System.in);
System.out.println("Input");
//since you want only lowercase as input so converting at front is an better option
String playerInput = keyboard.next().toLowerCase();
// to make sure we have only char input nothing else
char input = playerInput.charAt(0);
// Check if the inputted char is between a and l only
if (input >= 'a' && input <='l' ){
// Do the stuff you want to do if the input is in between
// with the char variable input
}
else{
System.out.println("Error Raised");
}
}
}
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Prog {
int[] array = new int[12];
Set<String> list = new HashSet<String>();
String alphabet = "a,b,c,d,e,f,g,h,i,j,k,l,A,B,C,D,E,F,G,H,I,J,K,L";
int count = 0 ;
public String playerInput;
public void start() throws Exception
{
String[] val = alphabet.split(",");
while(count<24){
list.add(val[count]);
count++;
}
Scanner scn = new Scanner( System.in );
while(count < 12){
System.out.println("please enter input:");
playerInput = scn.nextLine();
System.out.println("scn.nextLine() = " + playerInput);
if(list.contains(playerInput)){
//assign your desired value to that letter
}
else{
//throw exception here ;
}
}
}
}
I didnt understand your problem clearly but i guess may be you want to do something like this(not sure though) -
Scanner scn = new Scanner( System.in );
System.out.println("please enter input:");
playerInput = scn.nextLine();
int i=0;
Map<String,Integer> map=new TreeMap<String,Integer>();
Set<String> set= new TreeSet<String>();
while(playerInput.matches("[a-lA-L]")){
set.add(playerInput.toLowerCase());
playerInput=scn.nextLine();
if(!playerInput.matches("[a-lA-L]")){
System.out.println("Error!!! Wrong Input");
break;
}
}
for(String s:set){
map.put(s, i);
i++;
}
System.out.println(map);

how to only allow one argument at a time

I am allowing the user to enter numbers via command line. I would like to make it so when the user enters more then one number on the command line at a time it displays a message asking for one number then press enter. then carries on.
here is my code. If someone could show me how to implement this I would appreciate it.
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
class programTwo
{
private static Double calculate_average( ArrayList<Double> myArr )
{
Double sum = 0.0;
for (Double number: myArr)
{
sum += number;
}
return sum/myArr.size(); // added return statement
}
public static void main( String[] args )
{
Scanner scan = new Scanner(System.in);
ArrayList<Double> myArr = new ArrayList<Double>();
int count = 0;
System.out.println("Enter a number to be averaged, repeat up to 20 times:");
String inputs = scan.nextLine();
while (!inputs.matches("[qQ]") )
{
if (count == 20)
{
System.out.println("You entered more than 20 numbers, you suck!");
break;
}
Scanner scan2 = new Scanner(inputs); // create a new scanner out of our single line of input
try{
myArr.add(scan2.nextDouble());
count += 1;
System.out.println("Please enter another number or press Q for your average");
}
catch (InputMismatchException e) {
System.out.println("Stop it swine! Numbers only! Now you have to start over...");
main(args);
return;
}
inputs = scan.nextLine();
}
Double average = calculate_average(myArr);
System.out.println("Your average is: " + average);
}
}
As suggested in the comments to the question: Just do not scan the line you read for numbers, but parse it as a single number instead using Double.valueOf (I also beautified the rest of your code a little, see comments in there)
public static void main( String[] args )
{
Scanner scan = new Scanner(System.in);
ArrayList<Double> myArr = new ArrayList<Double>();
int count = 0;
System.out.println("Enter a number to be averaged, repeat up to 20 times:");
// we can use a for loop here to break on q and read the next line instead of that while you had here.
for (String inputs = scan.nextLine() ; !inputs.matches("[qQ]") ; inputs = scan.nextLine())
{
if (count == 20)
{
System.out.println("You entered more than 20 numbers, you suck!");
break;
}
try{
myArr.add(Double.valueOf(inputs));
count++; //that'S even shorter than count += 1, and does the exact same thing.
System.out.println("Please enter another number or press Q for your average");
}
catch (NumberFormatException e) {
System.out.println("You entered more than one number, or not a valid number at all.");
continue; // Skipping the input and carrying on, instead of just starting over.
// If that's not what you want, just stay with what you had here
}
}
Double average = calculate_average(myArr);
System.out.println("Your average is: " + average);
}
(Code untested, so there may be errors in there. Please notify me if you got one ;))
String[] numbers = inputs.split(" ");
if(numbers.length != 1){
System.out.println("Please enter only one number");
}

Categories