I am trying to understand gathering user input and looping until conditions.
I want to loop a scanner until user inputs 0, however, I need each inputted integer to be stored so it can be accessed for later use. The hard part is, I can't use an array.
simply you can do something like
List mylist = new ArrayList(); //in java. other wise you can create array[size]
int input = 1;
while(input!=0)
{
/* input number from user here */
if(input!=0)
mylist.add(input);
}
Here is an easy way to loop user input until 0 is entered.
Scanner console = new Scanner(System.in);
boolean loop = true;
String input;
while(loop) {
input = console.nextLine();
//Add input to a data structure
if (input.equals("0")) {
loop = false;
}
}
As far as adding the user input to a data structure, you said you can't use an Array. How about a List or a Set. Even a Stack or a Queue would work. Have you looked at using any of these data structures?
Here is a basic example using a List:
List<String> aList = new ArrayList<String>();
aList.add(input);
And this is how you might use a Stack:
Stack<String> stk = new Stack<String>();
stk.push(input);
Perhaps the most efficient way would be to use a HashSet:
Set<String> set = new HashSet<String>();
set.add(input);
Using arrays here would be little tricky since you don't know the numbe of elements user is going to enter. You can always write the code to create a new array with bigger capacity once user has exhaused initial capacity and copy over existing input elements but using List would be much easier.
Scanner scanner = new Scanner(System.in);
List<Integer> input = new ArrayList<>();
int nextInt = Integer.MIN_VALUE;
while((nextInt = scanner.nextInt()) != 0){
input.add(nextInt);
}
See this question if you really want to use arrays. Answer explains on creating new arrays and copying over elements. Java dynamic array sizes?
Related
TL;DR-- how to get a java.util.NoSuchElementException to return a null instead of error and crash the program.
I was writing a program that is supposed to read a series of ints from a text file. In the program the amount of ints will vary each time I run it. I have written a piece of code that will read ints and I want to know how to make the java.util.NoSuchElementException not crash my program and instead return a null.
The code I have writen is as follows
public static void main(String[] args) throws IOException{
Scanner Input = new Scanner(new File("newestcode.txt"));
Integer[] digits = new Integer[100];
int h = 0;
while(true){
digits[h] = Input.nextInt();
h++;
System.out.println(digits[h]);
}
}
in case you are curious, the program I am to be writing is a sort of decryption engine for a bad encryption engine I wrote the other day
try {
digits[h] = Input.nextInt();
h++;
System.out.println(digits[h]);
}catch (NoSuchElementException e){
break;
}
First of all, if you're not sure about amount of ints in your file, don't try to store them into fixed-size array. Use ArrayList instead.
Also don't use endless loop while(true) but consider using Input.hasNext() to check if there still is something to read from file.
And one more. You're trying to print value after increment. This means that you're adding element on 0 position but trying to read it from 1 position. Make increment on the end of the loop.
Scanner Input = new Scanner(new File("newestcode.txt"));
List<Integer> digits = new ArrayList<>();
int h = 0;
while(Input.hasNetxt()){
digits.add(h, Input.nextInt());
System.out.println(digits.get(h));
h++;
}
You should use the input.hasNext() method to check whether the input has any more 'int' before using it.
In order to support any length of int elements, you cannot set the array to a fixed length of 100, you need to use an ArrayList to add elements dynamically.
Scanner input = new Scanner(new File("./newestcode.txt"));
List<Integer> digits = new ArrayList<>();
int h = 0;
while (input.hasNext()) {
digits.add(h, input.nextInt());
System.out.println(digits.get(h));
h++;
}
Note: You need to print digits[h] before increasing the h.
What I'm trying to do is to declare a certain amount of strings according to the amount of tokens a scanner scans in a single input, then have these strings equal the next input. This is what I'm trying:
int numberOfTokens = 0;
boolean mainLoop = true;
Scanner input = new Scanner(System.in);
while(mainLoop == true)
{
while(input.hasNext())
{
String int(+ numberOfTokens) = input.next(); (this doesn't work)
numberOfTokens += 1;
}
}
I hope I made it clear of what I am trying to do. I tried using String arrays, but they won't work for what i'm trying to do.
Thanks.
You can do:
String[] myStringArray = new String[abc];
where abc is an integer you get from user
and then
myStringArray[index] = input.next();
and index must be a valid number between 0 and abc
If you don't know in advance how many strings you will need to store then an array is a poor choice of data structure, at least during the input phase. Use a List instead -- these keep the elements in order, yet expand as needed to accommodate new elements. They are convenient to work with overall, but if you ultimately must get the strings in array form (e.g. because some external API requires that form) then it is easy to obtain the corresponding array.
For example:
List<String> tokens = new ArrayList<>();
while (input.hasNext()) {
tokens.add(input.next());
// a List keeps track of its own length
}
If you later wanted the array then you could do
String[] tokenArray = tokens.toArray(new String[0]);
The number of tokens recorded in the List is available at any time as tokens.size(), or after you convert to an array, as tokenArray.length.
In any event, you cannot create new variables at runtime in Java.
Instead of string variables, you should declare one variable like this before the while loop.
List<String> tokens = new ArrayList<>();
while (input.hasNext()) {
tokens.add(input.next());
}
You can then operate on the tokens, like this:
int n = tokens.size();
for (String token : tokens) {
System.out.println(token);
}
I just need a step in the right direction. I am working on some homework for a basic java class and I can't seem to recall what I should do here. I do not want to use an array though, I do know that. Here is the code so far.
import java.util.Scanner;
public class Store
{
public static void main (String [] args)
{ Scanner s = new Scanner (System.in);
System.out.println("How many songs would you like to purchase?");
int numSongs = s.nextInt();
for(int i = 0; i < numSongs; i++) {
System.out.println("Enter the length of the songs: ");
int lengthSongsi = s.nextInt();
}
}
}
I need to be able to store user-defined variables. The amount is unknown until the user tells us. I am not sure how to go about doing this without overwriting the last variable. If an array is the only way, I will use it
You would want to use an ArrayList. This is like an array, but it's dynamic, so you don't need to define the length initially:
ArrayList mList = new ArrayList();
You can also define types, like so:
ArrayList<String> mList = new ArrayList<String>();
Then, when you want to add data, you do:
mlist.add("My Value");
For more info, check the docs
As people suggested, use an ArrayList or an Array. Easy way to do would just be constantly add them to your ArrayList while some parameter remains true.
Also, and this is just my style of code, I always have the first { start after the declaration so instead of say if{.... it would be:
if
{..... makes code easier.
As for the code aspect of it, you could try this:
ArrayList<Integer> mList = new ArrayList();
for(int i = 0; i < numSongs; i ++)
{
System.out.println("Enter Song Length");
int lengthSongsi = s.nextInt();
mList.add(lengthSongsi);
//if you want to access the length of the song at a particular point
//just access it as you would any normal array, so it could look like
//System.out.println("Song length at index " + i + "is: " + mList.get(i));
}
If it doesn't work let me know. I haven't run it through an IDE yet as I am currently at work.
So I have a collection of phrases that are separated by newlines and I would like to populate an array with these phrases. This is what I have so far:
Scanner s;
s = new Scanner(new BufferedReader(new FileReader("Phrases.txt")));
for(i = 0; i < array.length;i++)
{
s.nextLine() = array[i];
}
Is there a fast and simple way to just populate an array with phrases separated by newlines?
The assignment should be reverse: -
array[i] = s.nextLine();
And, I think you should fill your array based on the input received from the file. Here you are receving input based on the length of your pre-declared array. I mean, since you are using an array, your size is fixed. So you can only populate it with a fixed number of phrases.
A better way would be to use an ArrayList.
List<String> phrases = new ArrayList<String>();
Now, you can populate your arraylist, based on the phrases you get from your file. You don't need to pre-define the size. It increases in size dynamically.
And to add phrases, you would do: -
phrases.add(s.nextLine());
With a while loop to read till EOF.
while (s.hasNextLine()) {
phrases.add(s.nextLine());
}
Since you don't know how many phrases you're likely to have (I suspect), I would populate an ArrayList<String> and convert it to an array using ArrayList.toArray() once you're done. I'd perhaps keep it as a Java collection, however, for greater flexibility.
You have the assignment operation inverted (array[i] should be set to s.nextLine(), not the other way around. Also, it would be best to modify the for loop to terminate when no more lines exist:
for(i = 0; i < array.length && s.hasNextLine() ;i++) {
array[i] = s.nextLine()
}
It can be done with a 1 liner with apache commons and specifically FileUtils.readLines()
FileUtils.readLines(myFile).toArray(new String[0]);
Don't waste your time with Scanner. BufferedReader is just fine. Try this:
BufferedReader br = new BufferedReader(new FileReader("Phrases.txt")));
LinkedList<String> phrases = new LinkedList<String>();
while(br.ready()) {
phrases.add(br.readLine());
}
String[] phraseArray = phrases.toArray(new String[0]);
By the way it's important to use LinkedList not ArrayList if the file is large. That way you only create one array at the end. Otherwise you will have a lot of large array creation and wasted memory.
you are doing it wrong. it has to be
for(i = 0; i < array.length;i++)
{
array[i]=s.nextLine();
}
array[i] = value; // the value would be assigned into the array at index i.
However, a better option would be to use a List implementing classes such as ArrayList which gives you an advantage of dynamic size.
List<String> list = new ArrayList<>();
list.add(s.nextLine(());
Can anyone please help me with the code as how to read multiple lines from console and store it in array list?
Example, my input from the console is:
12 abc place1
13 xyz place2
and I need this data in ArrayList.
So far I tried this code:
Scanner scanner = new Scanner(System.in);
ArrayList informationList = new ArrayList<ArrayList>();
String information = "";
int blockSize = 0, count = 1;
System.out.println("Enter block size");
blockSize = scanner.nextInt();
System.out.println("Enter the Information ");
while (scanner.hasNext() && blockSize >= count) {
scanner.useDelimiter("\t");
information = scanner.nextLine();
informationList.add(information);
count++;
}
Any help is greatly appreciated.
Input line from console is mix of string and integer
You've got a few problems.
First of all, the initialization line for your ArrayList is wrong. If you want a list of Object so you can hold both Integers and Strings, you need to put Object inside the angle braces. Also, you're best off adding the generic type argument to the variable definition instead of just on the object instantiation.
Next, your count is getting messed up because you're initializing it to 1 instead of 0. I'm assuming "block size" really means the number of rows here. If that's wrong leave a comment.
Next, you don't want to reset the delimiter your Scanner is using, and you certainly don't want to do it inside your loop. By default a Scanner will break up tokens based on any whitespace which I think is what you want since your data is delimited both by tabs and newlines.
Also, you don't need to check hasNext() in your while condition. All of the next*() methods will block waiting for input so the call to hasNext() is unnecessary.
Finally, you're not really leveraging the Scanner to do what it does best which is parse tokens into whatever type you want. I'm assuming here that every data line is going to start with a single integer and the be followed by two strings. If that's the case, just make a call to nextInt() followed by two calls to next() inside your loop and you'll get all the data parsed out into the data types you need automatically.
To summarize, here is your code updated with all my suggestions as well as some other bits to get it to run:
import java.util.ArrayList;
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Object> list = new ArrayList<>();
System.out.println("Enter block size");
int blockSize = scanner.nextInt();
System.out.println("Enter data rows:");
int count = 0;
while (count < blockSize) {
list.add(scanner.nextInt());
list.add(scanner.next());
list.add(scanner.next());
count++;
}
System.out.println("\nThe data you entered is:");
System.out.println(list);
}
}