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);
}
Related
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);
}
I'm trying to get some practice with Java before starting a new programming class. To do this, I decided to remake so old Perl programs I made from an earlier class. The original Perl file entered numbers entered by the user into an array and would output the array in four ways: the numbers as entered, ascending order, descending order, and the just the largest and smallest numbers.
I looked through several examples here and elsewhere online to trouble-shoot and while the program compiles, the output is wrong. As is, the array is outputted a couple dozen times, only outputting the numbers as entered. I think I have the four loops set up wrong, but I'm still learning Java so there's likely something I missed. Here's the Java code as it is now:
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayOutPut {
static Scanner input = new Scanner(System.in);
static String convertToString(ArrayList<Integer> numbers) {
StringBuilder builder = new StringBuilder();
for (int i : numbers) {
builder.append(numbers);
builder.append(",");
}
builder.setLength(builder.length() - 1);
return builder.toString();
}
public static void main(String args[]) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
int userInput;
int Largest = 0, Smallest = 0;
System.out.print(
"This program takes a set of integers from the user, and then outputs the results to the screen in four ways:\n");
System.out.print(
"the order they were entered seperated by a comma and a space, in ascending order, in descending order, and as Largest:Smallest.\n\n");
// explain to the user what the program does, needs, etc.
System.out.print("Please enter a number or -1 to end: ");
userInput = input.nextInt();
while (userInput != -1) {
System.out.print("Please enter a number or -1 to end: ");
numbers.add(userInput);
userInput = input.nextInt();
}
// Prints the array contents as entered
String sort = convertToString(numbers);
System.out.println(sort);
// prints numbers ascending
for (int i = 0; i < numbers.size(); i++) {
System.out.println(sort);
}
// prints numbers descending, largest first
for (int i = numbers.size() - 1; i >= 0; i--) {
System.out.println(sort);
}
for (int i = 0; i < numbers.size(); i++) {
int number = numbers.get(i);
if (i < Smallest) {
Smallest = i;
}
if (i > Largest) {
Largest = i;
}
System.out.println(Largest + Smallest);
}
}
}
For additional reference, here's the original Perl program:
#!/usr/bin/perl
use Modern::Perl;
my (#numbers, $userInput);# declare the array and more than one variable at a time
print("\nThis program takes a set of integers from the user, and
\nthen outputs the results to the screen in four ways:
\nthe ordered they were entered seperated by a comma and a space,
\nin ascending order, in descending order, and as Largest:Smallest.\n\n"); # explain to the user what is does, needs, etc
print "Please enter a number or -1 to end: ";
chomp ($userInput = <>); #loop is primed
if ($userInput == -1) {
say "\nThere's no numbers to process.\n";
}
else{
while($userInput != -1) {
push (#numbers, $userInput);
#Push the variable $userInput into #numbers.
print "Please enter a number or -1 to end: ";
chomp ($userInput = <>);
}
}
#Don't declare the #numbers array again, otherwise that'll clear out the entered numbers.
$" = ", ";
print "#numbers\n";
my #upsorted = sort {$a <=> $b} #numbers;
#prints numbers ascending, smallest first.
#Don't use $a, $b, or any number as a variable because they're reserved.
$" = ", ";
print "#upsorted\n";
my #downsorted = sort {$b <=> $a} #numbers;
#prints numbers descending, largest first
$" = ", ";
print "#downsorted\n";
print "$downsorted[0]:$upsorted[0]\n";
#must be set off with a blank line above and below
##End of program
Okay, as a quick update, I've finally gotten the program to run after looking up comparators on tutorialspoint.com. Here's where the code is at now:
import java.util.*;
public class ArrayOutPut {
static String convertToString(ArrayList<Integer> numbers) {
StringBuilder builder = new StringBuilder();
for (int i : numbers){
builder.append(i);
builder.append(",");
}
builder.setLength(builder.length() - 1);
return builder.toString();
}
public static void main(String args[]){
Scanner input = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<Integer>();
int userInput, largest = Integer.MIN_VALUE, smallest = Integer.MAX_VALUE;
System.out.println("This program takes a set of integers from the user, and then "
+ "outputs the results to the screen in four ways:");
System.out.println("the order they were entered seperated by a comma and a space, "
+ "in ascending order, in descending order, and as Largest:Smallest.");
System.out.println();
System.out.print("This program takes a set of integers from the user, and then outputs the results to the screen in four ways:\n");
System.out.print("the order they were entered seperated by a comma and a space, in ascending order, in descending order, and as Largest:Smallest.\n\n");
//explain to the user what the program does, needs, etc.
do {
System.out.print("Please enter a number or -1 to end: ");
userInput = input.nextInt();
if (userInput != -1) {
numbers.add(userInput);
largest = Math.max(largest, userInput);
smallest = Math.min(smallest, userInput);
}
} while (userInput != -1);
//Prints the array contents as entered
String sort = convertToString(numbers);
Comparator cmp = Collections.reverseOrder();
System.out.println(sort);
Collections.sort(numbers);
System.out.println(convertToString(numbers));
Collections.sort(numbers, Comparator.reverseOrder());
System.out.println(convertToString(numbers));
System.out.printf("Smallest = %d, Largest = %d%n", smallest, largest);
}
}
My only concern is that when I compiled, I got a note that says the program uses unchecked or unsafe operations, and that I should recompile with -Xlint:unchecked for details.
First, if using Java 8+, I would use a StringJoiner in convertToString1
static String convertToString(List<Integer> numbers) {
StringJoiner sj = new StringJoiner(",");
numbers.stream().map(String::valueOf).forEach(sj::add);
return sj.toString();
}
Second, you need to sort and call convertToString again to print the results. Prefer variables with lower case names. And you can eliminate the loops with built-in functions. Check that userInput isn't -1 before adding it to your List. And I would prefer a do-while. Something like,
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
List<Integer> numbers = new ArrayList<>();
int userInput, largest = Integer.MIN_VALUE, smallest = Integer.MAX_VALUE;
System.out.println("This program takes a set of integers from the user, and then "
+ "outputs the results to the screen in four ways:");
System.out.println("the order they were entered seperated by a comma and a space, "
+ "in ascending order, in descending order, and as Largest:Smallest.");
System.out.println();
// explain to the user what the program does, needs, etc.
do {
System.out.print("Please enter a number or -1 to end: ");
userInput = input.nextInt();
if (userInput != -1) {
numbers.add(userInput);
largest = Math.max(largest, userInput);
smallest = Math.min(smallest, userInput);
}
} while (userInput != -1);
// Prints the array contents as entered
String sort = convertToString(numbers);
System.out.println(sort);
Collections.sort(numbers);
System.out.println(convertToString(numbers));
Collections.sort(numbers, Comparator.reverseOrder());
System.out.println(convertToString(numbers));
System.out.printf("Smallest = %d, Largest = %d%n", smallest, largest);
}
Update
Based on your edit(s), you're using Java 7 (not Java 8+). In which case, your code (glad to hear it is working), can be "corrected" with a typed Comparator. Something like,
Comparator<Integer> cmp = Collections.<Integer> reverseOrder();
Which will give you an Integer based Comparator in reverse order. However, it's also possible to create a custom Comparator. Such as,
Comparator<Integer> cmp = new Comparator<Integer>() {
#Override
public int compare(Integer o1, Integer o2) {
if (o1 == null) {
return (o2 == null) ? 0 : -1;
}
return o1.compareTo(o2);
}
};
And then you can use it (and reverse it) like
System.out.println(sort);
Collections.sort(numbers, cmp);
System.out.println(convertToString(numbers));
Collections.sort(numbers, cmp.reversed());
System.out.println(convertToString(numbers));
1And, please prefer the List interface over the ArrayList concrete type.
Since you are already using data structures of the java.util package, I can suggest an easy way of sorting the elements in the ArrayList. Provided that numbers is the ArrayList holding all the numbers to work upon, do the following:
Display the numbers in the ArrayList numbers as they are
Make a TreeSet of numbers. A TreeSet automatically sorts its elements in ascending order NOTE: A TreeSet will only hold unique elements. So, if elements inside the list are repeated, they will get deleted. Only a single copy of each element will be stored in the Set.
Re-initialize numbers as the TreeSet made out of numbers. This is because a TreeSet can be displayed only in one order. Now, display the elements of numbers from first to last for ascending order and from last to first for descending order.
Finally, display the first and last elements of numbers as the smallest and largest numbers respectively.
Here's a code.
import java.util.*;
class MyClass{
public static void main(String[] args){
ArrayList<Integer> numbers <--- holds all the numbers
System.out.println("The numbers are:");
for(int i=0; i<numbers.size();i++)
System.out.print(numbers.get(i).intValue()+" ");
TreeSet<Integer> ts = new TreeSet<Integer>(numbers);
numbers = new ArrayList<Integer>(ts);
System.out.println("\nThe numbers in ascending order are:");
for(int i=0;i<numbers.size();i++)
System.out.print(numbers.get(i).intValue()+" ");
System.out.println("\nThe numbers in descending order are:");
for(int i=numbers.size()-1;i>=0;i--)
System.out.print(numbers.get(i).intValue()+" ");
System.out.println("\nThe smallest number is "+numbers.get(0).intValue());
System.out.println("The largest number is "+numbers.get(numbers.size()-1).intValue());
}
}
I tested it with an ArrayList having elements 1 2 5 6 7 and here's the output:
The numbers are:
7 5 6 1 2
The numbers in ascending order are:
1 2 5 6 7
The numbers in descending order are:
7 6 5 2 1
The smallest number is 1
The largest number is 7
I hope this helps.
I want to store a specified number of sequences of integers in an ArrayList.
The number of sequences is going to be defined by the user.
For example, if the user enters 3 then the program will know that there will be 3 sequences inserted.
Each sequence ends when a 0 is inserted. For example, the next user input could be:
1 2 3 0
4 5 6 7 8 0
11 12 0
I want to store these sequences and then do some calculations on each of them. How do I do this?
This is what I have so far:
public static void main (String[] args){
Scanner scan = new Scanner (System.in);
System.out.println("number of sequences: ");
int size = scan.nextInt();
List<Integer> arr = new ArrayList<Integer>();
//How to get the input sequences by sequence?
scan.close();
}
If you want to use ArrayLists, you can use a generic type:
ArrayList<ArrayList<Integer>> myList = new ArrayList<ArrayList<Integer>>();
You can fill this list with ArrayList of Integers.
You can make this new ArrayList of Integers with a for loop, which exits the loop when the given numbers of lists.
For example:
for (int i=0; i < userInputNumber; i++) {
ArrayList<Integer> newList = new ArrayList<Integer>();
// fill the newList object with the user input list of integers
myList.add(newList)
}
here's some semi-pseudo code to help get you started
//beginning number
int numOfSequences = readUserInputAsInt()
//make an array big enough to hold all the sequences
List<Integer>[] sequences = new List<Integer>[numOfSequences];
// read all the next input as one big string
String userInput = readUserInputAsString();
//this method would split the userInput string up by spaces to get each integer
int[] numbers = convertStringToIntArray(userInput);
//put each number in to the correct sequence list
int sequenceNumber = 0;
for(int number : numbers) {
// if we haven't used this sequence before, create a new list to hold it
if(sequences[sequenceNumber] == null){
sequences[sequenceNumber] = new ArrayList<Integer>();
}
// if number is 0, end that sequence, else add the number to the sequence
if(number == 0) {
sequenceNumber++;
} else {
sequences[sequenceNumber].add(number);
}
}
// do work on 'sequences'
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'm just trying to read the input integers from the user for example
2 2 1 1 1 < as a whole
In the debugger, it works places each integer but when
the resulting array is printed something like [I#19eda2c is printed.
public static void main(String[] args) {
int count=0;
int[] array = new int[10];
String input;
Scanner scan = new Scanner(System.in);
System.out.println("Enter up to 10 integers: ");
while(scan.hasNextInt()){
array[count] = scan.nextInt();
count++;
}
System.out.println(array);
}
}
I understand now that it needs to be printed with a for loop or toString method
but I realized when I run the code,
the program waits for me even though the user inputs the integers
is my scanner logistics incorrect?
You need to use java.util.Arrays.toString() method for a 1D array .
or
java.util.Arrays.deepToString() for multi-dimensional arrays.
Your program is fine except that it will read 12 integers if user enters 12 numbers. Your loop needs to run from 0 to 9 to read 10 numbers and not as long as there are tokens in the input
Here is how Arrays.toString() works:
Returns a string representation of the contents of the specified
array. The string representation consists of a list of the array's
elements, enclosed in square brackets ("[]"). Adjacent elements are
separated by the characters ", " (a comma followed by a space).
Elements are converted to strings as by String.valueOf(int)
Here is how Arrays.deepToString() works:
Returns a string representation of the "deep contents" of the
specified array. If the array contains other arrays as elements, the
string representation contains their contents and so on. This method
is designed for converting multidimensional arrays to strings.
For more, read the docs: http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html
You can't print the elements of the array just by System.out.println(array);. Iterate through the array and print each element in the array.
for(int index=0; index < count; index++ )
System.out.println(array[index]);
You are just printing textual representation of array object, use for loop to iterate in array and to display its content.
public static void main(String[] args) {
int count = 0;
int[] array = new int[10];
String input;
Scanner scan = new Scanner(System.in);
System.out.println("Enter up to 10 integers: ");
while (scan.hasNextInt()) {
array[count] = scan.nextInt();
count++;
}
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
System.out.println(array); // prints value from default toString() method
// implementation (e.g. 'className + '#' + hashCode' in Java Oracle)
You should use something like
System.out.println(Arrays.toString(array));
to print values.
Better is to use List instead of array
public static void main(String[] args)
{
List<Integer> array = new ArrayList<Integer>();
String input;
Scanner scan = new Scanner(System.in);
while(scan.hasNextInt())
{
array.add(scan.nextInt());
}
System.out.println("Count=" + array.size());
System.out.println(array);
}