Call a method in the Static void main - java

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

Related

Assign new value to an Array using Enhanced For Loop

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

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

subroutine taking an array as a parameter in Java

In the following program, the user is supposed to enter a String (name of a City) and the program should return the index of the corresponding City in the array.
But I get an error, in the subroutine indexCities the following message:
"nameCity cannot be resolved".
I guess it is a problem of variable scoping but I don't figure out how I should do.
Thanks for your help.
import java.util.Scanner;
public class villes {
public static void main(String[] args) {
String cities[] = {"Vierzon","Salbris","Nouans","LB","LFSA","Orleans"};
Scanner input = new Scanner(System.in);
String nameCity = input.nextLine();
indexCities(cities);
}
public static int indexCities(String cities[]) {
for (int i = 0; i < cities.length; i++) {
if(nameCity.equals(cities[i])) {
System.out.println(i);
break;
}
}
}
}
nameCity is a local variable inside your main method. You can not access it outside the method.
One option for you is to pass the nameCity also as an argument in indexCities method. Also return type of your indexCities method should be void since you are not returning anything.
public static void main(String[] args) {
String cities[] = {"Vierzon","Salbris","Nouans","LB","LFSA","Orleans"};
Scanner input = new Scanner(System.in);
String nameCity = input.nextLine();
indexCities(cities, nameCity);
}
public static void indexCities(String cities[], String nameCity){
for (int i = 0; i < cities.length; i++) {
if(nameCity.equals(cities[i])) {
System.out.println(i);
break;
}
}
}
You could do it in this way:
public static void main(String[] args) {
String cities[] = { "Vierzon", "Salbris", "Nouans", "LB", "LFSA", "Orleans" };
int index = indexCities(cities, "Vierzon");
System.out.println("Index of city Vierzon is: " + index);
}
public static int indexCities(String cities[], String cityName) {
List<String> cityList = Arrays.asList(cities);
return cityList.indexOf(name);
}
Scope of variable nameCity is limited to main function. You can not access it outside of main function.
The variable is out of scope when you try to use it inside the method indexCities. One solution is making the variable nameCity an instance variable by moving it's definition out of the main method, but your code can be improved in several ways too. Check some option below:
This will print the index of the city you're looking for inside the array:
import java.util.Scanner;
public class villes {
public static void main(String[] args) {
String cities[] = {"Vierzon","Salbris","Nouans","LB","LFSA","Orleans"};
Scanner input = new Scanner(System.in);
String nameCity = input.nextLine();
indexCities(nameCity, cities);
}
public static void indexCities(String copyOfNameCity, String cities[]){
for (int i = 0; i < cities.length; i++) {
if(copyOfNameCity.equals(cities[i])) {
System.out.println(i);
break;
}
}
}
}
You you can improve it by making the method return a value. Like this:
import java.util.Scanner;
public class villes {
public static void main(String[] args) {
String cities[] = {"Vierzon","Salbris","Nouans","LB","LFSA","Orleans"};
Scanner input = new Scanner(System.in);
String nameCity = input.nextLine();
int cityIndex = indexCities(nameCity, cities);
System.out.println(cityIndex == -1 ? "City not found" : "City found in index " + cityIndex);
}
public static int indexCities(String nameCity, String cities[]){
for (int i = 0; i < cities.length; i++) {
if(nameCity.equals(cities[i])) {
return i;
}
}
return -1;
}
}
Another way is:
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class test2 {
public static void main(String[] args) {
String cities[] = {"Vierzon", "Salbris", "Nouans", "LB", "LFSA", "Orleans"};
Scanner input = new Scanner(System.in);
System.out.print("Enter the name of city to be searched -> ");
String nameCity = input.nextLine();
int cityIndex = indexCities(nameCity, cities);
System.out.println(cityIndex == -1 ? "City not found" : "Found at position " + cityIndex);
input.close();
}
public static int indexCities(String cityName, String cities[]) {
List<String> cityList = Arrays.asList(cities);
return cityList.indexOf(cityName);
}
}

If an input is in the array return true, else false

Fixed it. Working code! I had to move the fruit array into the method and call it from main.
import java.util.Scanner;
public class StringArrayTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input;
System.out.println("Enter a fruit: ");
input = sc.nextLine();
System.out.println("Is \"" + input + "\" in the array? " + isIn(input));
sc.close();
}
public static boolean isIn(String input) {
String[] fruit = new String[6];
fruit[0] = "grape";
fruit[1] = "banana";
fruit[2] = "apple";
fruit[3] = "mango";
fruit[4] = "watermelon";
fruit[5] = "orange";
for(int i = 0; i < fruit.length; i++) {
if (input.equals(fruit[i])) {
return true;
}
}
return false;
}
}
The following code will return true if the array contains the input and false if it doesn't.
Credits to camickr for this code:
Arrays.asList(yourArray).contains(yourString)
return false must be outside the for loop. If it's in the else part, the for loop will end at the first iteration.
Here's how the code should look like:
public boolean isIn(String input) {
for(int i = 0; i < fruit.length; i++) {
if (input.equals(fruit[i])) {
return true;
}
}
return false;
}
Also, you cannot declare a method inside another method. Move the method isIn outside main.
Other problems in your code:
String[] fruit is currently declared, initialized and filled inside main method. It should be at least declared outside as a field of the class in order to be accessed by other methods.
You're not using isIn anywhere.
In order to use the fields and methods inside main method, you have two options:
Declare the fields and methods as static.
Create a new instance of your class inside the main method and use the fields and methods from this instance.
The code may look like this:
import java.util.Scanner;
public class StringArrayTest {
static String[] fruit = new String[6];
public static void main(String[] args) {
fruit[0] = "grape";
fruit[1] = "banana";
fruit[2] = "apple";
fruit[3] = "mango";
fruit[4] = "watermelon";
fruit[5] = "orange";
Scanner sc = new Scanner(System.in);
String input;
input = sc.nextLine();
if (isIn(input)) {
//do something...
} else {
//do something else...
}
}
public static boolean isIn(String input) {
for(int i = 0; i < fruit.length; i++) {
if (input.equals(fruit[i])) {
return true;
}
}
return false;
}
}
Summarizing the suggestions given by others.
import java.util.Arrays;
import java.util.Scanner;
public class StringArrayTest {
public static void main(String[] args) {
String[] fruit = new String [] {"grape", "banana", "apple", "mango", "watermelon", "orange"};
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
System.out.println(Arrays.asList(fruit).contains(input));
}
}

How to make an Array of Strings with no values yet

In my program the user will introduce a string(String A) and I want an Array(AA[]) of Strings to get every single letter of the String A. But it says that the Array
import java.util.Scanner;
public class arrays{
public static void main(String[] args){
String A,B,AA[];
int a,cX,cY,cc,c;
Scanner scanner=new Scanner(System.in);
System.out.println("Introduce your text");
A=scanner.nextLine();
a=A.length();
cX=0;
cY=cX+1;
cc=0;
for(c=0;c==a;c++){
B=A.substring(cX,cY);
AA[cc]=B;
cc+=cc;
cX+=cX;
cY+=cY;
}
}
}
It says(The error), that the variable AA might no have been initialized.
What I want is to make the Array to have all the letters from the String A...
UPDATED:
import java.util.Scanner;
public class arrays{
public static void main(String[] args){
String A,B,AA[];
int a,cX,cY,cc,c;
Scanner scanner=new Scanner(System.in);
System.out.println("Introduce your text");
A=scanner.nextLine();
a=A.length();
cX=0;
cY=cX+1;
cc=0;
AA = new String[a];
for(c=0;c==a;c++){
B=A.substring(cX,cY);
AA[cc]=B;
cc+=cc;
cX+=cX;
cY+=cY;
}
System.out.println(AA[2]);
}
}
Now when I print it out, it says null.
You need to initialize AA to the length of String A:
AA = new String[A.length];
And your loop is strange. You can change it to :
for(c=0;c<a;c++){
B=A.substring(c,c+1);
AA[c]=B;
}
Instance and class variables are initialized to null (or 0), but local variables are not.
A local variable must be explicitly given a value before it is used, by either initialization or assignment
There is a much simpler way:
public static void main(String[] args)
{
String inputString; //A
char [] inputStringCharacters; //AA
Scanner scanner=new Scanner(System.in);
System.out.println("Introduce your text");
inputString=scanner.nextLine();
inputStringCharacters = new char[inputString.length()];
for(int i = 0; i < inputString.length(); i++)
{
inputStringCharacters[i] = inputString.charAt(i);
}
//print each character in AA
for (int i = 0; i < inputString.length(); i++)
{
System.out.println(inputStringCharacters[i]);
}
}
I also strongly advise you to use descriptive variable names rather than things like "cc, A, AA", etc. It will be much easier to understand the logic of your code if you make it clear what a variable is supposed to contain.

Categories