Assign new value to an Array using Enhanced For Loop - java

I am trying to find a way to assign values to an Array from the scanner input by using enhanced For loop. But I don't see a way I can do it.
In the code below i have declared a getInput() method which loops through the Array and assign numbers from the scanner input. But in case of enhanced For loop I can't really use something like this -
For(int i: baseData){
//basedata[i]=scanner.nextInt()}
because baseData array will not return any value as it iterates, so i thought how about iterating through scanner.nextInt() and assign values in the array, but scanner.nextInt() is not a array.
So what could the easy solution for this problem?
package com.ksk;
import java.util.Scanner;
public class Main {
private static Scanner scanner = new Scanner(System.in);
private static int[] baseData = new int[4];
public static void main(String[] args) {
System.out.println("Enter 4 numbers here");
getInput();
printInput();
}
static void getInput() {
for (int i = 0; i < baseData.length; i++) {
baseData[i] = scanner.nextInt();
}
}
static void printInput() {
for (int i : baseData) {
System.out.println(i);
}
}
}

A for-each loop hides the iterator, so you won't be able to update the array with one (at least not without adding a new counter / iterator). Instead, assuming you're using Java 8+, you can write an IntStream generator using your Scanner. Something like,
private static int[] baseData = IntStream.generate(() -> scanner.nextInt())
.limit(4).toArray();
However, this is really just an example, in real life I would prefer code that is a little more forgiving with unexpected input.

Try like this.
import java.util.Scanner;
import java.util.stream.IntStream;
public class Main {
private static Scanner scanner = new Scanner(System.in);
private static int[] baseData = IntStream.generate(() -> scanner.nextInt())
.limit(4).toArray();
public static void main(String[] args) {
System.out.println("Enter 4 numbers here");
printInput();
}
static void printInput() {
for (int i : baseData) {
System.out.println(i);
}
}
}
OR
import java.util.Scanner;
public class Main {
private static Scanner scanner = new Scanner(System.in);
private static int[] baseData = new int[4];
public static void main(String[] args) {
System.out.println("Enter 4 numbers here");
getInput();
printInput();
}
static void getInput() {
int position =0;
for(int i:baseData){
baseData[position] = scanner.nextInt();
position++;
}
}
static void printInput() {
for (int i : baseData) {
System.out.println(i);
}
}
}

Related

I tried taking input in ArrayList but it shows out of memory

I tried taking input in ArrayList but it shows out of memory. can anybody see whats wrong?
first i created takeInput to receive input till last number entered is -1. After that i made print function to print the code
Code-
import java.util.*;
public class ArrayListTakeInput {
/**
* #return
*/
public static ArrayList<Integer> takeInput(){
ArrayList<Integer> list = new ArrayList<Integer>();
Scanner s=new Scanner(System.in);
int i=s.nextInt();
while(i!=-1){
list.add(i);
}
return list;
}
public static void print(ArrayList<Integer> list2){
for(int i=0; i<list2.size(); i++) {
System.out.print(list2.get(i) + " ");
}
}
public static void main(String[] args) {
ArrayList<Integer> list2 = new ArrayList<Integer>();
list2=takeInput();
print(list2);
}
}
The problem is your condition of your while loop in the method takeInput(). Your Variable 'i' is not updated inside the loop. Currently you set i once and the while loop condition never become false. That is the reason why it shows out of memory. To avoid this mistake updat 'i' inside the loop. I guess you won't add the end operation of your methode (-1) so this could be a solution:
import java.util.*;
public class ListTakeInput {
/**
* #return
*/
public static List<Integer> takeInput() {
List<Integer> list = new ArrayList<>();
Scanner s = new Scanner(System.in);
int i = s.nextInt();
while (i != -1) {
list.add(i);
i = s.nextInt();
}
return list;
}
public static void print(List<Integer> list2) {
for (Integer integer : list2) {
System.out.print(integer + " ");
}
}
public static void main(String[] args) {
List<Integer> list2 = takeInput();
print(list2);
}
}

Call a method in the Static void main

Hy my method is this:
public static String[] getcontestants(String[] contestants) {
int numcontestants = 8;
String name[] = new String[numcontestants];
for (int j = 0; j < numcontestants; j++) {
Scanner ip = new Scanner(System.in);
System.out.println("Enter contestant's name");
name[j] = ip.nextLine();
}
return name;
}
I would like to call this method in the static void main but I don't exactly know how to do it. Tell me if there's any mistake in this method. Thanks!
So tbh, I like Maarten Bodewes's answer better, but I think this might be a bit easier for you to understand.
Main :
public static void main(String[] args) {
String[] contestants = getcontestants();
}
I edited Your function just a bit:
public static String[] getcontestants()
{
int numcontestants=8;
String name[] = new String[numcontestants];
for(int j=0;j<numcontestants;j++){
Scanner ip=new Scanner(System.in);
System.out.println("Enter contestant's name");
name[j]=ip.nextLine();
}
return name;
}
Hope that answers your question!
You can just use
MyClass.getcontestants(new String[] { "MS", "MR" });
where MyClass is the class that contains the method. You can leave out MyClass. if your main method is in the same MyClass class.
This is a direct answer to your question. If you look at the design of your class then Hadeems answer shows you that you don't need to pass the String array to the method; the scanner can be used locally.
You don't need to create scanner object in this method (it will create as many objects as the loop goes which is not the standard way of coding & not efficient at all).
Declare static Scanner ip = new.... ; outside the method within a class as global variable. (static - so that it's only one instance)
class YourClassName{
static Scanner ip = new....;
public static void main(String [] args){
//String[] inputStringArray = getcontestants( //new String (){"my", "text", "as", "string", "array"});
// Why passing string array to the function where actually you are taking input from user
// Better don't pass anything except length of the string array
String[] inputStringArray = getcontestants(contestanstCount);
}
public static String[] getcontestants(..){}
}
here is the code. Try it.
import java.util.Scanner;
public class AmadouQuestion {
public static void main(String[] args) {
String [] names = getcontestants(3);
for (int i = 0; i < names.length; i++) {
System.out.println(names[i]);
}
}
public static String[] getcontestants(int numcontestants)
{
Scanner ip=new Scanner(System.in);
String[] names = new String[numcontestants];
for(int j=0;j<numcontestants;j++){
System.out.println("Enter contestant's name");
names[j]=ip.nextLine();
}
ip.close();
return names;
}
}

How can I pass an Array from one class to another?

I am trying to make the compiler pass the array from one of the classes to the main method. I don't know why it does not work, the code looks like this:
public class Main {
public static void main(String[] args) {
int[] board2;
int userInput;
playBoard = board.createBoard();
userInput = takeAGuess.input();
}
}
import java.util.Scanner;
public class takeAGuess {
int input()
{
int input=0;
Scanner reader = new Scanner(System.in);
System.out.println("Please enter your guess now");
input = reader.nextInt();
System.out.println("Guess entered successfully");
return input;
}
}
public class board {
int[] createBoard()
{
int[] board = new int[7];
int randomNum =(int) (Math.random()*5);
for (int i=0; i<2; i++)
{
board[randomNum+i] = 1;
}
System.out.println("Board created");
return board;
}
}
I already tried these lines:
new[] board = board.Createboard();
int board[] = board.Createboard();
{
int board = new board();
board = createBoard();
}
I am aware of that I could easily put everything in one class and even one method but i'm to practice on using classes therefore I create lots of them.
int[] board2;
int userInput;
playBoard = board.createBoard();
userInput = takeAGuess.input();
where is playboard defined?
And... so much classes! Use methods in the Main class instead, it'll make your job lighter.

create objects using user input number of object [duplicate]

This question already has answers here:
Is this a valid way to count instances of objects?
(2 answers)
Closed 6 years ago.
I am a new user in java. As a programming exercise i have to make a program that - asks how many objects the user wants to create and then creates them. Class also calls for a class method that prints the number of created objects. also
to write the class which creates the objects. Class must be able to keep track of the number of created objects. Class also needs the method that prints the number of objects. Check the completed class for the names of the class and method.
I have tried following but have not reached any where so i am expecting some help: Please help!!
import java.util.Scanner;
public class NumberOfObjects{
public static void main(String args[]) {
System.out.print("How many objects do you want to create:");
Scanner reader = new Scanner(System.in);
int amount = reader.nextInt();
Thing[] things = new Thing[amount];
for(int i = 0; i<amount; i++) {
things[i] = new Thing();
}
Thing.numberOfObjects();
}
class Thing{
int count;
public void numberOfObjects(){
System.out.println(count);
}
}
}
You forgot 3 things:
1- to increment the count of the objects when they are created. You can do so in the Thing constructor.
2- declare the count variable as static to allow the variable to be shared between all objects of type Thing.
3 - to declare the numberOfObjects method as static since it is a class method that you are accessing via the Thing class
Try this:
import java.util.Scanner;
public class NumberOfObjects{
public static void main(String args[]) {
System.out.print("How many objects do you want to create:");
Scanner reader = new Scanner(System.in);
int amount = reader.nextInt();
Thing[] things = new Thing[amount];
for(int i = 0; i<amount; i++) {
things[i] = new Thing();
}
Thing.numberOfObjects();
}
class Thing{
private static int count = 0;
public Thing(){
count++;
}
public static void numberOfObjects(){
System.out.println(count);
}
}
}
class Box
{
//Keep track of all your objects
Thing[] objs;
int cursor;
public Box(int countOfObjects)
{
objs = new Thing[countOfObjects];
}
//add new object to the array
public void add(Thing thing)
{
objs[cursor++] = thing
}
//gets the object
public Thing getThing(int pos)
{
if(pos < 0 || pos >= objs.lenght())
throw;
return objs[pos];
}
//count the objects
public int numberOfObjects()
{
System.out.println(objs.lenght());
return objs.lenght();
}
}
}
class Thing()
{
//any field you need to store
}
Your main should look like this
public static void main(String args[]) {
System.out.print("How many objects do you want to create:");
Scanner reader = new Scanner(System.in);
int amount = reader.nextInt();
Box box = new Box(amount);
for(int i = 0; i<amount; i++) {
box.Add(new Thing());
}
box.numberOfObjects();
}
Declare count as static and add count in constructor.Another import thing,move Thing class out of NumberOfObjects Class,otherwise, the Thing class is an inner class, you will need create NumberOfObjects instance first and use this object to create Thing instance.
import java.util.Scanner;
public class NumberOfObjects{
public static void main(String args[]) {
System.out.print("How many objects do you want to create:");
Scanner reader = new Scanner(System.in);
int amount = reader.nextInt();
Thing[] things = new Thing[amount];
for(int i = 0; i<amount; i++) {
things[i] = new Thing();
}
Thing.numberOfObjects();
}
}
class Thing{
private static int count ;
public Thing(){
count++;
}
public static void numberOfObjects(){
System.out.println(count);
}
}

Array List for odd and even numbers stopping at -1

I can't get my code to work. Im trying to get all the even and odd numbers of an array but I have to stop whenever i find a -1.
import java.util.*;
public class EvenOdd{
private static int[] array;
private static List<Integer> even = new ArrayList<>();
private static List<Integer> odd = new ArrayList<>();
Scanner sc = new Scanner();
int numbers = sc.nextInt();
public static void classify() {
for(int i = 0 ; i < array.length ; i++){
if(numbers==-1){
if(array[i] % 2 == 0)
even.add(array[i]);
else
odd.add(array[i]);
}
}
}
public static void display(List<Integer> list){
for(Integer i : list)
System.out.println(i);
}
public static void main(String[] args){
classify();
display(even);
}
}
There are many issues in your code:
First of all, your code evaluates the next integer only if it is -1, skipping iteration otherwise;
Second, you're making a bit of confusion on the classify operation input:
the array was never populated, so the use of array in the for statement and module operations does not have any sense.
Furthermore the scanner constructor does not have a source.
If you want to insert numbers to evaluate from System.in, you can try the following fixed code:
import java.util.*;
public class Main {
private static List<Integer> even = new ArrayList();
private static List<Integer> odd = new ArrayList();
public static void classify(Scanner sc){
Integer number;
while(sc.hasNextInt()) {
number = sc.nextInt();
if(number==-1)
break;
if(number % 2 == 0)
even.add(number);
else
odd.add(number);
}
}
public static void display(List<Integer> list){
for(Integer i : list)
System.out.println(i);
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
classify(sc);
display(even);
}
}
There are many error in your code
constructor of java.util.Scanner
the if(numbers == -1) condition
the attribut array is allways null
This code is a small improvement of your code
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class EvenOdd{
private static List<Integer> array;
private static List<Integer> even;
private static List<Integer> odd;
private static Scanner sc;
public EvenOdd() {
array = new ArrayList<>();
even = new ArrayList<>();
odd = new ArrayList<>();
sc = new Scanner(System.in);
}
public void classify(){
for(int n : array){
if(n % 2 == 0) even.add(n);
else odd.add(n);
}
}
public void fillArray(){
int n = sc.nextInt();
do {
array.add(n);
n = sc.nextInt();
} while (n != -1);
}
public void display(List<Integer> list){
for(Integer i : list)
System.out.println(i);
}
public List<Integer> getEven() {
return even;
}
public List<Integer> getOdd() {
return odd;
}
public static void main(String[] args){
EvenOdd eo = new EvenOdd();
eo.fillArray();
eo.classify();
System.out.println("even");
eo.display(eo.getEven());
System.out.println("odd");
eo.display(eo.getOdd());
}
}
For what I've just read in the docs the Scanner class constructor needs a source as a parameter, and in your line:
Scanner sc = new Scanner(/*insert_source_object_here*/);
You are not providing any source, here's the list of possible constructors:
Scanner(File source)
Scanner(File source, String charsetName)
Scanner(InputStream source)
Scanner(InputStream source, String charsetName)
Scanner(Path source)
Scanner(Path source, String charsetName)
Scanner(Readable source)
Scanner(ReadableByteChannel source)
Scanner(ReadableByteChannel source, String charsetName)
Scanner(String source)

Categories