How can i create as many scanners as the user wants - java

I want to write a code that will allow the user to pick how many scanners he wants to use. First I created a simple scanner and assigned an int to it
Scanner scanner = new Scanner(System.in);
int input = scanner.nextInt();
now the user will enter ANY integer (ex. 7). Then I want the program to create an array of scanners that will then allow a number of lines of input (in this case 7). Any help is appreciated!

To create a specific number of objects and store them somewhere you can easily use arrays:
Scanner[] scanners = new Scanner[num_of_scanners];
At this point you will have an array of null scanner objects. To declare them properly you have to use a loop like this:
for (int i = 0; i < scanners.length; i++)
{
scanners[i] = new Scanner(System.in);
}
Now you succesfully initialized all the scanners. To get your scanner at certain index see the example below:
Scanner first_scanner = scanners[0];
More on arrays here.

Related

Adding user input in Arraylist

I am new to JAVA and this is what I have to do:
Accept a set of marks (out of 100). The user should press the Enter button after each mark is entered and the mark should then be added to an ArrayList of Integers.
This is what I have so far:
int score = Integer.parseInt(marksinput.getText());
ArrayList<Integer> marks = new ArrayList();
Collections.addAll(marks, score);
String out = "";
String Out = null;
int[] studentmarks = {score};
for (int item : studentmarks) {
marksoutput.setText(""+item);
}
if (score > 100) {
marksoutput.setText("Enter marks\n out of 100");
}
This only adds one mark in the arraylist and I need user to input as many marks he wants. I know that my arraylist is wrong, which is why it only takes 1 number but I do not know how to make all the input numbers go in arraylist. What I have is that it takes the number and if user inputs another number, it just replaces the older number. I want it to display both the numbers not just one. Any help is appreciated and thank you in advance!☻☻
(This is not a duplicate even though others have the same title)
In case what you are after is a program that adds any integer typed by the user into an ArrayList, what you would have to do is the following:
Scanner scanner = new Scanner(System.in);
List<Integer> ints = new ArrayList<Integer>();
while(true)
ints.add(scanner.nextInt());
What this program will do, is let the user input any number and automatically puts it into an ArrayList for the user. These integers can then be accessed by using the get method from the ArrayList, like so:
ints.get(0);
Where the zero in the above code sample, indicates the index in the ArrayList from where you would like to retrieve an integer.
Since this website is not there to help people write entire programs, this is the very basics of the ArrayList I have given you.
The ArrayList is a subclass of List, which is why we can define the variable using List. The while loop in the above example will keep on going forever unless you add some logic to it. Should you want it to end after executing a certain amount of times, I would recommend using a for loop rather than a while loop.
Best regards,
Since it seems you are really new,
What you are looking for is a for-loop
From the Java documentation, he is the syntax of a for-loop in Java
for (initialization; termination; increment) {
statement(s)
}
Initialization: Obviously you want to start from 0
Termination: you want to stop after 100 inputs, so that's 99 (starting from zero)
Increment: you want to "count" one by one so count++
for(int counter = 0; counter < 100; counter++) {
//Ask user for input
//read and add to the ArrayList
}
So before you enter the for-loop you need to initialize the ArrayList, and a Scanner to read input:
Scanner sc = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList();
for(int counter=0; counter < 100; counter++) {
System.out.println("please enter the " + counter + " number");
int x = sc.nextInt();
list.add(x);
}

Convert input strings into int array

I want to read in five numbers from the console. To convert the input strings into int[x] for each number i tried to use a for loop. But it turns out that #1 incrementation is dead code and #2 my array is not initialized, even though i just did.
I'm on my first Java practices and would be happy to hear some advices.
My code:
public static void main(String[] args) throws IOException {
System.out.println("Type in five Numbers");
int [] array;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
for(int x=0; x<5; x++){
String eingabe = br.readLine();
array[x] = Integer.parseInt(eingabe);
break;
}
reserve(array); }
First off, you didn't initialize your array, you only declared an array variable (named array). I highly suggest reading and practicing this fundamental concept of Java before proceeding further, because otherwise you will likely be confused later on. You can read more about the terms declaration, initialization, and assignment here.
Another issue, as Andrew pointed out, is that you used the keyword break in your first iteration of the loop. This keyword terminates a block of code, so your loop will only run once and then exit for good.
This code can be greatly simplified with a Scanner. A Scanner reads input from a specified location. The scanner's constructor accepts two inputs: System.in, for the default input device on your computer (keyboard), or a File object, such as a file on your computer.
Scanners, by default, have their delimeter set to the whitespace. A delimeter specifies the boundary between successive tokens, so if you input 2 3 5 5, for example, and then run a loop and invoke the scanVarName.nextInt() method, it will ignore the white spaces and treat each integer in that single line as its own token.
So if I understand correctly, you want to read input from the user (who will presumably enter integers) and you want to store these in an integer array, correct? You can do so using the following code if you know how many integers the user will enter. You can first prompt them to tell you how many integers they plan to enter:
// this declares the array
int[] array;
// declares and initializes a Scanner object
Scanner scan = new Scanner(System.in);
System.out.print("Number of integers: ");
int numIntegers = scan.nextInt();
// this initializes the array
array = new int[numIntegers];
System.out.print("Enter the " + numIntegers + " integers: ");
for( int i = 0; i < numIntegers; i ++)
{
// assigns values to array's elements
array[i] = scan.nextInt();
}
// closes the scanner
scan.close();
You can then use a for-each loop to run through the items in your array and print them out to confirm that the above code works as intended.

Confusion with Scanners (Big Java Ex 6.3)

Currently reading Chapter 6 in my book. Where we introduce for loops and while loops.
Alright So basically The program example they have wants me to let the user to type in any amount of numbers until the user types in Q. Once the user types in Q, I need to get the max number and average.
I won't put the methods that actually do calculations since I named them pretty nicely, but the main is where my confusion lies.
By the way Heres a simple input output
Input
10
0
-1
Q
Output
Average = 3.0
Max = 10.0
My code
public class DataSet{
public static void main(String [] args)
{
DataAnalyze data = new DataAnalyze();
Scanner input = new Scanner(System.in);
Scanner inputTwo = new Scanner(System.in);
boolean done = false;
while(!done)
{
String result = input.next();
if (result.equalsIgnoreCase("Q"))
{
done = true;
}
else {
double x = inputTwo.nextDouble();
data.add(x);
}
}
System.out.println("Average = " + data.getAverage());
System.out.println("Max num = " + data.getMaximum());
}
}
I'm getting an error at double x = inputTwo.nextDouble();.
Heres my thought process.
Lets make a flag and keep looping asking the user for a number until we hit Q. Now my issue is that of course the number needs to be a double and the Q will be a string. So my attempt was to make two scanners
Heres how my understanding of scanner based on chapter two in my book.
Alright so import Scanner from java.util library so we can use this package. After that we have to create the scanner object. Say Scanner input = new Scanner(System.in);. Now the only thing left to do is actually ASK the user for input so we doing this by setting this to another variable (namely input here). The reason this is nice is that it allows us to set our Scanner to doubles and ints etc, when it comes as a default string ( via .nextDouble(), .nextInt());
So since I set result to a string, I was under the impression that I couldn't use the same Scanner object to get a double, so I made another Scanner Object named inputTwo, so that if the user doesn't put Q (i.e puts numbers) it will get those values.
How should I approach this? I feel like i'm not thinking of something very trivial and easy.
You are on the right path here, however you do not need two scanners to process the input. If the result is a number, cast it to a double using double x = Double.parseDouble(result) and remove the second scanner all together. Good Luck!

Using a Scanner with a String Splitter

I am trying to use a string splitter to display user input e.g. 1,2 coordinates to display on a console. I don't get any errors when I run my code. However, my attempt to use the splitter does not seem to work.
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a row and column number at which to shoot (e.g., 2,3): ");
String[] coordinates = scanner.nextLine().split(",");
if (coordinates.length != 2) {
System.out.println("Please enter coordinates in the correct format.");
System.out.println("\nPlayer 1 Please take your turn:");
continue;
}
System.out.println("\nEnter Mine location:");
System.out.println("\nPlease Enter x position for your Mine:");
System.in.read(byt);
str = new String(byt);
row = Integer.parseInt(str.trim());
System.out.println("\nPlease Enter y position for your Mine:");
System.in.read(byt);
str = new String(byt);
col = Integer.parseInt(str.trim());
Your use of System.in.read(...) is dangerous code and is not doing what you think it's doing:
System.in.read(byt); // *****
str = new String(byt);
row = Integer.parseInt(str.trim());
Instead use a Scanner, something that you already have, and either call getNextInt() on the Scanner, or get the line and parse it.
Also, you never use the Strings held in the coordinates array -- why get the Strings if you are ignoring them?
You ask about:
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a row and column number at which to shoot (e.g., 2,3): ");
str = scanner.nextInt().split(",");
but then see that the compiler won't allow this since you're trying to call a method on the int primitive that scanner.nextInt() returns.
My recommendation to use Scanner#nextInt() was as a replacement for you misuse of System.in.read(...). If instead you want the user to enter two numbers on one line, separated by a comma, then you're best bet is to use String.split(","), although, I think it might be better to use String.split("\\s*,\\s*") to get rid of any white space such as spaces hanging about. This way the split should work for 1,1 as well as 1, 2 and 1 , 2, and then you can parse the items held in the array via Integer.parseInt(...).

How do i declare and read values into integer values?

I'm really new to java and i'm taking an introductory class to computer science. I need to know how to Prompt the user to user for two values, declare and define 2 variables to store the integers, and then be able to read the values in, and finally print the values out. But im pretty lost and i dont even know how to start i spent a whole day trying.. I really need some help/guidance. I need to do that for integers, decimal numbers and strings. Can someone help me?
You can do this by using Scanner class :
A simple text scanner which can parse primitive types and strings using regular expressions.
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
For example, this code allows a user to read a number from System.in:
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
int j = scan.nextInt();
System.out.println("i = "+i +" j = "+j);
nextInt() : -Scans the next token of the input as an int and returns the int scanned from the input.
For more.
or to get user input you can also use the Console class : provides methods to access the character-based console device, if any, associated with the current Java virtual machine.
Console console = System.console();
String s = console.readLine();
int i = Integer.parseInt(console.readLine());
or you can also use BufferedReader and InputStreamReader classes and
DataInputStream class to get user input .
Use the Scanner class to get the values from the user. For integers you should use int, for decimal numbers (also called real numbers) use double and for strings use Strings.
A little example:
Scanner scan = new Scanner(System.in);
int intValue;
double decimalValue;
String textValue;
System.out.println("Please enter an integer value");
intValue = scan.nextInt(); // see how I use nextInt() for integers
System.out.println("Please enter a real number");
decimalValue = scan.nextDouble(); // nextDouble() for real numbers
System.out.println("Please enter a string value");
textValue = scan.next(); // next() for string variables
System.out.println("Your integer is: " + intValue + ", your real number is: "
+ decimalValue + " and your string is: " + textValue);
If you still don't understand something, please look further into the Scanner class via google.
As you will likely continue to run into problems like this in your class and in your programming career:
Lessons on fishing.
Learn to explore the provided tutorials through oracle.
Learn to read the Java API documentation
Now to the fish.
You can use the Scanner class. Example provided in the documentation.
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();

Categories