I am trying to make a functioning to do list with a limit of 10 elements, however I am having an issue with two major things in the to do list.
The first is that after I first compile and run the program and select to add elements to the list, that functions properly, but if I add two elements and the 'stop' sentinel, when I select the next option to print the to do list, I am presented with a list, showing my two elements and then the stop sentinel along with 7 null values in the list. So the first issue I am having is to get rid of the null values, I attempted using a counter as you can see in my code however that was not proving to be effective.
The next issue that I am having is that I am trying to make it so that you can add to the list, so once you select to add more things to the list, the new options the user writes, rewrites over them in the array and prints out the new values and not along with the old ones. I am assuming that can be done through some sort of recursion method but I am having a hard time figuring it out.
Any help would be greatly appreciated!
Thanks!
import java.util.Scanner;
public class ToDo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
final int MAX = 10;
String[] list = new String[MAX];
int choice = 0;
while (choice != 3) {
System.out.println();
System.out.println("Type 1 to add a new thing to your to do list.");
System.out.println("Type 2 to print the to do list.");
System.out.println("Type 3 to exit the program.");
System.out.print("Select an option: ");
choice = input.nextInt();
int count = 0;
if (choice == 1) {
System.out.println("Keep hitting enter after to do's, if you want to stop, type 'stop'.");
for (int i=0;i<MAX;i++) {
list[i] = input.nextLine();
if (list[i].equals("stop")) break;
count++;
}
}
if (choice == 2) {
for (int index = 0;index < list.length; index++) {
System.out.println(list[index]);
}
}
}
}
}
As I have mentioned in the comment, you can use an ArrayList instead of String[] to make your processing much easier.
But if you want to use the array itself, there are 3 minor issues with your code.
In your choice 1 for loop, start the loop from count,
for (int i=count;i<MAX;i++) {
list[i] = input.nextLine();
if (list[i].equals("stop")) break;
count++;
}
In your choice 2 for loop, end the loop before reaching count,
for (int index = 0;index < count; index++) {
System.out.println(list[index]);
}
And move your count initialization outside the while loop.
int count = 0;
But beware, if you decide to implement removing tasks, this could get complicated and using ArrayList would become much simpler.
Instead of using a fixed size array of Strings, use an ArrayList of Strings. Then you can add elements to it as you go.
Make sure to
import java.util.ArrayList;
Declaration syntax is
ArrayList<String> myList = new ArrayList<String>();
Add elements to your list with the add() method:
myList.add(input.nextLine())
You don't need that inner for loop, instead break out of the while loop of input options when you've iterated through it 10 times.
To solve your problem of "stop" being in your list, check that the input is "stop", and stop, before you attempt to add to the list.
It is better to use ArrayList but if you still want to stick to String[] then the following program will work for you:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
final int MAX = 10;
String[] list = new String[MAX];
int choice = 0;
while (choice != 3) {
System.out.println();
System.out.println("Type 1 to add a new thing to your to do list.");
System.out.println("Type 2 to print the to do list.");
System.out.println("Type 3 to exit the program.");
System.out.print("Select an option: ");
choice = input.nextInt();
String userEnteredItem;
if (choice == 1) {
System.out.println("Keep hitting enter after to do's, if you want to stop, type 'stop'.");
for (int i=0;i<MAX;i++) {
userEnteredItem = input.nextLine();
if(!userEnteredItem.isEmpty()) {
list[i] = userEnteredItem;
if (userEnteredItem.equals("stop")) {
break;
}
count++;
} else {
i--; // Do not increase index for empty item.
}
}
}
else if (choice == 2) {
for (int index = 0;index < count; index++) {
System.out.println(list[index]);
}
}
else {
input.close();
}
}
}
It keeps track of user items in static int count and it also closes the scanner when you do not need it.
Related
Confused on this exercise, its asking me to create a loop which remembers multiple integers that the user inputted, and prints them out the exact same way. I'm confused on how to print the input without making it a list and not using any methods. I tried making input equal to i, but that doesn't output anything.
public static void main(String[]args) {
Scanner scanner = new Scanner(System.in);
int i = 0;
int i2 = 0;
ArrayList <Integer> name_input = new ArrayList<>();
while(true) {
System.out.print("print number:");
int input = Integer.valueOf(scanner.nextLine());
name_input.add(input);
if (input == -1) {
break;
}
i++;
}
while(i2 < i){
System.out.println(i);
i2++;
}
}
Original question: The exercise template contains a base that reads numbers from the user and adds them to a list. Reading is stopped once the user enters the number -1.
Expand the functionality of the program so that after reading the numbers, it prints all the numbers received from the user. The number used to indicate stopping should not be printed.
I've tried the following but am not getting any output:
ArrayList<String> list=new ArrayList ();
Scanner s=new Scanner(System.in);
for(int i=0; i<list.size(); i++)
{
System.out.println("Enter string "+(i+1));
String se = s.next();
list.add(se);
}
for(int i=0; i<list.size(); i++)
{
System.out.print(list.get(i));
}
You need to loop on your Scanner input until you get an empty line, not on your List. Your List is empty to start with so you will not enter your loop.
List<String> list = new ArrayList<>();
Scanner s = new Scanner(System.in);
int counter = 1;
String userInput;
System.out.println("Enter string "+ counter);
while (true) { // Infinite loop, you need a break inside of the loop to get out of it
// Assign the input value to the userInput variable
userInput = s.nextLine();
// Stop looping when it is an empty line
if (userInput.isEmpty()) {
break;
}
list.add(userInput);
counter++;
System.out.println("Enter string "+ counter);
}
for (String st : list) {
System.out.println(st);
}
here the size is specified by the user...
now it works...
ArrayList<String> list=new ArrayList ();
Scanner s = new Scanner(System.in);
System.out.println("How many strings to add");
int a = s.nextInt();
for(int i=0; i<a; i++)
{
System.out.println("Enter string "+(i+1));
String se = s.next();
list.add(se);
}
for(int i=0; i<list.size(); i++)
{
System.out.print(list.get(i));
}
The reason you are not getting any output is because you are using list.size() as a comparison value in a loop before you've populated the list with elements. It is empty so it's size will always be 0 until you add some elements to it.
Returns the number of elements in this list. If this list contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.
The quote above is from the List Javadoc. Keep in mind that it's always a good idea to read the documentation of new concepts you are trying to use.
You can't use a for-loop on the list's size for the purpose of creating the list in the first place. You need to have some other control mechanism, such as a while-loop that continues until the user enters some sort of "finished" value.
So instead of using the list size (like the comment above states) you should be using another control mechanism like a local variable which can define the size of your list. It can also be used to set the initial capacity of your list.
// Use this local variable as a control mechanism
final int listSize = 10;
// Create new array with the initial capacity set to 10
List<String> list = new ArrayList<>(listSize);
Scanner s = new Scanner(System.in);
// Use a dedicated integer value for the loop
for(int i = 0; i < listSize; i++)
{
System.out.println("Enter string " + (i+1));
String se = s.nextLine();
list.add(se);
}
// Once the list has been populated we can use it's
// size as a comparison value in a loop
for(int i = 0; i < list.size(); i++)
{
// Print each string in a new line
System.out.println(list.get(i));
}
Couple of notes that might help you in the future:
Use System.out.println instead of System.out.print whenever you want to print each log in a separate line.
Format your code in a readable manner so it's easier for both you and others to review it. In my opinion this includes separating each element in a syntax with at least a single whitespace as well as following the proper naming convention.
First loop in your code tries to iterate over values between 0 and list.size() - also 0, because your list is empty.
In this example your program will keep asking for string unless user provide STOP_WRITING_CODE value which is exit.
static final String STOP_WRITING_CODE = "exit";
ArrayList<String> list=new ArrayList();
Scanner s=new Scanner(System.in);
String se = "";
while (true) {
System.out.println("Enter string: ");
se = s.next();
if(se != STOP_WRITING_CODE)
break;
list.add(se);
}
for(int i=0; i < list.size(); i++) {
System.out.print(list.get(i));
}
So I'm doing some random practice for an upcoming exam, and I don't know if it's the fact that I've been reviewing for hours and my brain isn't functioning, or something in this code is wrong.
I'm attempting to make a very simple java program that asks the user for the amount of numbers they wish to enter (totalNum), create an array that long, and then ask the user for each individual value. After it asks the user for each value in the array, it prints the array.
Here is my code:
import java.util.Scanner;
public class Practice1 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("How many numbers would you like to store?");
int totalNum = s.nextInt();
int[] numbers= new int[totalNum];
for (int i = 0; i>totalNum; i++) {
System.out.println("Number" + i + " :");
numbers[i] = s.nextInt();
i++;
}
numbers.toString();
System.out.println(numbers);
}
}
When I run it it asks the user for the numbers I want to store, then prints [I#33909752 and stops. I've done dozens of programs like this and for the life of me I can't figure out where I went wrong.
Any help would be appreciated, thanks!
Your loop test is backwards. This
for (int i = 0; i>totalNum; i++) {
should be
for (int i = 0; i < totalNum; i++) {
as is, the test evaluates to false and the loop isn't entered. And, don't increment i in the loop body (that's what i++ does in the for). Finally,
System.out.println(numbers);
isn't going to print the array correctly, because arrays don't override Object.toString(). You can use Arrays.toString like
System.out.println(Arrays.toString(numbers));
i>totalNum is the problem. The for loop will not execute even once.
The for loop has three parts:
The action to perform before starting the loop
The condition
The action to perform after each loop
Your condition is i>totalNum, which is false for i=0 and totalNum=1. The loop won't execute even once.
The i++ is already mentioned in the loop, you do not need to include it in the loop body anymore.
The unexpected output is the caused by the default toString()-method of Array. Use Arrays.toString() for a readable output.
Your loop condition should be
for (int i = 0; i<totalNum; i++) {
and within loop don't increment variable i
use below for your desired result.
public class Practice1 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("How many numbers would you like to store?");
int totalNum = s.nextInt();
int[] numbers= new int[totalNum];
for (int i = 0; i<totalNum; i++) {
System.out.println("Number" + i + " :");
numbers[i] = s.nextInt();
i++; //remove this
}
numbers.toString();
System.out.println(Arrays.toString(numbers));
}
}
public class Sort {
public static void main(String[] args) {
int i = 1;
Scanner input = new Scanner(System.in);
// prompts the user to get how many numbers need to be sorted
System.out.print("Please enter the number of data points: ");
int data = input.nextInt();
// this creates the new array and data sets how large it is
int [] userArray = new int[data];
// this clarifies that the value is above 0 or else it will not run
if (data < 0) {
System.out.println("The number should be positive. Exiting.");
}
// once a value over 0 is in, the loop will start to get in all user data
else {
System.out.println("Enter the data:");
}
while (i <= data) {
int userInput = input.nextInt();
userArray[i] = userInput;
i++;
}
// this calls the sortArray method to sort the values entered
sortArray(userArray);
// this will print the sorted array
System.out.println(Arrays.toString(userArray));
}
}
I have set the array size equal to what the user inputs for how many variables they will be entering to be sorted. For some reason, Java only wants a set number instead of the number that is entered by the user. Is there a way to make this work?
First of all, there are a few mistakes in your code. You are checking if(data < 0) after you create your array with int[] userArray = new int[data];. You should check it before.
Furthermore, you will get ArrayIndexOutOfBoundsException because userArray[data] does not exist. Array indices start at 0, so the last index is data-1. You need to change your while-loop to while(i < data) instead of while(i <= data).
The problem is not that you have data instead of 10 as the length of the array. The problem is as I stated above: your while-loop.
Your issue is the while loop. Because arrays are 0 based and you need to only check if i < data. By setting it to <=, you are exceeding the array length and generating and ArrayIndexOutOfBoundsException
while (i < data) {
int userInput = input.nextInt();
userArray[i] = userInput;
i++;
}
You are over-indexing the array. A more standard way for inputting the data would be
for ( int i=0; i < data; i++ ) {
userArray[i] = input.nextInt();
}
I am self-learning Java and am stuck on a simple project. I'd like to receive 6 unique 'lottery' numbers from a user.
User will be asked to input an integer.
Each user input will be placed into an array.
If the user inputs a previously input number, I want to prompt to reenter the number again.
Recheck the new input. If unique, continue the for loop. If non-unique, run step 3 again.
So far, all I have is:
public static int[] userLottoInput()
{
int[] userNums = new int[6];
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < userNums.length; i++ ) {
System.out.printf("Enter Lottery number %d: ", i + 1);
userNums[i] = keyboard.nextInt();
for (int k=i; k<userNums.length; k++) {
while (k!=i && userNums[k] == userNums[i]) {
System.out.printf("if");
System.out.printf("Error! Try again: ");
userNums[i] = keyboard.nextInt();
}
}
}
}
Any help is appreciated!!
Try and keep you logic simple.
While the user hasn't enter 6 numbers, loop
Ask the user for a value
Check to see if it's a duplicate
If it is, ask the user to re-enter the value
If it's not (a duplicate) increment the counter to the next element...
For example...
public static int[] userLottoInput() {
int[] userNums = new int[6];
Scanner keyboard = new Scanner(System.in);
int i = 0;
// Keep looping until we fill the array, but
// allow the control to fall somewhere else
while (i < userNums.length) {
System.out.printf("Enter Lottery number %d: ", i + 1);
userNums[i] = keyboard.nextInt();
// Check for duplicates
boolean duplicate = false;
// We only need to check up to i - 1, as all the
// other values are defaulted to 0
// We also don't need to check for the last number entered ;)
for (int k = 0; k < i; k++) {
// Check for duplicated
if (userNums[k] == userNums[i]) {
System.out.println("No duplicates allowed, please try again");
duplicate = true;
// Break out of the loop as we don't need to check any more..
break;
}
}
// If no duplicates where found, update i to the next position
if (!duplicate) {
i++;
}
}
return userNums;
}
With this, there is only one point at which you prompt the user. Everything else is used to control the element position (i) to meet your requirements.
Now, I'm sure that there are other ways to do this and this is just a simple example ;)
Move the asking of number outside loop, when received the number loop over the numbers array to find a match. If match found re-ask for number (outside the for loop used for finding the match), else if match not found, then add the number to array.
Don't you think your for loop is little complicated. Anyways, you can try this :
for (int k=0; k<i-1; k++) { //Start k=0 means from the first stored value
while (k!=i && userNums[k] == userNums[i]) {
System.out.printf("if");
System.out.printf("Error! Try again: ");
userNums[i] = keyboard.nextInt();
}
}