Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have a console application with a main method and some methods that I call from main. There, I want to ask the user for some input, for which I use the Scanner class.
Here's my problem:
I find there is no way to use Scanner when reading inputs from outside main without random exceptions or unexpected behaviour. I have tried two approaches:
Having a Scanner global variable in the class containing main. Then
I use this same Scanner in all functions in that same class.
In every function I need to ask for input, I declare a new Scanner
variable, use it, and close it before exiting the function.
1. makes Scanner try to read twice. I mean, I have a sc.readLine in a function and, when I exit that function, I have another sc.readLine in main. I input once and the two readLine lines get executed, the second one reading an empty String.
2. throws Exception (base class Exception) when I call any sc.readLine for a second time during the execution of the program.
I have also noticed that any other method other than readLine is going to read various items on the same line. For example, line "10 20 30 40" would execute 4 sc.nextInt calls.
TL;DR: how do you use Scanner in a console application?
One way:
import java.util.Scanner;
public class Main {
private Scanner scanner = new Scanner(System.in);
public Scanner getScanner() {
return scanner;
}
void fun1() {
Scanner in = getScanner();
System.out.print("Enter a string: ");
System.out.println("You entered: " + in.nextLine());
}
void fun2() {
Scanner in = getScanner();
System.out.print("Enter an integer: ");
int n = 0;
try {
n = Integer.parseInt(in.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
System.out.println(n + " + 10 = " + (n + 10));
}
public static void main(String[] args) {
Main m = new Main();
m.fun1();
m.fun2();
}
}
A sample run:
Enter a string: Hello world!
You entered: Hello world!
Enter an integer: 25
25 + 10 = 35
Another way:
import java.util.Scanner;
public class Main {
static void fun1(Scanner in) {
System.out.print("Enter a string: ");
System.out.println("You entered: " + in.nextLine());
}
static void fun2(Scanner in) {
System.out.print("Enter an integer: ");
int n = 0;
try {
n = Integer.parseInt(in.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
System.out.println(n + " + 10 = " + (n + 10));
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
fun1(in);
fun2(in);
}
}
A sample run:
Enter a string: Hello world!
You entered: Hello world!
Enter an integer: 25
25 + 10 = 35
Regarding your problem with next() or nextInt(): Given below is the recommended way for multiple inputs in one go.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean valid = true;
System.out.print("Enter some intgers: ");
String strNum = in.nextLine();
String[] strNumArr = strNum.split("\\s+");
int[] numArr = new int[strNumArr.length];
for (int i = 0; i < strNumArr.length; i++) {
try {
numArr[i] = Integer.parseInt(strNumArr[i]);
} catch (NumberFormatException e) {
numArr[i] = Integer.MIN_VALUE;
valid = false;
}
}
System.out.println(Arrays.toString(numArr));
if (!valid) {
System.out.println("Note: invalid inputs have been reset to " + Integer.MIN_VALUE);
}
}
}
A sample run:
Enter some intgers: 10 5 20 15
[10, 5, 20, 15]
Another sample run:
Enter some intgers: 4 40 a 20 b 15
[4, 40, -2147483648, 20, -2147483648, 15]
Note: invalid inputs have been reset to -2147483648
Check Scanner is skipping nextLine() after using next() or nextFoo()? for more information about console input using Scanner.
to use a single instance of Scanner (or any other datatype or class), you can use the design pattern "Singleton" which consist to instantiate a single instance of your Object for the whole project.
The Singleton definition (a new class) :
import java.util.Scanner;
public class ScannerSingleton {
private static Scanner sc = null;
private ScannerSingleton() {
sc = new Scanner(System.in);
}
public static Scanner getInstance() {
if (sc == null) {
synchronized(ScannerSingleton.class) {
if (sc == null)
sc = new ScannerSingleton();
}
}
}
}
and each time you want to use your scanner anywhere you only have to call ScannerSingleton.getInstance() which will return your single instance of scanner
example of use:
String test = ScannerSingleton.getInstance().nextLine();
I suggest to pass your Scanner object as another parameter for your functions.
public static void main(String[] args)
{
Scanner scanner=new Scanner(System.in);
String answer = ask(scanner, "what is your name?");
System.out.println("Oh! Hello dear " + answer + "!");
scanner.close();
}
private static String ask(Scanner scanner, String question)
{
System.out.println(question);
return scanner.nextLine();
}
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
I am trying to get the strings to separate, and WITHOUT the comma.
We haven't learned anything like arrays, this is an intro class.
Everything I find on here just keeps giving me errors or does nothing to my code in zybooks.
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // Input stream for standard input
Scanner inSS = null; // Input string stream
String lineString = ""; // Holds line of text
String firstWord = ""; // First name
String secondWord = ""; // Last name
boolean inputDone = false; // Flag to indicate next iteration
// Prompt user for input
System.out.println("Enter input string: ");
// Grab data as long as "Exit" is not entered
while (!inputDone) {
// Entire line into lineString
lineString = scnr.nextLine();
inSS = new Scanner(lineString);
firstWord = inSS.next();
lineString.split(",");
// Output parsed values
if (firstWord.equals("q")) {
System.out.println("Enter input string: ");
inputDone = true;
}
//This may be where I am messing up??
else if (lineString.contains(",")) {
secondWord = inSS.next();
System.out.println("First word: " + firstWord);
System.out.println("Second word: " + secondWord);
System.out.println();
} else {
System.out.println("Error: No comma in string");
System.out.println("Enter input string: ");
}
}
return;
}
}
I am messing up somewhere and keep getting different error codes as I keep messing with it...
"Enter input string:
First word: Jill,
Second word: Allen"
When it should be
"Enter input string:
First word: Jill
Second word: Allen"
And then also as the computer enters more data I start getting this message:
"Exception in thread "main" java.util.NoSuchElementException"
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at ParseStrings.main(ParseStrings.java:44)"
One of the possibilities (if you didn't learn about arrays) is to use StringBuilder and remove commas or simply loop over input string and if character at let's say index 8 is comma, you do yourString.substring(0,8);, and then print the second word as yourString.substring(10, yourstring.length); I put starting index of 10 in the second substring because you want to skip comma and a space that's separating first and last name. Here is code sample for using nothing but String class, it's methods and for loop:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter first name and last name: ");
String str = in.nextLine();
int indexOfComma = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ',')
indexOfComma = i;
}
System.out.println("First name is: " + (str.substring(0, indexOfComma)));
System.out.println("Last name is: " + (str.substring(indexOfComma + 2, str.length())));
}
}
Or as I see you tried using split() (but since you said you didn't learn arrays yet I posted solution above), you can do it with .split() like this:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter first name and last name: ");
String[] name = in.nextLine().split(", ");
System.out.println("First name is: " + name[0]);
System.out.println("Last name is: " + name[1]);
}
}
Also, here is an example with StringBuilder class:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter first name and last name: ");
StringBuilder name = new StringBuilder(in.nextLine());
name.deleteCharAt(name.indexOf(","));
System.out.println("Full name is: " + name);
}
}
Your error happens when the Scanner reads all the data, such as calling the nextLine method and there's no line... Or next method when you didn't put a space after the comma
By default, the Scanner uses whitespace as a delimiter. If you want to add a comma delimiter before any whitespace, you can try this
Scanner sc=new Scanner(System.in);
sc.useDelimiter(",?\\s+");
Now, sc.next() will read only Hello from Hello, World, and a second call to it should return World
Or you can use the array you made
String[] words = lineString.split(",");
String first = words[0]:
String second = words[1];
I am using Java eclipse and I would like to have the user input the filename to retrieve a list of scores from the file. My goal is to take the average of those numbers. What line of code do I need just to get the user to input a file name and for the program to take those numbers so that I can compute with them? Currently I can have the user input scores, But I need to get the numbers from the file instead. I have visited numerous resources on this site. Here are a few:
BufferedReader, Error finding file, Getting a list from a file
package Average;
/**An average of scores*/
import java.util.Scanner;
public class Average2 {
public static void main(String[] args) {
int grade = 0;
int students = 0;
float total = 0;
double average = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter number of students: ");
students = input.nextInt();
if (students <= 10) {
System.out.println("Enter the grades of the students: ");
for(int i = 0; i < students; i++) {
do {
grade = input.nextInt();
} while(grade < 0 || grade > 100);
total += grade;
}
average = (total/students);
int median = ((82+84)/2);
System.out.println("The average is " + average);
System.out.println("The mean is " + median);
}
}
}
Update since above post!
package trials;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class trials2 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
// Create new Scanner object to read from the keyboard
Scanner in = new Scanner(System.in);
// Grab the name of the file
System.out.println("Enter filename: ");
String fileName = in.next();
// Access the file
Scanner fileToRead = new Scanner(new File(fileName));
// While there is still stuff in the file...
double sum = 0;
while (fileToRead.hasNext()) {
if (fileToRead.hasNextDouble()) {
sum += fileToRead.nextDouble();
} else {
fileToRead.next();
}
}
{
fileToRead.close();
}
System.out.println(sum);
}
}
The results I get from this:
Enter filename:
esp.txt <--entered by me
501.0
Given that you want to find the average of numbers in a file, you could do something like this:
// Create new Scanner object to read from the keyboard
Scanner in = new Scanner(System.in);
// Grab the name of the file
System.out.println("Enter filename: ");
String fileName = in.next();
// Access the file
Scanner fileToRead = new Scanner(new File(fileName));
// Initialize our relevant counters
double sum = 0.0;
int numStudents = 0;
// While there is still stuff in the file...
while (fileToRead.hasNext()) {
// Is this next line consisting of just a number?
if (fileToRead.hasNextDouble()) {
// If it is, accumulate
sum += fileToRead.nextDouble();
numStudents++;
}
else { // Else, just skip to the next line
fileToRead.next();
}
}
// Close the file when finished
fileToRead.close();
// Print the average:
System.out.println("The average mark is: " + (sum / numStudents));
This code will create a new Scanner object that will read input from your keyboard. Once it does that, you type in the file name, and it gets access to this file by opening another Scanner object. After that, we initialize some counters to help us calculate the average. These are sum, which will add up all of the marks we encounter and numStudents, which keeps track of how many students there are in the file.
The while loop will keep looping through each line of this file until it reaches the end. What is important is that you check to see whether or not the line you are reading in next consists of a single number (double). If it is, then add this to our sum. If it isn't, skip to the next line.
Once you're finished, close the file, then display the average by taking the sum and dividing by the total number of students we have encountered when reading the numbers in the file.
Just took a look at your profile and your profile message. You have a long road ahead of you. Good luck!
Look at the Java tutorial on Scanning: http://docs.oracle.com/javase/tutorial/essential/io/scanning.html, particularly the ScanSum example. It shows how to scan double values from a text file and add them. You should be able to modify this example for your project.
Scanner userInput = new Scanner(System.in);
System.out.println("ENter filename");
String fileName = userInput.next();
Scanner fileScan = new Scanner(new File(fileName));
then use scanner methods to process lines or string tokens you are interested in.
import java.util.Scanner;
public class Cardhelp2{
private static String[] pairArray={"A,A","K,K","Q,Q","J,J","10,10","9,9","8,8","7,7","6,6","5,5","4,4","3,3","2,2"};
public static void generateRandom(int k){
int minimum = 0;
int maximum = 13;
for(int i = 1; i <= k; i++)
{
int randomNum = minimum + (int)(Math.random()* maximum);
System.out.print("Player " + i +" , You have been dealt a pair of: ");
System.out.println(pairArray[randomNum]);
}
} //reads array and randomizes cards
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many players would you like to play with? ");
int m = scan.nextInt();
generateRandom(m);
//displays the cards
___________________________________________________
System.out.println("Would you like to play?");
Scanner scanner = new Scanner(System.in);
if(scanner.next().equalsIgnoreCase("y")||scanner.next().equalsIgnoreCase("yes")) {
System.out.println("This will be fun");
} else if(scanner.next().equalsIgnoreCase("n")||scanner.next().equalsIgnoreCase("no")) {
System.out.println("Maybe next time");
} else {
System.out.println("Invalid character");
}
}
}
Im having trouble understanding why the end part is not working, I've been told i need to change scanner.next(); to a variable but im not sure how to do it and get the code working. Is there a simple way of reading in the users answer then displaying a response to the user?
Thanks
Your conditional expression
if(scanner.next().equalsIgnoreCase("y")||scanner.next().equalsIgnoreCase("yes"))
calls scanner.next() twice, which means the second call will read/wait for more input. Instead you need to call it only once, store the result and use that in the comparison:
String tmp = scanner.next();
if(tmp.equalsIgnoreCase("y")||tmp.equalsIgnoreCase("yes"))
Let's assume the user inputs "yes".
At
if(scanner.next().equalsIgnoreCase("y")||scanner.next().equalsIgnoreCase("yes")) {
Scanner.next() produces "yes" in the first test. So the code is effectively
"yes".equalsIgnoreCase("y")
Which is false, so it moves to the next test:
scanner.next().equalsIgnoreCase("yes")
Here's where your issue is.
the "yes" entered has already been consumed by the first test. Now the Scanner has nothing in the buffer.
If you want to test the SAME input again, you must capture it, and use that in your tests.
So
String userReply= Scanner.next();
if(userReply.equalsIgnoreCase("y")||userReply.equalsIgnoreCase("yes")) {...
This is becauswe, with each call to scanner.next(), the Scanner returns the next value in the stream, and then MOVES PAST IT
If the user had entered "yes" and then "no", the tests would be performed like this:
if("yes".equalsIgnoreCase("y")||"no".equalsIgnoreCase("yes")) {...
You need change the way of Scanner's calls.
The user input \n and Scanner seems don't follow with the next token. Then you need read line by line.
:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("How many players would you like to play with? ");
int m = Integer.parseInt(sc.nextLine()); // May thrown NumberFormatException
generateRandom(m);
//displays the cards
System.out.print("Would you like to play? ");
String input = sc.nextLine();
if (input.equalsIgnoreCase("y") || input.equalsIgnoreCase("yes")) {
System.out.println("This will be fun");
} else if (input.equalsIgnoreCase("n") || input.equalsIgnoreCase("no")) {
System.out.println("Maybe next time");
} else {
System.out.println("Invalid character");
}
}