I've been up for a few hours trying to find a solution.
My program asks the user to enter a list of integers (example: 5 2 5 6 6 1).
Then I would like to create an array and store each integer into its respective array index, consecutively.
Here is the part of my program i'm having trouble with (this program was meant to perform calculations via a method later on, but I didn't include that):
import java.util.Scanner;
public class Assignment627 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x = 0;
int[] list1Array = new int[1];
System.out.println("Enter list1: ");
while (input.hasNext()){
list1Array[x] = input.nextInt();
x++;
}
As you can see, I am instantiating the array "list1Array" but the problem is I don't know how many integers the user would enter! If only there were a way of knowing how many integers have been input... Any help would be greatly appreciated!
Thanks,
Sebastian
import java.util.Scanner;
public class Assignment627 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//int[] list1Array = new int[1];
List<Integer> list1Array = new ArrayList<>();
System.out.println("Enter list1: ");
while (input.hasNext()){
list1Array.add(input.nextInt());
}
}
}
An ArrayList, is like an array that does not have a predefined size and it dynamically changes its size; exactly what you are looking for. You can get its size by list1Array.size();
If you insist on having the final result as an array, then you can later call the toArray() method of ArrayList. This post will be helpful.
If you really want to use Arrays, do it like this:
import java.util.Scanner;
public class Assignment627 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x = 0;
int[] list1Array = new int[1];
System.out.println("Enter list1: ");
while (input.hasNext()) {
list1Array[x] = input.nextInt();
x++;
int[] temp = new int[list1Array.length + 1];
for (int i = 0; i < list1Array.length; i++) {
temp[i] = list1Array[i];
}
list1Array = temp;
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter elemnt size ");
int size = input.nextInt();
int x = 0;
int[] list1Array = new int[size];
for (int y = 0 ; y < size ; y++) {
System.out.println("Enter number");
list1Array[x] = input.nextInt();
x++;
}
System.out.println(Arrays.toString(list1Array));
}
Output
Enter elemnt size
4
Enter number
2
Enter number
3
Enter number
4
Enter number
2
[2, 3, 4, 2]
Use List, in your case ArrayList will be fine:
List<Integer> list1Array = new ArrayList();
while (input.hasNext()){
list1Array.add(input.nextInt());
x++;
}
You should take the input as string and then use string.split(" "); and then obtain an array of Strings representing each number. Obtaining array by string can be done by string tokenizing.
UPDATE
But you should be careful not to put other chars as separators for numbers number
Related
I am trying to take user input, place it into my array, display the array and then print all the values larger than the "n" values the user provides. I think I am close, but I can't get the user input to go to the array. I keep getting an error in eclipse when I call the method (main at very bottom) the "arrayValues" cannot be resolved to a variable:
import java.util.Arrays;
import java.util.Scanner;
public class LargerThanN {
//initialize n
static int n;
static int arraySize;
//setup the array
static int [] integerArray = new int [] {};
public static void printGreaterThanN(int[] integerArray, int n) {
for (int i = 0; i < integerArray.length; i++) {
if (integerArray[i]>n) {
System.out.println(integerArray[i]);
}
}
}
public static int[] fillArrayWithUserInt() {
Scanner sc = new Scanner(System.in);
System.out.println("How big will the array be?");
int arraySize = sc.nextInt();
sc.nextLine(); // clears rest of input, including carriage return
int[] integerArray = new int[arraySize];
System.out.println("Enter the " + arraySize + " numbers now.");
for (int i = 0; i < integerArray.length; i++) {
integerArray[i] = sc.nextInt();
}
return integerArray;
}
/**
* This method prints the array to the standard output
* #param array
*/
private static void displayArray( int[] integerArray) {
for (int i = `0; i < integerArray.length; i++) {
System.out.print(integerArray[i] + " ");
}
}
public static void main(String[] args) {
int [] array ;
array = fillArrayWithUserInt();
Scanner sc = new Scanner(System.in);
fillArrayWithUserInt();
displayArray(array);
System.out.println("To which number would you like to compare the rest? Your n value is: ");
n = sc.nextInt();
printGreaterThanN(array, n);
but now my output looks like:
How big will the array be?
4
Enter the 4 numbers now.
1 2 3 4
How big will the array be?
3
Enter the 3 numbers now.
1 2 3
1 2 3 4
To which number would you like to compare the rest? Your n value is:
2
3
4
Heads up, the following code does nothing in java...
public void set(int n, int value) {
n = value;
}
You seem to written code like this in many functions where a value should be returned.
For example, the function definition :
static void fillArrayWithUserInt(int[] integerArray, int arraySize, int arrayValues, int n)
Should really be written as :
static int[] fillArrayWithUserInt()
It could be implemented as follows
public static int[] fillArrayWithUserInt() {
Scanner sc = new Scanner(System.in);
System.out.println("How big will the array be?");
int arraySize = sc.nextInt();
sc.nextLine(); // clears rest of input, including carriage return
int[] integerArray = new int[arraySize];
System.out.println("Enter the " + arraySize + " numbers now.");
System.out.println("What are the numbers in your array?");
for (int i = 0; i < integerArray.length; i++) {
integerArray[i] = sc.nextInt();
}
return integerArray;
}
The above function will ask the user for the array size. Create the array with the given size. Then prompt the user to fill the array with the correct number of values. The array created in this process is then returned.
All you must handle differently now is finding the value to compare. This must be done outside the fillArrayWithUserInt function.
Like so :
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] array = fillArrayWithUserInt();
displayArray(array);
System.out.println("To which number would you like to compare the rest? Your n value is: ");
int n = sc.nextInt();
printGreaterThanN(array, n);
}
Lastly, you should not need to declare any static variables at the top of your class.
These lines can all be deleted :
//initialize n
static int n;
static int arraySize;
//setup the array
static int [] integerArray = new int [] {};
Here is my solution check it out.
import java.util.Scanner;
public class LargerThanN {
static int[] integerArray = null;
static int n ;
public static void printGreaterThanN() {
for (int i = 0; i < integerArray.length; i++) {
if (integerArray[i] > n) {
System.out.println(integerArray[i]);
}
}
}
public static void fillArrayWithUserInt() {
Scanner sc = new Scanner(System.in);
System.out.println("How big will the array be?");
int arraySize = sc.nextInt();
sc.nextLine(); // clears rest of input, including carriage return
integerArray = new int[arraySize];
System.out.println("Enter the " + arraySize + " numbers now.");
System.out.println("What are the numbers in your array?");
for (int i = 0; i < integerArray.length; i++) {
integerArray[i] = sc.nextInt();
}
System.out.println("To which number would you like to compare the rest? Your n value is: ");
n = sc.nextInt();
}
/**
* This method prints the array to the standard output
*
* #param array
*/
private static void displayArray() {
for (int i = 0; i < integerArray.length; i++) {
System.out.print(integerArray[i] + " ");
}
}
public static void main(String[] args) {
fillArrayWithUserInt();
displayArray();
printGreaterThanN();
}
}
My school homework is to declare array with 100 variables.
The actual task is: Declare array with 100 variables. Use do.. while loop to read the data to array. Reading data should be finished when array will be full or when user will enter a negative number.
So far I got:
public static void runTask1() {
Scanner read = new Scanner(System.in);
int[] tab = new int [100];
for (int i = 0; i < tab.length; i++);
System.out.println("Enter number for array ");
tab [] = read.nextInt();
Please help. I'm a total newbie in programming.
You should do your homework yourself ;)
Scanner read = new Scanner(System.in);
int[] tab = new int [100];
int idx=0;
do{
System.out.println("Number for array idx "+idx);
try{
tab[idx] = read.nextInt();
}catch(Exception e){
System.out.println("Wrong input");
}
if(tab[idx]<0) break;
idx++;
}while(idx<100)
Not compiled, just wrote it here.
Try that
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int[] tab = new int [100];
int index = 0;
while(index < tab.length){
System.out.println("Enter number for array ");
tab[index]= read.nextInt();
if(tab[index]<1) break;
index++;
}
System.out.println(Arrays.toString(tab));
}
I am trying to pass an array from one method to another method and then copy the contents of that array into a new array. I am having trouble with the syntax to accomplish that task.
Does anyone have some reference material that I could read about this topic or maybe a helpful tip that I could apply?
I apologize if this is a noob question, but I have only been messing with Java for 3-4 weeks part time.
I know that Java uses pass by value, but what where I'm getting lost is...should I invoke the sourceArray before copying it to the targetArray?
My goal here is not to be just handed an answer, I need to understand WHY.
Thanks...in advance.
package cit130mhmw08_laginess;
import java.util.Scanner;
public class CIT130MHMW08_Laginess
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter the total number of dealers: ");
int numDealers = input.nextInt();
numDealers = numberOfDealers(numDealers);
System.out.printf("%nPlease enter the required data for each of your dealers:");
dataCalculation(numDealers);
}//main
//METHOD 1
public static int numberOfDealers(int dealers)
{
int results;
Scanner input = new Scanner(System.in);
while(dealers < 0 || dealers > 30)
{
System.out.printf("%nEnter a valid number of dealers: ");
dealers = input.nextInt();
}
results = dealers;
return results;
}//number of dealers methods
//METHOD 2
public static void dataCalculation(int data)
{
String[] dealerNames = new String[data];
Scanner input = new Scanner(System.in);
System.out.printf("%nEnter the names of the dealers:%n ");
for(int i = 0; i < data; i++)
{
String names =input.nextLine();
dealerNames[i]= names;
}
int[] dealerSales = new int[data];
System.out.printf("%nEnter their sales totals: %n");
for(int i = 0; i < data; i++)
{
int sales = input.nextInt();
dealerSales[i] = sales;
}
for(int i = 0; i < data; i++)
{
System.out.println(" " + dealerNames[i]);
System.out.println(" " + dealerSales[i]);
}
//gather the required input data.
//Perform the appropriate data validation here.
}//data calculations
//METHOD 3
public static int commission(int data)
{
//Create array
int[] commissionRate = new int[dealerSales];
//Copy dealerSales array into commissionRate
System.arraycopy(dealerSales, 0, commissionRate, 0, dealerSales.length);
//calculate the commission array.
//$1 - $5,000...8%
//$5,001 to $15,000...15%
//$15,001...20%
//
}//commission method
}//class
If you want to copy an array, you can use the Arrays.copyOf(origin, length) method. It takes 2 arguments, first one is the array from which the data is supposed to be copied and second is the length of the new array, and import java.util.Arrays.
-See the link for more info https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#copyOf(int[],%20int)
import java.util.Scanner;
public class Tar0 {
static Scanner in = new Scanner (System.in);
public static void main(String[] args) {
int d, i = 0, a = 0, f = 1;
System.out.println("Enter How many Digits you want?");
d = in.nextInt();
int num[] = new int[d];
for(i = 0; i < d; i++) {
System.out.println("Enter Single Digit");
num[i] = in.nextInt();
}
for(i = d; i > 0; i--) {
a = a + (num[i] * f);
f = f * 10;
}
System.out.println("The Number is: " + a);
}
}
Question: User will enter number of digits and the program will make from it a number I have wrote the code by myself but it doesnt seems to work.
When Running the program:
the input seems to work fine. I have tried to test the output of the
array without the second loop with the calculation, seems to work
but with the calculation seems to crush:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at tar0.main(tar0.java:17)
What's the deal?
Java arrays start at 0 and continue up from there. The way your code is formatted right now you are losing a value and therefore your array is too small to hold the values.
One option as outlined above would be to decrement your d value so that we are using a proper array size in the loop. This would be the preferred way so I removed the additional code above for the other option.
import java.util.Scanner;
public class tar0 {
static Scanner in = new Scanner (System.in);
public static void main(String[] args)
{
int d,i=0,a=0,f=1;
System.out.println("Enter How many Digits you want?");
d=in.nextInt();
int num[] = new int[d];
for(i=0;i<d;i++)
{
System.out.println("Enter Single Digit");
num[i]=in.nextInt();
}
for(i = d - 1; i >0 ; i--)
{
a=a+(num[i]*f);
f=f*10;
}
System.out.println("The Number is: "+a);
}
If you have modified the following code it will work.
for(i=d;i>0;i--)
{
a=a+(num[i-1]*f);
f=f*10;
}
Array index value will start at 0. so change array from num[i] to num[i-1]
i came across this problem whereas user need to enter a certain series of number in one input, then the program will output back the number one by one. For example, the user entered 4 6 8, then the program will output 4 6 8 to the user.
The code that i have done is like this :
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int N;
String num;
Scanner in = new Scanner(System.in);
System.out.println("Enter number:");
num = in.nextLine();
ArrayList<Integer> numbers = new ArrayList<Integer>();
for(int x = 0; x < num.length(); x++)
{
char c = num.charAt(x);
if(Character.getNumericValue(c) >= 0 ){
numbers.add(Character.getNumericValue(c));
}
}
for(int n=0; n<numbers.size(); n++){
System.out.println(numbers.get(n));
}
}
}
But i think it is not really efficient as it is quite long for just doing a simple task. So, could you suggest anything that is much simpler? Thanks!
If all the numbers are in one line then this can solve the problem:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String[] tokens = reader.readLine().split(" ");
for (int i = 0; i < tokens.length; i++)
System.out.println(Integer.parseInt(tokens[i]));
See BufferedReader for more info.
Set delimitter on Scanner and read each number a int
Scanner in = new Scanner(System.in);
in.useDelimiter("\\s");
System.out.println("Enter number:");
ArrayList<Integer> numbers = new ArrayList<Integer>();
while (in.hasNextInt()) {
numbers.add(in.nextInt());
}
Here's my idea:
String num = "4 6 8"; // user's input
System.out.println(num.replaceAll("\\s+", "\n"));
4
6
8
If you want to ignore everything except the numbers you can use "[^\\d]+" instead of "\\s+".