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.
Related
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 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?
Any possible way to keep entering numbers, and when the same number is entered 2 or more times an error message arises or something like that? I need this to be answered in Java only. I'm new and I don't know where to go from here. I need help searching values in the array and then printing out all the numbers that have been entered.
public class Test
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("How big is the group?: ");
int[] group = new int[input.nextInt()];
for (int i = 0; i < group.length; i++)
{
System.out.println("Please enter number: ");
group[i] = input.nextInt();
}
I think this is what you're looking for. Inside of the for loop, there's a while loop spinning to keep collecting new ints until you enter one that's not already in the list.
for (int i = 0; i < group.length; i++)
{
System.out.println("Please enter number: ");
int next = input.nextInt();
while(Arrays.asList(group).contains(next)) { // Keep asking for new input while the input is already in list
System.out.println("That number is already in the group ... try again.");
next = input.nextInt();
}
group[i] = next;
}
Since this is clearly a "learning exercise", it is only appropriate to give you hints:
You can search an array by stepping through the array indexes and testing the elements at each index.
A method and a class both need a closing } ...
I need this to be answered in Java only.
That is incorrect. What you REALLY need is some hints. If we give you Java code, you miss out on the important learning experience of writing it yourself. And THAT is the WHOLE POINT of the homework. Go ask your teacher if you don't believe me.
I'm having a little trouble with a simple code. It is suppose to be a program where people can add Notes that get stored in an array. I know this code is long but hopefully some can help me out.
public class NoteOrganizer {
int action = 0;
public static Note[] myArray;
public static void addNotes(int num)
{
String note;
String date;
for(int z = 0; z <= num; z++)
{
Scanner getLi = new Scanner(System.in);
System.out.println("Please enter a note (max 140 characters): \n");
note = getLi.nextLine();
System.out.println("Please enter a date:\n");
date = getLi.nextLine();
Note test = new Note();
test.id = z;
test.myNote = note;
test.date = date;
myArray[z] = test; // THE ERROR IS IN THIS LINE, NOT THE LINE MENTIONED BEFORE
}
}
public static void main(String[] args)
{
int action = 0;
int y = 0;
Scanner getLi = new Scanner(System.in);
System.out.println("Please press 1 to add notes, 2 to delete notes or 3 to view "
+ "all notes:\n");
action = getLi.nextInt();
if(action == 1)
{
System.out.println("How many notes would you like to add: \n");
int d = getLi.nextInt();
//myArray = new Note[d];
addNotes(d);
//System.out.println(myArray[0].print());
}
else if(action == 3)
{
System.out.println(Arrays.toString(myArray));
}
}
}
The error that I am getting is the
Exception in thread "main" java.lang.NullPointerException
at note.organizer.NoteOrganizer.addNotes(NoteOrganizer.java:46)
at note.organizer.NoteOrganizer.main(NoteOrganizer.java:95)
Java Result: 1
I commented which line the error was in.
Any help is greatly appreciated.
Thanks,
You haven't initalized your Note array. It seems you've commented out that line for some reason:
//myArray = new Note[d];
public static Note[] myArray;
myArray[z] = test;
You did not initialize the array, so it is still null.
Once you know the length you need (seems to be num), you can do
myArray = new Note[num];
before using the array.
(It seems you already had code to that effect, but it is commented out for some reason).
You've never set myArray to anything, so you can't write into it.
You're trying to automatically expand an array by writing to it, but that doesn't work in Java. However, an ArrayList does support writing at the end (but not any further), and reallocates its internal array as neccessary:
ArrayList<Note> myList = new ArrayList<Note>();
Then, instead of
myArray[z] = test;
use
myList.add(test);
(which will automatically append to the end of the List, wherever it is)
then read from the list as
myList.get(index)
You need initialize your array, I suggest use the class ArrayList, that is like a dynamic array.
myArray = new Note[length];
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);
}
}