I want to have an ArrayList that records user entries and ends when it receives a non-integer value but I am getting an infinite loop and I don't know why.
public class Tryout1
{
public static void main(String[] args)
{
ArrayList entries = new ArrayList();
Scanner obj1 = new Scanner(System.in);
System.out.println("enter numbers");
int i = obj1.nextInt();
boolean accumulating = obj1.hasNextInt(); //check int
while(accumulating) {
entries.add(i);
}
System.out.println(entries);
}
}
you should move your check inside the loop, so it will check every time before the next loop is executed.
In your code, the check is only performed once.
public class tryout1 {
public static void main(String[] args) {
ArrayList entries = new ArrayList();
Scanner obj1 = new Scanner(System.in);
System.out.println("enter numbers");
do {
// get the next int
int i = obj1.nextInt();
entries.add(i);
} while (obj1.hasNextInt()); // <- check here for nextInt
System.out.println(entries);
}
}
Related
How do I make this program run until the user enters a specific key, lets say x, to terminate the program?
public class NestedLoopTableApp {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Input Table Numbers [one at a time]");
int valueOne = sc.nextInt();
int valueTwo = sc.nextInt();
NestedLoopTable np = new NestedLoopTable(valueOne, valueTwo);
np.printTable();
sc.close();
}
}
Just add your code block into the while loop and add a condition
while(sc.nextLine().equals("x")) {
//...... your code here
}
Thanks,
Vijay Kareliya
I am trying to create a program that takes user inputs stores them into an Arraylist and the prints the Arraylist out after user inputs a certain string. my current problem is that i cant get the user inputs to stop and print out. i think what i have currently have is a strong base, i cant see what is wrong.
import java.util.ArrayList;
import java.util.Scanner;
public class GroceryArraylist {
public static void main(String[] args) {
ArrayList<String> Grocerylist = new ArrayList<String>();
Scanner input = new Scanner(System.in);
System.out.print("Enter an item, enter end to stop ");
while (!input.equals("end")) {
Grocerylist.add(input.next());
if (Grocerylist.equals("end")){
for(String str:Grocerylist)
System.out.println(str);
}
}
}
}
Here is the mistake:
Grocerylist.equals("end")
GroceryList is of type ArrayList and it will never be equal to the string "end". It's like comparing apples with oranges.
You could try this instead:
while (!input.equals("end")) {
String input = input.next();
Grocerylist.add(input);
if ("end".equals(input)){
for(String str:Grocerylist)
System.out.println(str);
}
break;
}
You can use hasNext command to avoid including "end" into the array.
public class GroceryArraylist {
public static void main(String[] args) {
ArrayList<String> Grocerylist = new ArrayList<String>();
Scanner input = new Scanner(System.in);
System.out.print("Enter an item, enter \"end\" to stop ");
while (input.hasNext()) {
Grocerylist.add(input.next());
if(input.hasNext("end")) {
System.out.println(Grocerylist);
break;
}
}
}
}
Or you can use a do-while loop instead of:
public class GroceryArraylist{
public static void main(String[] args) {
ArrayList<String> Grocerylist = new ArrayList<>();
Scanner input = new Scanner(System.in);
System.out.print("Enter an item, enter \"end\" to stop ");
do {Grocerylist.add(input.next());}
while (!input.hasNext("end"));
System.out.println(Grocerylist);
System.exit(0);
}
}
I am trying to make a three different linked list. I will determine the first ones inputs but for the other two I want to ask the user for the inputs and then insert them into a linked list. Can anyone help me with how to do that? So far I could only write this code
package homework001;
import java.util.Scanner;
import java.util.List;
import java.util.LinkedList;
import java.util.ListIterator;
public class morph {
public static LinkedList<String> list;
public static void main(String[] args){
LinkedList<String> list = new LinkedList<>();
list.add("10");
list.add("34");
list.add("1");
list.add("97");
list.add("5");
list.add("62");
}
}
I think we can simply take user input in LinkedList by using
this method -> listname.add(sc.nextInt());
code for the implementation is below! thank you :)
public class LL_userInput {
public static void main(String[] args) {
LinkedList<Integer> ll = new LinkedList<>(); //creating list
Scanner sc = new Scanner(System.in); //creating scanner for total elements to be inserted in list
System.out.println("enter total count of elements -> ");
int num = sc.nextInt(); // user will enter total elements
while(num>0) {
ll.add(sc.nextInt());
num--; // decrement till the index became 0
}
sc.close();
System.out.println(ll);
}
}
Using scanner, you can get input from any source. To read from console use
Scanner sc = new Scanner(System.in);
while(!sc.hasNextInt()) sc.next();
int number = sc.nextInt();
for(i=0; i< number; i++)
myList.add(sc.next());
I think you don't understand from the comments here is a simple example ;
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();//declare your list
Scanner scan = new Scanner(System.in);//create a scanner
System.out.print("Enter the Nbr of element : ");
int nbr = scan.nextInt();//read the number of element
scan.nextLine();
do {
list.add(scan.nextLine());//read and insert into your list in one shot
nbr--;//decrement the index
} while (nbr > 0);//repeat until the index will be 0
scan.close();//close your scanner
System.out.println(list);//print your list
}
import java.util.*;
class LinkedList{
public static void main(String[] args) {
Scanner sc= new Scanner (System.in );
LinkedList<Integer>list=new
LinkedList<>();
System.out.println("Enter how many
elements you want");
int num=sc.nextInt();
for(int i=0;i<num;i++){
System.out.println("Enter element
at index "+i);
list.add(sc.nextInt());
}
System.out.print(list+" ");
}
}
Last objective of my assignment asks to create a method matches(). It receives another GenericMemoryCell as a parameter, and returns true if both of its stored values can be found in the stored values of the current GenericMemoryCell. Order of stored values is not important.
Creating the method was not difficult, but I am lost on how to call it from main() because I cannot wrap my head around the concept of passing another instance of GenericMemoryCell. Where am I getting another pair of storedValueA and storedValueB in the first place? Is matches() "running" a virtual instance of the entire program within itself?
import java.util.*;
public class GenericMemoryCell<T>{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter valueA: ");
String readerA = input.next();
System.out.print("Enter valueB: ");
String readerB = input.next();
GenericMemoryCell<String> values = new GenericMemoryCell<>(readerA, readerB);
System.out.println("storedValueA: " + values.readA());
System.out.println("storedValueB: " + values.readB());
values.writeA(readerA);
values.writeB(readerB);
}
public GenericMemoryCell(T storedValueA, T storedValueB)
{ this.storedValueA = storedValueA; this.storedValueB = storedValueB; writeA(storedValueA); writeB(storedValueB); }
public T readA()
{ return storedValueA; }
public T readB()
{ return storedValueB; }
public void writeA(T x)
{ storedValueA = x; }
public void writeB(T y)
{ storedValueB = y; }
public boolean matches(GenericMemoryCell<T> that){
return (this.storedValueA.equals(that.storedValueA) && this.storedValueB.equals(that.storedValueB)); }
private T storedValueA, storedValueB;
}
I think you need something like this
public class GenericMemoryCell {
public static void main(String[] args) {
GenericMemoryCell g1 = new GenericMemoryCell();
//set g1 values here
GenericMemoryCell g2 = new GenericMemoryCell();
//set g2 values here
System.out.println(g1.matches(g2));
}
public boolean matches(GenericMemoryCell g) {
//implement the logic here
return ...;
}
}
Hopefully, it might work for you. However, if you want system to ask for inputs repeatedly, you need to some kind of loop.
public class GenericMemoryCell {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter first input: ");
int firstInput = scanner.nextInt();
System.out.println("Please enter second input");
int secondInput = scanner.nextInt();
list.add(firstInput);
list.add(secondInput);
Scanner scannerObj = new Scanner(System.in);
System.out.println("Please enter first input: ");
int firstArg = scannerObj.nextInt();
System.out.println("Please enter second input: ");
int secondArg = scannerObj.nextInt();
boolean isMatches = isInputMatches(firstArg, secondArg, list);
if (isMatches) {
System.out.println("These inputs were already stored before. Please try again with different inputs");
} else {
System.out.println("The inputs are successfully stored. Thank you.");
}
scanner.close();
scannerObj.close();
}
private static boolean isInputMatches(int firstArg, int secondArg, List<Integer> list) {
return list.contains(firstArg) && list.contains(secondArg);
}
}
I have a Student class which has
private String name;
private long idNumber;
and getters and setters for them.
I also have a StudentTest class which has three different methods, 1. to ask user for the size of the array and then to create an array of type Student, 2. to ask user to populate the array with names and ID numbers for as long as the array is, 3. to show the contents of the array.
The code I have so far is;
import java.util.Scanner;
public class StudentTest {
// Main method.
public static void main(String [] args) {
}
// Method that asks user for size of array.
public static Student[] createArray() {
System.out.println("Enter size of array:");
Scanner userInputEntry = new Scanner(System.in);
int inputLength = userInputEntry.nextInt();
Student students[] = new Student[inputLength];
return students;
}
// Method that asks user to populate array.
public static void populateArray(Student [] array) {
}
// Method that displays contents of array.
public static void displayArray(Student[] array) {
}
}
I'm not sure as to how to tackle the second method of asking the user to populate the array, any help will be greatly appreciated :)
This may help you
public static Student[] createArray() {
System.out.println("Enter size of array:");
Scanner userInputEntry = new Scanner(System.in);
int inputLength =userInputEntry.nextInt();
Student students[] = new Student[inputLength];
return students;
}
public static void populateArray(Student [] array) {
for(int i=0;i<array.length().i++)
{
array[i]=new Student();
System.out.println("Enter Name");
Scanner userInputEntry = new Scanner(System.in);
array[i].setName(userInputEntry .next());
System.out.println("Enter Id");
array[i].setIdNumber(userInputEntry .nextLong());
}
}
The easiest solution is probably a loop, in which you ask the user for input and then store it in your array.
Something like:
for(int i = 0; i < students.length(); i++){
[Ask for input and store it]
}
i suppose something like this:
// Method that asks user to populate array.
public static void populateArray(Student [] array) {
for(int i = 0; i < array.lenght;i++) {
array[i]=new Student(name, id); //put here student name/id
}
}