I'm fairly new to Java so please have some patience with me.
I was wondering how I could go about passing an array with a bunch of strings into a new method that would ask the user a question and then print the array. I then also want the input from the user to be stored in a different array but I feel confident I can do this part myself.
A fragment of what I think the code should look like is as follows:
public static void birdarray()
{
String[] birds = {"Blue Tit", "Blackbrid", "Robin"};
}
public static void wanttogetarrayinhere ()
{
String question = print("What bird are you reporting?");
print(birds);
I would appreciate a nudge in the right direction.
Just add it as a parameter:
public static void wanttogetarrayinhere(String[] arr)
{
String question = print("What bird are you reporting?");
print(arr);
}
Then pass in the desired array when you call it:
String[] birds = {"Blue Tit", "Blackbrid", "Robin"};
wanttogetarrayinhere(birds);
As was pointed out in the comments you'll also need an overloaded print() method, with an overload for a String parameter and one for a String[] parameter, e.g.:
public static void print(String str) {
System.out.println(str);
}
public static void print(String[] arr) {
StringBuilder builder = new StringBuilder();
for (int i=0; i<arr.length; i++) {
builder.append(arr[i]);
if (i<arr.length-1)
builder.append(", ");
}
System.out.println(builder.toString());
}
You could do this to get the array into the method:
public static void wanttogetarrayinhere(String[] input){
// then to print array out something like:
for (int i=0; i<input.length; i++){
System.out.println(input[i]);
}
}
Related
So I asked a question previously about returning arrays in Java, to which I got an answer, and now my code is updated with a getter, however I keep getting something along the lines of:
Phone#b08deb
as an output, which is not what I want, and if I were to do something like:
return arr[1];
It tells me that Phone cannot be converted to Phone[], and I'm incredibly lost as to how to get simply the number "00000" to be spit out by the compiler from the array (as I do understand that I don't need to initialize the array because it defaults to 0)
Link to question:
How do I return an array to another class in Java?
Updated code:
class TheDriverClass
{
public static void main(String[] args)
{
Phone p = new Phone(5);
System.out.println(p);
// Here it's supposed to return the values of an array with size 5,
//so it should print out 00000
}
}
Next I have the class Phone:
class Phone
{
private Phone[] arr; //I'm supposed to keep the array private
public Phone(int theLength){
arr = new Phone[size];
}
public Phone[] getPhone(){
return arr;
}
}
When you System.out.println() an array it basically prints out the array pointer.
you need something like Arrays.toString(array) it will call the toString on each element and print out something that is human readable.
Also to have a Phone that you can read. You will need to override the toString() on it as well.
class Phone
{
private int[] numbers; //I'm supposed to keep the array private
public Phone(int theLength){
numbers = new int[theLength];
}
public int[] getPhone(){
return numbers;
}
#Override
public String toString() {
return Arrays.toString(numbers);// also can use return Arrays.toString(numbers).replaceAll(",|\\[|\\]| ", ""); to clean up the , and []s
}
}
public class HelloWorld {
public static void main(String[] args) {
Phone p = new Phone(5);
System.out.println(p.getPhone());
}
}
class Phone {
private int[] arr;
public Phone(int size) {
this.arr = new int[size];
}
/* convert array to string */
public String getPhone() {
return Arrays.toString(arr);
}
}
If you would like to get the exact output as "00000" format, then you need to use StringBuilder
In the Phone class, the Phone[] arr will default to null, hence using int[] will default values to 0
If you don't want to make any changes in Phone class then inherit Phone class in CustomPhone class and override toString. this will work when Phone class is not final. I guess the following code may solve your problem.
class PhoneCustom extends Phone{
public PhoneCustom(int theLength) {
super(theLength);
}
#Override
public String toString() {
StringBuffer sb = new StringBuffer();
for(int i = 0; i < super.getPhone().length; i++) {
if(super.getPhone()[i] == null) {
sb.append(0);
}else {
sb.append(super.getPhone()[i]);
}
}
return sb.toString();
}
}
Also, modify toString according to your requirement in else part.
If you have flexiblity to modify you phone class then override the toString method in phone class.
class Phone
{
private Phone[] arr; //I'm supposed to keep the array private
public Phone(int theLength){
arr = new Phone[theLength];
}
public Phone[] getPhone(){
return arr;
}
#Override
public String toString() {
StringBuffer sb = new StringBuffer();
for(int i = 0; i < arr.length; i++) {
if(arr[i] == null) {
sb.append(0);
}else {
sb.append(arr[i]);
}
}
return sb.toString();
}
}
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;
}
}
I have a small java program that collects 10 words written by a user and prints them in specified orders. As it stands, the program works, but it is not cohesive.
My issue stems from not knowing enough about the concept of cohesion to work on fixing this, as well as being new to Java/OO languages.
I believe that the class Entry is way way way too cluttered, and that another class should take on some of this class' functions.
Any hint or clue, cryptic or otherwise would be greatly appreciated!
The lack of a input reader in Dialogue.java is intentional, as the original code uses proprietary code.
These are the three classes: entry, dialogue and printer.
Entry.java
public class Entry {
public static void main(String[] args){
String[] wordArray = new String[10];
Dialogue d = new Dialogue();
wordArray = d.read(wordArray);
Printer p = new Printer();
p.printForwards(wordArray);
p.printBackwards(wordArray);
p.printEveryOther(wordArray);
}
}
Dialogue.java
public class Dialogue {
public String[] read(String[] s){
String[] temp;
temp = new String[s.length];
for(int i=0;i<s.length;i++){
String str = anything that reads input("Enter word number" + " " + (i+1));
temp[i] = str;
}
return temp;
}
}
Printer.java
public class Printer {
public void printForwards(String[] s){
System.out.println("Forwards:");
for(int i=0;i<s.length;i++){
System.out.print(s[i] + " ");
if(i==s.length-1){
System.out.println("");
}
}
}
public void printBackwards(String[] s){
System.out.println("Backwards:");
for(int i=s.length-1;i>=0;i--){
System.out.print(s[i]+ " ");
if(i==0){
System.out.println("");
}
}
}
public void printEveryOther(String[] s){
System.out.println("Every other:");
for(int i = 0; i < s.length; i++){
if(i % 2 == 0){
System.out.print(s[i] + " ");
}
}
}
}// /class
It looks okay overall, the truth is it is a very simple task where as OOP is better suited for more complex programs. That being said, here are a few pointers/examples.
You can also do your printing more OOP style.
The purpose of this is build reusable, modular code. We do this by abstracting String array manipulations (which previously existed in the Printer class) to it's own class.
This is also very similar/also known as loose-coupling. We achieve loose-coupling by splitting the string processing functionality and the printing functionality.
Change you Printer class to StringOrderer or something along those lines:
public class StringOrderer {
private String[] array;
public class StringOrderer(String[] array) {
this.array = array;
}
public String[] getArray() {
return array;
}
public String[] everyOther(){
String[] eos = new String[array.length];
for(int i = 0; i < s.length; i++){
if(i % 2 == 0){
eos[eos.length] = s[i];
}
return eos;
}
public String[] backwards() {
...
And then in your main class add a method like such:
private static void printStringArray(String[] array) {
for (int i=0; i<array.length; i++) {
System.out.print(array[i]);
}
}
Then call it in your main method:
StringOrderer s = new StringOrderer(wordArray);
System.out.println('Forward:');
printStringArray(s.getArray());
System.out.println('Every other:');
printStringArray(s.everyOther());
System.out.println('Backwards:');
...
Extra tip - You can also add methods in your main class like so:
public class Entry {
public static void main(String[] args){
String[] wordArray = readWordArray()
Printer p = new Printer();
p.printForwards(wordArray);
p.printBackwards(wordArray);
p.printEveryOther(wordArray);
}
private static String[] readWordArray() {
Dialogue d = new Dialogue();
return d.read(new String[10]);
}
}
to make it more readable.
I discovered what i think is a bug whilst using netbeans. When i call up my method to sort an array containing names(ob.sort) in alphabetical order it automatically sorts another array which contains the original names when it isn't supposed to as the original names is not assigned to anything after it has been populated with input at the beginning(ob.input).
I experienced this problem whilst writing larger programs(encountered more than once), but i made a simpler one to demonstrate this problem. It looks like much as i copied the class methods an pasted it below the main class making it easier for you to trace the variables in the program.
public static void main(String args[]){
ObjectTest ob = new ObjectTest();
ob.input();
String x[] = ob.getNames();
System.out.println(x[0]);
ob = new ObjectTest(x);
System.out.println(x[0]);
ob.sort();
System.out.println(x[0]);
String y[] = ob.getNamesrt();
System.out.println(x[0]);
}
}
/*import java.io.*;
import javax.swing.*;
public class ObjectTest {
String name[];
String namesrt[];
public ObjectTest(){
name = new String[3];
namesrt = new String[3];
}
public ObjectTest(String j[]){
namesrt = j;
}
public void input(){
for(int i = 0; i < name.length; i++){
name[i] = JOptionPane.showInputDialog("Enter name");
}
}
public void sort(){
if(!(namesrt == null)){
for(int i = 0; i < namesrt.length; i++){
for(int c = i + 1; c < namesrt.length; c++){
if(namesrt[i].compareToIgnoreCase(namesrt[c]) > 0){
String n = namesrt[i];
namesrt[i] = namesrt[c];
namesrt[c] = n;
}
}
}
}
else{JOptionPane.showMessageDialog(null,"Names not received");}
}
public String[] getNames(){
return name;
}
public String[] getNamesrt(){
return namesrt;
}
public void setNames(String j[]){
name = j;
}
public void setNamesrt(String j[]){
namesrt = j;
}
}*/
I discovered what i think is a bug whilst using netbeans.
Well, it may be a bug in your code. It's not a bug in Java or in Netbeans. It's just demonstrating the fact that arrays are reference types in Java, and the way that objects work.
Here's a short but complete program demonstrating the same effect:
public class Test {
public static void main(String[] args) {
String[] x = { "hello" };
// Copy the *reference*
String[] y = x;
System.out.println(y[0]); // Prints "hello"
x[0] = "new value";
System.out.println(y[0]); // Prints "new value"
}
}
The values of x and y here are references to the same array object... so if the array is changed "through" x, that change is still visible as y[0].
If you want to make your code create independent objects, you'll want to change this:
public ObjectTest(String j[]){
namesrt = j;
}
to:
public ObjectTest(String j[]){
namesrt = j.clone();
}
(Ideally change it to declare the parameter as String[] j, or better yet fix all your variable names to be more meaningful, but that's a different matter.)
I need some help with a homework question I am working on.
I need to create a "Library" class that contains an array of Song objects.(capacity of 10).
Then make a method addSong.
Here's what I have so far:
public class Library{
Song[] arr = new Song[10];
public void addSong(Song s){
for(int i=0; i<10; i++)
arr[i] = s;
}
}
My question is: Is there another way to fill the array? i will later need to search for a song based on a index value. So i will create a method like:
public Song getSong(int idx)
Thank you in anticipation for your answers!
If you really have to use an array (and not an ArrayList or LinkedList), this solution may be the right for you:
public class Library{
private Song[] arr = new Song[10];
private int songNumber = 0; //the number of Songs already stored in your array
public void addSong(Song s){
arr[songNumber++] = s;
}
}
If you want to avoid a runtime-exeption if you add more then 10 songs:
public void addSong(Song s){
if(songNumber<10)
{
arr[songNumber++] = s;
}else{
//what to do if more then 10 songs are added
}
}
There are a number of ways of accomplish this.
The logic you're using is more or less ok.
But what you are doing here:
public void addSong(Song s){
for(int i=0; i<10; i++)
arr[i] = s;
}
Is filling all the Songs array with the same song, perhaps this would be better:
public void addSong(Song s, int index){
arr[index] = s;
}
Of course, if you pass a negative index, or an index greater than 9, you are gonna be in trouble.
Use an ArrayList instead of an array. This way you can use the ArrayList.add() function to append to the end of your array and the ArrayList.get(int index) function to get the array entry at index index.
public class Library{
ArrayList<Song> arr = new ArrayList<Song>();
public void addSong(Song s){
arr.add(s);
}
public Song getSong(int index){
return arr.get(index);
}
}
To expand on Vacation9s' answer:
ArrayList<Song> songArray = new ArrayList<Song>();
public void addSong(Song s){
songArray.add(s);
}