Reading input as array - java

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);
}

Related

java arraylist question where is wrong with my code

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);
}

Create java list from user input

I have a bit of a unique problem to solve and I'm stuck.
I need to design a program that does the following:
Inputs two series of numbers (integers) from the user.
Creates two lists based on each series.
The length of each list must be determined by the value of the first digit of each series.
The rest of the digits of each series of numbers becomes the contents of the list.
Where I'm getting stuck is in trying to isolate the first number of the series to use it to determine the length of the list.
I tried something here so let me know if this is what you're looking for. It would be better for you to provide your attempt first.
I also want to point out that Lists are for the most part dynamic. You don't have to worry about the size of them like a normal array.
Scanner sc = new Scanner(System.in);
ArrayList<Integer[]> addIt = new ArrayList<>();
boolean choice = false;
while(choice == false){
String line = sc.nextLine();
if(line.equalsIgnoreCase("n")){
break;
}
else{
String[] splitArr = line.split("\\s+");
Integer[] convertedArr = new Integer[splitArr.length];
for(int i = 0; i < convertedArr.length; i++){
convertedArr[i] = Integer.parseInt(splitArr[i]);
}
addIt.add(convertedArr);
}
}
This is assuming that you are separating each integer with a whitespace. If you are separating the numbers with something else just modify the split statement.
The user enters "n" to exit. With this little snippet of code, you store each array of Integer objects in a master ArrayList. Then you can do whatever you need to with the data. You can access the first element of each Integer object array to get the length. As you were confused how to isolate this value, the above snippet does that for you.
I would also advise you to add your parse statement in a try-catch block to provide error handling for invalid input that cannot be parsed to an integer.
This is one way of doing it with default arrays.
import java.util.Scanner;
public class ScanList {
public static void main(String[] args){
System.out.println("Array:");
Scanner s = new Scanner(System.in);
String line = s.nextLine();
String[] nums = line.split(",");
int[] result = new int[Integer.parseInt(nums[0])];
for(int i = 0; i<result.length;i++){
result[i]=Integer.parseInt(nums[i+1]);
}
for(int r:result){
System.out.println(r);
}
}
}
This is what I came up with:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Insert the first series of numbers: ");
String number1 = input.nextLine();
System.out.println("Insert the second series of numbers: ");
String number2 = input.nextLine();
String[] items = number1.split(" ");
String[] items2 = number2.split (" ");
List<String> itemList = new ArrayList<String>(Arrays.asList(items));
itemList.remove(0);
Collections.sort(itemList);
System.out.println(itemList);
} // End of main method

How to store a specified number of sequences of integers in an ArrayList in java?

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'

Java Homework Reverse Array

Details of my Homework
Topic: Single Dimensional Array
Write a java program that first read in the size of a one dimensional array, read in each array element of double type, reverses the order of this one-dimensional array.
Do not create another array to hold the result.
Hint: Use the code in the text for exchanging two elements.
Sample Output:
Please input the size of array: 4
Please input 4 double numbers: 1.0, 2.0, 3.0, 4.0
After reverse order: 4.0, 3.0, 2.0, 1.0
I have 2 problems with my assignment. Wondering if anyone can help me find a solution.
I need to fill the values of an array (double[] myArray) using
Scanner input from a single line for multiple doubles.
I need to reverse the order of the values inside the array WITHOUT
using a 2nd array.
This is my code so far.
Scanner sc = new Scanner(System.in);
System.out.println("Please input the size of array: ");
int arraySize = sc.nextInt(); //Stores user input
double[] myArray = new double[arraySize]; //Create array[userInput]
System.out.print("Please input " + arraySize + " double numbers: ");//Collect user input
int j = 0;
while (sc.hasNext()) { //Another Failed Attempt to collect the input from a single line
if (sc.hasNextDouble()) {
myArray[j] = sc.nextDouble(); //Insert user input into array
j++;
}
}
Collections.reverse(Arrays.asList(myArray));//Doesn't work :(
System.out.println("After reverse order: ");
for (int i=0;i<arraySize;i++)
System.out.println(myArray[i]);
My problem is that when the input for the doubles is given by the user the console moves to the next line still expecting input, if input is given ArrayIndexOutOfBounds is thrown
You misunderstood something here.
In Collections.reverse(Arrays.asList(myArray)); you use Arrays.asList(myArray) that is returning a new List. Afterwards you reverse it, but you don't assign it to a variable and you just lose it.
That's not how you need to do it.
You need to think of another way of doing it.
I'll give you a hint: use the hint in the question!
and if you say you just need to reverse it, why do you need to sort it?!
I need to fill the values of an array (double[] myArray) using
Scanner input from a single line for multiple doubles.
If I understand this correctly first you need to read entire line and then parse it to read all double values from it. To read entire line of doubles from user you can invoke nextLine from scanner which handles System.in stream. Then you can either
split line on spaces and use Double.parseDouble(String) (to get double from String) on each String element from result array
wrap this line with another Scanner and use its nextDouble.
BTW if you want to read next line after nextDouble (or nextInt or nextAnythingExceptLine) you need to consume reminded line separators with another nextLine method (more info here Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods).
So first part of your assignment can look like
Scanner sc = new Scanner(System.in);
System.out.println("Please input the size of array: ");
int arraySize = sc.nextInt();
sc.nextLine();//consume line separator to let `nextLine` read actuall next line
double[] myArray = new double[arraySize];
System.out.print("Please input " + arraySize
+ " double numbers in one line: ");
String line = sc.nextLine();
System.out.println("your numbers are "+line);
Scanner lineScanner = new Scanner(line);
int j = 0;
while (lineScanner.hasNextDouble()) {
myArray[j++] = lineScanner.nextDouble();
}
lineScanner.close();
Your second problem is that generics don't support primitive types so T in asList(T..) can be only object type. Unfortunately autoboxing works only on primitive types, so double[] can't be promoted to Double[] because every array is already an object (even arrays of primitive types).
This means that result of Arrays.asList(T.. data) for argument myArray of type double[] will not return List<double> or List<Double> but List<double[]> — a list which holds one object, the passed array, not the elements of this array. That is why reversing doesn't work for you (reversing list containing one element changes nothing, as you can't reorder list with only one element).
To solve this problem simply change type of myArray form double[] (array of primitive types) to Double[] (array of object types), to let generic type T from asList(T..) represent non-primitive Double (otherwise T can only be inferred as non-primitive double[] type).
So change your line
double[] myArray = new double[arraySize]; // Create array[userInput]
to
Double[] myArray = new Double[arraySize]; // Create array[userInput]
Probably you have to instantiate a new Scanner after you have read the array size.
Scanner sc = new Scanner(System.in);
System.out.println("Please input the size of array: ");
int arraySize = sc.nextInt(); //Stores user input
double[] myArray = new double[arraySize]; //Create array[userInput]
sc.close();
sc = new Scanner(System.in).useDelimiter(",");
System.out.print("Please input " + arraySize + " double numbers: ");//Collect user input
int j = 0;
Collections.reverse(Arrays.asList(myArray));//Doesn't work :(
First of all: Arrays.asList get Object varargs and if you pass primitive array you'll get list of primitive arrays.
Second moment: Arrays.asList returns list. And if you changed it list your original array(from which you create list) will not be changed.
You shall make collection instead array and reverse it.
For example:
Scanner sc = new Scanner(System.in);
System.out.println("Please input the size of array: ");
int arraySize = sc.nextInt(); //Stores user input
System.out.print("Please input " + arraySize + " double numbers: ");//Collect user input
List<Double> myList = new ArrayList<Double>();
for (int i = 0; i < arraySize;) {
if (sc.hasNextDouble()) {
myList.add(sc.nextDouble());
i++;
}
}
Collections.reverse(myList);//Doesn't work :(
System.out.println("After reverse order: ");
for (int i=0;i<arraySize;i++)
System.out.println(myList.get(i));
Use this to reverse your array.
You need to get half of the array's length to get the full reverse of the array
for(double i = 0; i < Array.length / 2; i++)
{
int x = Array[i];
Array[i] = Array[Array.length - i - 1];
Array[Array.length - i - 1] = x;
}
package display.pkg1;
import java.util.Scanner;
public class Display1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(" Enter the size of array ");
int size = input.nextInt();
System.out.println(" Enter array Elements ");
double []lol = new double [size];
for(int i =0 ; i<size ; i++)
{
lol[i] = input.nextDouble();
}
for(int i =size-1 ; i>=0 ; i--)
{
System.out.println(" Array element " + ( i +1) + " is " + lol[i]);
}
}
}
Try this code
import java.util.Scanner;
public class ReverseArray{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please input the size of array: ");
int arraySize = sc.nextInt(); //Stores user input
double[] myArray = new double[arraySize]; //Create array[userInput]
System.out.print("Please input " + arraySize + " double numbers: ");//Collect user input
for(int i = 0; i < myArray.length; i++){
if (sc.hasNextDouble()) {
myArray[i] = sc.nextDouble(); //Insert user input into array
}
}
// Reverse myArray
for(int i = 0, j = myArray.length-1; i < (myArray.length/2); i++, j--){
Double temp = myArray[i];
myArray[i] = myArray[j];
myArray[j] = temp;
}
//Print the reversed myArray
System.out.println("After reverse order: ");
for (int i=0;i<arraySize;i++)
System.out.println(myArray[i]);
}
}

Convert numbers into word-numbers (using loop and arrays)

How do I write a simple program that converts numbers into word-numbers, using loops and arrays?
like this: input: 1532
output: One Five Three Two
Here's what I tried:
class tallTilOrd
{
public static void main (String [] args)
{
Scanner input = new Scanner (System.in);
String [] tall = {"null", "en" , "to", "tre", "fire" ,
"fem", "seks", "syv", "åtte", "ni", "ti");
System.out.println("Tast inn et ønsket tall");
int nummer = input.nextInt();
for (int i = 0; i<tall.length; i++)
{
if(nummer == i)
{
System.out.println(tall[i]);
}
}
}
}
Scanner input = new Scanner (System.in);
String in = Integer.toString(input.nextInt());
String [] tall = {"null", "en" , "to", "tre", "fire" , "fem", "seks", "syv", "åtte", "ni", "ti"};
for(char c : in.toCharArray()){
int i = (int) (c-'0');
for (int j = 0; j<tall.length; j++) {
if(i == j){
System.out.print (tall[j] + " ");
}
}
}
I give you a hint:
You could convert your Integer input into a String and then process each Character of that string. Check out the javadoc for String to figure out how to do it ;-)
Now I'm not sure this is the perfect way to do it, but it would be a possible one.
Instead of iterating over the length of your tall array, you need to iterate over the digits of nummer (to do this, check out the methods String.valueOf(int), String.charAt(int) and String.length()). Then use those digits as indices for tall to get their string representation.
A few notes:
In the code you provided, you need to use == instead of =. == is for comparison, = is for assignment.
Instead of looping through the predefined array, loop through the input. Instead of treating the number entered as an int, treat it as a string and then convert each character in the string into a number, which you can use as an index to fetch the corresponding string from your array.
Also, note that println prints a newline each time.

Categories

Resources