My program is that the ArrayList stores the entered number, and when the user enters the number -1, the program will stop end print out all the entered number in ascending order. My program runs, but let the number enters, it doesn't print the numbers out. it seems like if statement doesn't working. how to call the ArrayList in if statement to work right?
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Collections;
public class testArrayList {
public static void main(String[] args) {
Scanner inputs = new Scanner(System.in);
ArrayList <Integer> nums = new ArrayList<Integer>();
System.out.println("Enter a number(-1 to end): ");
while(inputs.hasNextInt()) {
nums.add(inputs.nextInt());
}
// it looks like it runs until here.
for (Integer n : nums) {
if (n == -1) {
Collections.sort (nums);
System.out.println("Here is the list of numbers : ");
System.out.println(n);
}
}
}
}
System.in will block and wait for a new input, and as long as you continue entering numbers, hasNextInt() will always be true. Instead, you should check for -1 in the initial input (while) loop:
while(inputs.hasNextInt()) {
int num = inputs.nextInt();
if (num == -1) {
break;
}
nums.add(num);
}
nums.sort();
System.out.println("Here is the list of numbers : ");
System.out.println(nums);
Your loop adding numbers to the list don't check for the value -1 to stop the loop. -1 is an int, so it's continuing.
After you've fixed that you will run into the next problem. You're iterating over the elements of the list and do a sort each time the user entered 1. I haven't checked but this will most likely lead to an exception because iterators get not amused if you change the underlying list while iterating over it. According to your description, you should call sort before the loop and then just do the System.out.println within the loop.
My program runs, but let the number enters, it doesn't print the
numbers out. it seems like if statement doesn't working.Trying
performing once step at a time:
In your code, it would do so only is n a value from the list nums is equal to -1.
Instead you should try to put your code as:
// Accept user input
Integer input = inputs.nextInt();
// check if it is not -1
while(input != -1) {
nums.add(input);
input = inputs.nextInt()
}
// sort the arraylist
Collections.sort (nums);
// print the elements
System.out.println("Here is the list of numbers : ");
for (Integer n : nums) {
System.out.println(n);
}
The if statement is never reached, you can check this by adding a println just before it which is never printed if because the scanner ignores whitespace. It will keep trying to take input until you enter a letter. To get the desired effects, I would probably just do n = inputs.nextInt(); then if n is -1 use break. Also your whole for loop and if condition is unnecessary, just sort the list and print it -using .toString because otherwise it will just be a memory address-because you do that in every case (although you may want to remove the -1).
i know there is a few answers, but here's my version :
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Collections;
public class testArrayList
{
public static void main(String[] args)
{
Scanner inputs = new Scanner(System.in);
ArrayList <Integer> nums = new ArrayList<Integer>();
System.out.println("Enter a number(-1 to end): ");
while(inputs.hasNextInt())
{
//check if the next value is -1
int nextVal = inputs.nextInt();
if(nextVal == -1)
{
break; //then exit the loop
}
else
{
nums.add(inputs.nextInt()); //else add to the list
}
}
//since we exited the loop, we can sort the list, and print header
Collections.sort (nums);
System.out.println("Here is the list of numbers : ");
for (int i = 0 ; i < nums.size(); i++)
{
System.out.println(nums.get(i)); // print every sorted int from
// the list
}
}
}
There was a problem with the logic of your code when printing, and also when reading for the -1 exit code. Now it's in the read loop, and then we print the whole sorted list.
tested here :
https://www.jdoodle.com/online-java-compiler
I have reorganized the code and make it much more simpler, as you are trying to exit the map when -1 value is entered.
public class TestArrayList {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList <Integer> nums = new ArrayList<Integer>();
while(true ) {
System.out.println("Enter a number(-1 to end): ");
int value = scanner.nextInt();
/*read until your input is -1*/
if ( value != -1 ){
nums.add(value);
}else {
Collections.sort (nums);
System.out.println("Here is the list of numbers : ");
for ( int i : nums){
System.out.println(i);
}
break;
}
}
scanner.close();
}
}
Scanner inputs = new Scanner(System.in);
ArrayList nums = new ArrayList();
System.out.println("Enter a number(-1 to end): ");
while (inputs.hasNextInt()) {
//Accepts the inputs
int input = inputs.nextInt();
//Checks condition
if (input == -1) {
break;// breaks out of the loop is fails
}
nums.add(input);// else keep adding
}
System.out.println("Here is the list of numbers : ");
Collections.sort(nums);
for (Integer n : nums) {
System.out.println(n);
}
Related
I have made a program that asks:
The length of the array:
and the elements of the Array:
And then the program will multiply the elements.
My question is, how would I prompt the user to just enter the elements of the array without asking for the length and then stop when I type -1? Would I need to use an array list? Here is my code so far.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Length of the array: "); //Prompt User for length
int number = Integer.parseInt(input.next());
System.out.print("The elements of your array: "); //Prompt User for elements
int[] myArray = new int[number];
for(int i = 0; i < number; i++){
myArray[i] = Integer.parseInt(input.next());
}
System.out.printf("The multiplication is %d.", multiplication(myArray, myArray.length - 1) ); //End Statement
}
static int multiplication(int[] array, int startIndex) {
if (startIndex == 0)
return(array[startIndex]);
else
return (array[startIndex] * multiplication(array, startIndex - 1));
}
}
Any help would be appreciated.
First the code, then the explanation (appears after the code, below).
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class MultiplyRecurse {
private static int multiplication(int[] array, int startIndex) {
if (startIndex == 0)
return(array[startIndex]);
else
return (array[startIndex] * multiplication(array, startIndex - 1));
}
/**
* #param args
*/
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner stdin = new Scanner(System.in);
String quit = "Q";
List<Integer> list = new ArrayList<>();
String line = null;
while (!quit.equalsIgnoreCase(line)) {
try {
System.out.print("Enter a number (or 'Q' to quit): ");
line = stdin.nextLine();
if (!line.equalsIgnoreCase(quit)) {
list.add(Integer.valueOf(line));
}
}
catch (NumberFormatException xNumberFormat) {
System.out.println("Not a number. Please try again.");
}
}
int[] myArray = list.stream().mapToInt(i->i).toArray();
System.out.printf("The multiplication is %d.%n",
multiplication(myArray, myArray.length - 1));
}
}
In java int is a primitive. If you look at the code for class ArrayList you will see that it contains a member named elementData which is an array of Object. Hence you can't create an ArrayList object that contains an array of int, so you need to use Integer instead.
Note that if the user enters a number larger than MAX_VALUE, the code Integer.valueOf(line) will throw NumberFormatException.
Your multiplication() method requires a int[] argument, so you need to convert your ArrayList<Integer> to a int[]. The line of code that achieves this is taken from this stackoverflow question:
How to convert List to int[] in Java?
EDIT
Due to OP's comment
List<Integer> numbers = new ArrayList<>();
System.out.print("Enter numbers: ");
while (input.hasNextInt()) {
int number = input.nextInt();
if (number == -1) {
break;
}
numbers.add(Integer.valueOf(number));
}
int[] myArray = numbers.stream().mapToInt(i->i).toArray();
System.out.printf("The multiplication is %d.%n",
multiplication(myArray, myArray.length - 1));
Sample run:
Enter numbers: 8 4 -1 <ENTER>
The multiplication is 32.
After typing -1, hit <ENTER> (on the keyboard).
Yes we can use ArrayList and Array too.Here is an example with ArrayList.
List<Integer> list = new ArrayList<Integer>();
Scanner input = new Scanner(System.in);
System.out.print("The elements of your array: ");
boolean flag = true;
while (flag) {
int val = input.nextInt();
if (val > 0) {
list.add(val);
} else {
flag = false;
System.out.println(list);
}
}
Question 1. (Arrays.java) Write a program that prompts the user to enter in an integer number representing the number of elements (between 2 and 12, use a while loop for input validation) in an arraylist. Create the appropriately-sized array list and prompt the user to enter in values for each element using a for loop. When the array is full, display the following:
The values from the array on a single line (comma separated).
The values from the array on a single line (comma separated) in
reverse order.
The values from the array that have odd numbered values.
The values from the array that have odd numbered indexes. Do not use
an if statement here.
The maximum from the array and the position (index) where it occurs.
here is my code. not sure where goes wrong the for loop doesn't run
import java.util.Scanner;
import java.util.ArrayList;
public class a5q2{
public static void main(String[] args){
Scanner keyb = new Scanner(System.in);
int num = 0;
do {
System.out.println("Enter a number 2 to 12");
num = keyb.nextInt();
} while(num<2||num>12);
ArrayList<Integer>list= new ArrayList<Integer>(num);
//user input
for(int i =0;i<list.size();i++) {
System.out.println("Enter a Value(list): ");
int value=keyb.nextInt();
list.add(value);
}
//display list
System.out.println(list);
//reverse order
for(int i =list.size() - 1;i>=0;i--) {
System.out.println(list.get(i)+",");
}
//all odd value
for(int i =0;i<list.size();i++) {
if(list.get(i)%2==1)
System.out.println(list.get(i)+",");
}
//odd indices
for(int i =0;i<list.size();i+=2) {
System.out.println(list.get(i)+",");
}
}
}
The problem is that the constructor public ArrayList(int initialCapacity):
Constructs an empty list with the specified initial capacity.
(Emphasis mine)
So your loop:
for(int i =0;i<list.size();i++){
System.out.println("Enter a Value(list): ");
int value=keyb.nextInt();
list.add(value);
}
Will never execute as the size is zero.
You can test this by printing out the size before the loop:
System.out.println(list.size());
To fix this, simply loop until num:
for(int i =0;i<num;i++){
System.out.println("Enter a Value(list): ");
int value=keyb.nextInt();
list.add(value);
}
Question :
Sorted?) Write the following method that returns true if the list is already sorted in increasing order. public static boolean isSorted(int[] list) Write a test program that prompts the user to enter a list and displays whether the list is sorted or not. Here is a sample run. Note that the first number in the input indicates the number of the elements in the list.
My try:
import java.util.Scanner;
public class Problem6_19 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number. for the length of the list: ");
int listLength = input.nextInt();
int[] number = new int[listLength];
for(int i = 0; i < number.length; i++) {
System.out.println("Enter a value: ");
number[i] = input.nextInt();
}
if (isSorted(number)) {
System.out.println("The list is sorted!");
} else {
System.out.println("The list is NOT sorted!");
}
}
public static boolean isSorted(int[] list) {
for(int i = 0; i < list.length; i++) {
if (list[i] > list[i + 1]) {
return false;
} else {
return true;
}
}
return false;
}
}
But there's one problem. In the question it prompts the user to enter list and the first element is length of that list. This means that we need to prompt the user only one time. So please explain how is this possible that first element becomes the size of an array??
The Scanner class uses whitespace, any white space, as the delimiter between tokens by default. This means that if the user pressed return between entering numbers then you need to handle that case and ask the user for another number, or the end user would just be on a new line and not know what to do. If the user doesn't press return between entering the numbers but separates them with a space, for example:
1 2 3 4 5
then the scanner would separate that in to 5 separate tokens that would be returned one at once when you call nextInt().
If you run your program and enter something like:
4 2 1 3 4
It should out put four questions asking you to enter inout (that you have already given to it) but then perform the function you want anyway and print "The list is NOT sorted!".
PS. the program doesn't quite work as I imagine you want it to because you as it only checks if the first two values are in ascending order and then returns. Instead you should check to see if the first two are correct, set a flag to keep track of them if they are and then carry on with the loop without exiting. Or only return in the case where the list isn't sorted and if you get to the end of checking the array and you haven't exited it must be sorted and therefore you should return true (as in the code example below). The return statements force your method isSorted to exit as soon as it hits that line, without going through the whole loop. You should also check for going off the end of the array before trying to access i+1. Something like
import java.util.Scanner;
public class ScannerClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number. for the length of the list: ");
int listLength = input.nextInt();
int[] number = new int[listLength];
for(int i = 0; i < number.length; i++) {
System.out.println("Enter a value: ");
number[i] = input.nextInt();
}
if (isSorted(number)) {
System.out.println("The list is sorted!");
} else {
System.out.println("The list is NOT sorted!");
}
}
public static boolean isSorted(int[] list) {
for(int i = 0; i < list.length - 1; i++) {
if (list[i] > list[i + 1]) {
return false
}
}
return true;
}
}
I just learned about array and wanted to build a simple program where I use do-while loops to only accept numbers entered that exist in the array but I'm having some trouble see the problem
Scanner input = new Scanner(System.in);
int[] values;
values = new int[5];
values[0] = 16;
values[1] = 10;
values[2] = 11;
values[3] = 14;
values[4] = 17;
int value;
do {
System.out.println("Enter a number:");
value = input.nextInt();
}
while(value != values[]);
the rest was going to be "if" statements that contained some out going text based on the which numbers from the array are entered. The "while" condition comes up in an error in the way I entered it as
EDIT: Since this isn't possible in java could I just write !=16,10,11,14,17 without getting an error? The array won't work in the condition so I'm still stuck in figuring a way to including multiple numbers in the condition
The termination condition of your do loop:
while(value != values[])
is not legal Java. You cannot compare an int value to an array and you cannot reference an array using values[]. I don't know what you're trying to accomplish, but you need to put in a specific subscript in the termination condition or modify it in some other way.
As you see it's not possible to just write while(value != values[]) but you can search a value in an array or check if the value is contained in a List:
--- First way
Using a List of integers:
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class InArrayWithAsListContains {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int value=0;
List<Integer> values = new ArrayList<Integer>();
values.add(16);
values.add(10);
values.add(11);
values.add(14);
values.add(17);
do {
System.out.println("Enter a number:");
value = input.nextInt();
} while(!values.contains(value));
}
}
A variation to work with a List starting with int[]:
int[] arr = new int[] {16,10,11,14,17};
// int[] into List<Integer> conversion
for (int i : arr) values.add(i);
--- Second way
Just using arrays and Arrays.binarySearch(values, key)
import java.util.Scanner;
import java.util.Arrays;
public class Program {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int value=0;
int[] values = {16,10,11,14,17};
Arrays.sort(values);
do {
System.out.println("Enter a number:");
value = input.nextInt();
} while(Arrays.binarySearch(values, value) < 0);
}
}
An int is not the same thing as an int[]
I am asked to print multiples of 2 only with a never ending loop.
Attempt:
import java.util.Scanner;
public class Infiniteloop {
public static void main (String [] args)
{
Scanner input=new Scanner (System.in);
int number,x;
System.out.print("Enter a number");
number=input.nextInt();
if(number%2==0)
{
while(number>=0)
{
x= (++number);
System.out.println(x);
}
}
}
}
I can only use while-loop. So I tried to set the remainder of 2 equal to zero. I tried using the counter but it doesnt increment it. Keeps printing out zeros. I need some help. Thanks.
Supposing that you want to prompt the user for a start number and then print all the following even numbers:
number = input.nextInt(); //read the input
number += number % 2; //if input is odd, add 1
while (true)
{
System.out.println (number);
number += 2;
}
Supposing you want to check for even numbers:
while (true)
{
number = input.nextInt();
if (number % 2 == 0) System.out.println (number);
}
Or if you don't care about empty lines:
while (true) System.out.println (input.nextInt () % 2 == 0 ? "even" : "");
EDIT: Same thing for powers of two:
public static void main (String [] args)
{
Scanner input = new Scanner (System.in);
int number;
while (true)
{
System.out.print ("Enter a number");
number = input.nextInt ();
while ( (number & 1) == 0) number >>= 1;
if (number == 1) System.out.println ("Perfect divisor.");
}
I am surprised this compiles.
x= (++number)
has no semi-colon at the end.
also, move the if statement inside of the while. If you are checking for multiples of 2, you will want that check after each iteration of the loop
edit: you changed your original code. Please copy/paste from your source instead of re-typing.
Question is not very clear but may be something like this would help you:
Scanner input=new Scanner (System.in);
int number;
do {
System.out.print("Enter a number: ");
number=input.nextInt();
if(number%2==0)
System.out.println(number);
} while (number > 0);
An infinite loop does not need a counter. It can be written like this:
if((number % 2) != 0) {
number++;
}
while(true) {
System.out.println(number);
number = number + 2;
}
edit: Added infinitely finding multiples of 2
I'm guessing that this is a homework question, so perhaps explaining the methodology will help you more than a full answer.
Firstly, you can use a while loop to ensure that your code gets executed more than once:
while loop
A while loop will keep executing the code inside it while the given boolean condition evaluates to true. So, you can wrap up your code with:
while(true) {
//...
}
and anything between the brackets will continually execute (line by line) forever.
If you get a number from the user at the beginning of the loop, the loop will stop executing any further code until the user types something (it will be blocked, waiting on IO).
Once you get the number, the loop will start executing the rest of the code, before returning to the top of the loop and repeating the process.
while (true) {
//ask user for number
//print out the number
// check that it is even
// print whether it is even or odd
}
class Fordemo
{
public static void main(String args[])
{
int k,x=0;
for(k=1;k<=10;k++)
{
x=k*2;
System.out.println("multiple of 2 is "+x);
}}}