Displaying lists in Java - java

I am trying to create code where the user gets to input whether they want to add a number to a linked list. Every time they add a number, the new linked list gets displayed showing the collection of numbers. Here is the first class:
public class Test {
public static void main(String[] args) {
while(true)
{
LinkedList<Integer> list = new LinkedList<Integer>();
Scanner scan = new Scanner(System.in);
System.out.print("Enter command: ");
String userInput = scan.nextLine();
String [] parts = userInput.split(" ");
String part1 = parts [0];
String part2 = parts[1];
int num = Integer.parseInt(part2);
if (part1.equals("add"))
{
Set test = new Set();
test.addNext(num);
list.add(num);
System.out.println(list.toString());
}
}
}
}
Is there a way to make the list print out like this:
Enter command: add 5
5
Enter command: add 8
8 5
Enter command: add 6
6 8 5

Move
LinkedList<Integer> list = new LinkedList<Integer>();
Scanner scan = new Scanner(System.in);
Outside the while loop, because every iteration list is getting overridden by a brand new one, so naturally it will have only one element every time you print it.
It also seems you want to display the list in reverse order. Normally when you add elements, they are placed at the end of the list. You should use addFirst() to put them at the beginning and get your expected output.

Related

Why do I have to write twice to add an input in the Arraylist?

public static void main(String[] args) {
List<String> arrayList = new ArrayList<>();
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter a product");
String product = input.nextLine();
arrayList.add(product);
}
while (!input.nextLine().equalsIgnoreCase("q"));
System.out.println("You wrote the following products \n");
for (String naam : arrayList) {
System.out.println(naam);
}
}
I'm trying to get some input from the user and store them into arraylist. The problem is I have to write the item twice to add an item into the list. I can't figure out why!
Instead of do-while loop use only while
while (true){
System.out.println("Enter a product");
String product = input.nextLine();
if (!product.equalsIgnoreCase("q"))
arrayList.add(product);
else
break;
}
Every time you write readLine(), a line is read. In this loop,
do {
System.out.println("Enter a product");
String product = input.nextLine();
arrayList.add(product);
}
while (!input.nextLine().equalsIgnoreCase("q"));
There are two occurrences of readLine(), so two lines are read every iteration. The first line is always added to the list and not checked against q, and the second is never added to the list, and always checked against q.
You should only do nextLine once:
while (true) {
System.out.println("Enter a product");
String product = input.nextLine(); // only this one time!
if (!product.equalsIgnoreCase("q")) {
arrayList.add(product);
} else {
break;
}
}
It happenes coz input.nextLine() makes java read the input. You should read the line and only then do the stuff:
Scanner input = new Scanner(System.in);
String product = input.nextLine();
System.out.println("Enter a product");
while (!product.equalsIgnoreCase("q")) {
arrayList.add(product);
System.out.println("Enter a product");
product = input.nextLine();
}
You can read the String values using input.next() once and have a while loop in place and read further values into your list only if the value is not equal to q.
If you have read it twice as in your case, one value is added to the list in your do part, and the value you read again in your while part is only compared to q and so to exit your code, you will be missing one value and adding another and have to give two q values one after another to exit it.
Also, since most of the other users have given there answers with nextLine instead of next you may want to check what next does and what nextLine does. In brief, if you enter names of products separated by a delimiter (default space), then with next, each value separated by the space is considered a product. Similarly, if you enter on different line as well. But, with nextLine, each line as a whole will be added as a new product. It depends on how you may want to achieve this as per your requirement.
public static void main(String[] args) {
List<String> arrayList = new ArrayList<>();
Scanner input = new Scanner(System.in);
String product = input.next();
while(!product.equalsIgnoreCase("q")) {
arrayList.add(product);
product = input.next();
}
System.out.println("You wrote the following products \n");
for (String naam : arrayList) {
System.out.println(naam);
}
}

How to split each input by a new line in Java?

I'm trying get 5 string inputs from the user and those inputs are going to be stored in an array. When I enter something like "Hello World" and hit a new line I can only enter 3 more words. So I want each user input to be a sentence and hitting enter should ask the user for another input on a new line.
Here is my code so far:
Scanner user_input = new Scanner(System.in);
String ask1 = user_input.next()+"\n";
String ask2 = user_input.next()+"\n";
String ask3 = user_input.next()+"\n";
String ask4 = user_input.next()+"\n";
String ask5 = user_input.next();
String[] cars = {ask1, ask2, ask3, ask4, ask5};
According to the documentation, Scanner.next():
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.
As the default delimiter used by Scanner is whitespace, calling next() will get you individual words from user input. When you want to capture multiple words that end with a newline, you should use Scanner.nextLine() instead.
Additionally, you can remove code duplication (which you always should do, keeping things DRY) by creating the array beforehand and allocating the user input entries within a loop:
final int numberOfCars = 5;
Scanner userInput = new Scanner(System.in);
String[] cars = new String[numberOfCars];
for (int i = 0; i < numberOfCars; i++) {
cars[i] = userInput.nextLine();
}
I recommend that you have a certain keyword or phrase that the user can type which stops the program. Here, I made a simple program that uses the java.util.Scanner object to receive keyboard input. Each value is stored in a java.util.ArrayList called "inputs." When the user is done entering input, he/she will type "stop" and the program will stop.
import java.util.*; //you need this for ArrayList and Scanner
public class Input{
public static void main(String[] args){
Scanner user_input = new Scanner(System.in); //create a scanner object
ArrayList<String> inputs = new ArrayList<String>(); //I used a java.util.ArrayList simply because it is more flexible than an array
String temp = ""; //create a temporary string which will represent the current input string
while(!((temp = user_input.next()).equals("stop"))){ //set temp equal to the new input each iteration
inputs.add(temp); //add the temp string to the arraylist
}
}
}
If you want to convert the ArrayList to a normal String[], use this code:
String[] inputArray = new String[inputs.size];
for(int i = 0; i < inputs.size(); i++){
inputArray[i] = inputs.get(i);
}
You can make this more generic by storing your question on an array and looping through a for loop prompting for input until you have question. This why when you have more questions you can add them to list without changing anything else on the code.
Then, to answer your original question regarding creating a String array, you could use following method String[] a = answers.toArray(new String[answers.size()]);
import java.util.ArrayList;
import java.util.Scanner;
public class HelloWorld
{
public static void main(String[] args)
{
ArrayList<String> questions = new ArrayList<String>(5){{
add("What is your name?");
add("What is school you went to?");
add("Do you like dogs?");
add("What is pats name?");
add("Are you batman?");
}};
ArrayList<String> answers = new ArrayList<String>(questions.size()); // initialize answers with the same size as question array
String input = ""; // Stores user input here
Scanner scanner = new Scanner(System.in);
for(String question : questions){
System.out.println(question); // Here we adding a new line and the user type his answer on a new line
input = scanner.nextLine();
answers.add(input); // Store the answer on answers array
}
System.out.println("Thank you.");
String[] a = answers.toArray(new String[answers.size()]); // THis converts ArrayList to String[]
System.out.println("You entered: " + a.toString());
}
}
You want this instead:
Scanner user_input = new Scanner(System.in);
String ask1 = user_input.nextLine()+"\n";
String ask2 = user_input.nextLine()+"\n";
String ask3 = user_input.nextLine()+"\n";
String ask4 = user_input.nextLine()+"\n";
String ask5 = user_input.nextLine();
String[] cars = {ask1, ask2, ask3, ask4, ask5};

Java : Get only 1 line of integers from the console?

I recently picked up Java and I am having an issue with some console input.
Basically, I want to read in an array of ints from the console in a format like this :
1 2 3 4 5 6
I looked through some examples on the forums and decided to do this by using the scanner nextInt() method.
My code currently looks like this :
Scanner get = new Scanner(System.in);
List<Integer> elements = new ArrayList<>();
while (get.hasNextInt()) {
elements.add(get.nextInt());
}
The problem with this code is that the while loop doesn't stop when I hit "Enter" on the console.
Meaning that after I enter some numbers (1 3 5 7) and then hit enter, the program doesn't continue with execution, but instead waits for more integers. The only way it stops is if I enter a letter to the console.
I tried adding !get.hasNextLine() as a condition in my while loop, but this didn't help.
I would be very greatful, if anyone has an idea how can I fix this.
If you want to read only one line the simpliest answer may be the best :)
Scanner in = new Scanner(System.in);
String hString = in.nextLine();
String[] hArray = hString.split(" ");
Now, in array hArray you have all elements from input and you can call them like hArray[0]
You can read one line, and then use that to construct another Scanner. Something like,
if (get.hasNextLine()) {
String line = get.nextLine();
Scanner lineScanner = new Scanner(line);
while (lineScanner.hasNextInt()) {
elements.add(lineScanner.nextInt());
}
}
The Scanner(String) constructor (per the Javadoc) constructs a new Scanner that produces values scanned from the specified string.
Scanner get = new Scanner(System.in);
String arrSt = get.next();
StringTokinizer stTokens = new StringTokinizer(arrSt," ");
int [] myArr = new Int[stTokens.countTokens()];
int i =0;
while(stTokens.hasMoreTokens()){
myArr[i++]=Integer.parseInt(stTokens.nextToken());
}
java-8
You may use the following. User just has to enter each integer without pressing enter and press enter at the end.
Scanner get = new Scanner(System.in);
List<Integer> elements = Stream.of(get.nextLine().split(" "))
.map(Integer::parseInt)
.collect(Collectors.toList());

How to match user input with arraylist

package BankingSystem;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Bank {
public static void main(String [] args){
List<String> AccountList = new ArrayList<String>();
AccountList.add("45678690");
Scanner AccountInput = new Scanner(System.in);
System.out.println("Hi whats your pin code?");
AccountInput.nextLine();
for (int counter = 0; counter < AccountList.size(); counter++){
if (AccountInput.equals(AccountList.get(counter))){ //If Input = ArrayList number then display "hi"
System.out.println("Hi");
}
else { //If not = to ArrayList then display "Incorrect"
System.out.println("Incorrect");
}
}
}
}
Hi, in here I am trying to match the userInput to arrayList, if its correct then display "hi" if not display "Incorrect", for the incorrect part do I to use exception handling? and how can I get it to match the ArrayList number - 45678690?
.nextLine() returns a string which needs to be assigned to a variable ....
And then compare the variable with elements in the arraylist using .contains() method ...
If you also want the index position use .indexOf() method ...
String input = AccountInput.nextLine();
if(AccountList.contains(input))
// do something
else
// do something else
First things first you need to store your user's input into some string as you currently aren't doing that.
Instead of using a counter and iterating through your list you can instead just use
AccountList.contains(the string variable assigned to AccountInput)
If it's false then the entry isn't there, otherwise it's in there. The exception handling you might want to use in this scenario would be to handle a user inputting letters instead of numbers.
You have to store the input value in a string to check the number :
String value = AccountInput.nextLine();
if (value.equals(AccountList.get(counter))) ...
Start variables with lower case. Names that start with upper case is for Classes only in java. So use List<String> accountList , and not List<String> AccountList .
The main problem in your code is that you are comparing the elements in list with the Scanner-object. And that will always be false.
You also never store the input from the Scanner any place.
You need to place the return value somewhere, like
String input = scanner.nextLine();
and compare the strings in the list to this string, not the Scanner-object.
I've added a flag so that it works correctly with multiple items in the accountList.
List<String> accountList = new ArrayList<String>();
accountList.add("45678690");
accountList.add("1");
accountList.add("0");
Scanner scanner = new Scanner(System.in);
System.out.println("Hi whats your pin code?");
String accountInput = scanner.nextLine();
boolean listContainsInput = false;
for (int counter = 0; counter < accountList.size(); counter++){
if (accountInput.equals(accountList.get(counter))){
listContainsInput = true;
break;
}
}
if(listContainsInput) {
System.out.println("Hi");
} else {
System.out.println("Incorrect");
}
You are comparing the instance of the Class Scanner
Scanner AccountInput = new Scanner(System.in);
To a String:
AccountInput.equals(AccountList.get(counter))
(ArrayList.get(int) returns a String or fires an Exception)
You need to start with comparing String to String first:
AccountInput.nextLine().equals(AccountList.get(counter))
If you need additional debbuging see how both strings look like(e.q. print 'em)
Here is documentation on Scanner:
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Read it, scanner is important thing in programming languages.

Print out userinput 1 ,2 ,3 , Array,Java,Eclipse

I'm trying to make a program that asks the user to type in 3 cities and the program
is supposed to take the 3 cities , and put them in a String Array , the first city in
[0],second in [1] and third in [2] , I got it to ask for them , collect the answers
but it's only Printing out the first answer, not all 3. Any ideas how I can fix that?
My code looks like this atm
public static void main(String[] args) {
String ans;
String[] favoritStad = new String [3];
Scanner scanner1 = new Scanner (System.in);
System.out.println("skriv in 3 favoritstäder");
String Användarinlägg1 = scanner1.nextLine();
String Användarinlägg2 = scanner1.nextLine();
String Användarinlägg3 = scanner1.nextLine();
favoritStad[0] = Användarinlägg1;
favoritStad[1] = Användarinlägg1;
favoritStad[2] = Användarinlägg1;
System.out.print(Användarinlägg1);
}
Användarinlägg is userinputt , favorit stad is favcity
the string "ans" was just an idea I tried to make to collect all 3 answers and print it out
but never figured it out
Solved it ! Just needed to add
System.out.print(Användarinlägg2);
System.out.print(Användarinlägg3);
As I suggested in my comment below your question - use a for loop. Also always check twice if you are not using the same variable (for example Användarinlägg1) over and over.
favoritStad[0] = Användarinlägg1;
favoritStad[1] = Användarinlägg2;
favoritStad[2] = Användarinlägg3;
for(int i=0; i<favoritStad.length; i++) {
System.out.println(favoritStad[i]);
}
In your code you've added the same element 3 times.
You need to use:
favoritStad[0] = Användarinlägg1;
favoritStad[1] = Användarinlägg2;
favoritStad[2] = Användarinlägg3;
And in order to print you can use for loop or just:
System.out.print(favoritStad[0]);
System.out.print(favoritStad[1]);
System.out.print(favoritStad[2]);
You can use for loop to print all the values of an array. You can use something like below:
for (int i=0; i&ltfavoritStad.length();i++){
System.out.println(favoritStad[i])
}
Try this way
favoritStad[1] = Användarinlägg2;
favoritStad[2] = Användarinlägg3;
Now Print Array:
1st way :
for(int i=0; i<favoritStad.length; i++) {
System.out.println(favoritStad[i]);
}
2nd way:
for(String s :favoritStad) {
System.out.println(s);
}
Also you need to print...
System.out.print(favoritStad);
instead of
System.out.print(Användarinlägg1);

Categories

Resources