how do i instantiate an array based on user input - java

I am confused on how to instantiate the array using input from the user, the spot where i believe it should be is next to the comment right here
import java.util.Scanner;
public class Sales
{
public static void main(String[] args)
{
int[] sales;
sales = getSales();
printSales(sales);
printSummary(sales);
}
private static int[] getSales()
{
Scanner input = new Scanner(System.in);
int[] temp;
System.out.print("Enter the number of salespeople: ");
temp = _____________; // RIGHT HERE

You should write something like:
temp = new int[input.nextInt()];

Related

Scanner as parameter and convert to int? (JAVA)

I have a trouble about usage of the scanner.
The getUserInput takes as an input the scanner instance and initialise the array of specified size which comes from the scanner. For example: if user puts 3 then the method will create an array of the size 3.
However, it keeps saying that scnr can't converted to int....
Any advice?
public static void main(String[] args)
{
Scanner scnr = new Scanner(System.in);
System.out.println("How many orders were placed Saturday?");
int [] userInput = getUserInput(scnr);
System.out.println("How many orders were placed Sunday?");
int [] userInput = getUserInput(scnr);
System.out.println("How many orders were placed Monday?");
int [] userInput = getUserInput(scnr)
return;
}
}
public static int[] getUserInput(Scanner scnr)
{
int[] userInput = new int[scnr];
return userInput;
}
You have to call a method on Scanner. And because you want an int do it like this:
int[] userInput = new int[scnr.nextInt()];
Here you'll find the API documentation: https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html
nextInt() method of Java Scanner class is used to scan the next token of the input as an int
public static int[] getUserInput(Scanner scnr)
{
int[] userInput = new int[scnr.nextInt()];
return userInput;
}
Firstly there are 2 mistakes you have done here.
int [] userInput there are 2 duplicates of this userInput variable.
You are passing an instance of Scanner as a parameter in your getUserInput function.
getUserInput FIX
So in order to create we need to follow a syntax i.e
datatype [] vairable_name = new datatype[size];
Here size can be byte short int but what you did is
datatype [] vairable_name = new datatype[Scanner];
Which is just not the Syntax. You can fix it by taking input as int from the user.
A scanner as a method to do that .nextInt() which converts the input of the user to int if it's in numbers.
Solution is
int[] userInput = new int[scnr.nextInt()];
// This is like the syntax
datatype [] vairable_name = new datatype[Scanner];
Duplicate Variable
You should revise scopes in java, and then you will know why it's an error.
You cannot have the same variable name in the same scope or in the child scope
public static void main(String args[]){
int a = 0;
int a = 1; // <- error cuz a is already difined and is duplicate in the same scope.
}
Similarly
public static void main(String args[]){
int a = 0;
if(true){
int a = 1; // <- error cuz a is already difined and is duplicate in child scope.
}
}
The solution is to change the variable name.
//scnr is now globally available in the class so need to pass it as a parameter
Scanner scnr = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("How many orders were placed Saturday?");
int [] saturdayUserInput = getUserInput();
System.out.println("How many orders were placed Sunday?");
int [] sundayUserInput = getUserInput();
System.out.println("How many orders were placed Monday?");
int [] mondayUserInput = getUserInput()
return;
}
}
public static int[] getUserInput()
{
int[] userInput = new int[scnr.nextInt()];
return userInput;
}
scnr is not an int. It's an isntance of the Scanner class. If you want to read an int from it, you'll need to call:
scnr.nextInt();
It's also better not to pass this as a parameter, but to create the Scanner on class level, so you can use it in all the methods.

Create a simple java random number pick with in a certain range

I tried searching on here for something similar, but failed to find it, maybe using wrong keywords let me know, but here is the deal.
I am fairly new with java and wanted to make something useful myself.
My idea was to create a random number picker within a range with.
So let's say range is from 1-50, and I want 5 random number in this range, and they have to be all different. I have worked with Random before, but not sure what I am doing wrong, here is the code I have so far, please push me in the right direction if possible.
I want to create an array or list with the number, or is there a better way to do this?
import java.util.Scanner;
import java.util.Random;
public class Randomizer {
static Random rnd = new Random();
static int rnd(int a, int b){
return a+rnd.nextInt(b-a+1);
}
public static void nPicker(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter start of range: ");
int start = sc.nextInt();
System.out.println("Enter end of range: ");
int end = sc.nextInt();
System.out.println("Enter amount of numbers to pick: ");
int c = sc.nextInt();
sc.close();
rnd(start,end);
int[] randomArrays = new int[c];
for(int i = 0; i>randomArrays.length; i++){
randomArrays.add();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
nPicker();
}
}
sorry if my code is messy.
At the moment I can't even get the random number to be added into the array
Try this, I did explain to you what is wrong with comments at the code, read them.
import java.util.Scanner;
import java.util.Random;
public class Randomizer {
static int[] randomArrays; // You need to declare the vector as an instance variable, otherwise it will disappear when the method it's done.
static Random rnd = new Random();
static int rnd(int a, int b){
return a+rnd.nextInt(b-a+1);
}
public static void nPicker(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter start of range: ");
int start = sc.nextInt();
System.out.println("Enter end of range: ");
int end = sc.nextInt();
System.out.println("Enter amount of numbers to pick: ");
int c = sc.nextInt();
sc.close();
randomArrays = new int[c];
for(int i = 0; i<randomArrays.length; i++){ // The condition was wrong
int numberToAdd = rnd(start,end);
randomArrays[i] = numberToAdd; //You are not using an ArrayList, vector has not the method add(), you have to add new element to the vector throughout its index
}
}
public static void main(String[] args) {
Randomizer rdm = new Randomizer();
rdm.nPicker();
for(int number:rdm.randomArrays) {
System.out.println(number);
}
}
}
Thank you everyone for your advices and hints. In the end I think I managed to get the code how I wanted with the code below.
Tell me if you see an error in this method, or if it has a way that is not allowed in java.
import java.util.Scanner;
import java.util.Random;
import java.util.ArrayList;
import java.util.List;
public class Randomizer {
static Random rnd = new Random();
static int rnd(int a, int b){
return a+rnd.nextInt(b-a+1);
}
public static void nPicker(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter start of range: ");
int start = sc.nextInt();
System.out.println("Enter end of range: ");
int end = sc.nextInt();
System.out.println("Enter amount of numbers to pick: ");
int c = sc.nextInt();
sc.close();
List randomnumbers = new ArrayList();
for(int i = 0; i<c; i++){
int numb = rnd(start,end);
if(randomnumbers.contains(numb)){
break;
}else{
randomnumbers.add(numb);
}
}
randomnumbers.forEach(System.out::println);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
nPicker();
}
}
ok in the end i changed the loops as following:
for(int i = 0; i<c;){
int numb = rnd(start,end);
while(!(randomnumbers.contains(numb))){
randomnumbers.add(numb);
i++;
}
}
randomnumbers.forEach(System.out::println);
}
seems to work fine this way

can a variable be passed in array in java as its size

I am taking a variable from user and wants the array of same size as that of variable. So if I pass that variable in it as its size it shows me an error so is there any wayout for it.
import java.util.Scanner;
public class passingtheparcel
{
public static void main(String[] args)
{
Scanner obj = new Scanner(System.in);
String firstline;
String song;
int n;
System.out.println("enter the no. of students");
firstline = obj.nextLine();
n = Integer.parseInt(firstline);
System.out.println("enter the lyrics of song");
song = obj.nextLine();
int[n] a;
}
}
The syntax for initializing an array of length n is :
int[] a = new int[n];
System.out.println("enter the no. of students");
int[] a = new int[obj.nextInt()];
import java.util.Scanner;
public class Demo{
public static void main(String a[]){
Scanner obj=new Scanner(System.in);
String firstline;
int n;
System.out.println("Enter the no. of students");
firstline=obj.nextLine();
n=Integer.parseInt(firstline);
int arr[]=new int[n];
}
}
Please try this this is working sample.

How can I take the input and insert it into LINKED LIST in java?

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

Asking user for array size and populating array | Java

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

Categories