how to print all of arrays with for loop in java - java

I have array in String. I want to use for loop to print all of the objects. I was under the impression this would be done by making for loop then returning the String. I am not sure what I need to change to accomplish this.
Following is my effort:
public class SolarSystem {
private Planet[] planets;
private int position = 0;
public SolarSystem(int size) {
planets = new Planet[size];
}
public void add(Planet planet) {
planets[position] = planet;
position++;
}
public String toString(){
for(int i = 0; i < planets.length; i++){
}
return toString();
}
}
ADDED PLANET CLASS
public class Planet {
String name;
int moons;
public Planet(String name, int moons)
{
this.moons = moons;
this.name = name;
}
public String toString() {
return "The Planet " + name + " Has " + moons + " Moon(s) \r\n ";
}
}

You can try using a StringBuilder:
public String toString() {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < planets.length; i++){
sb.append(planets[i].getName()); // getName() or toString()
sb.append("\n");
}
return sb.toString();
}

Override toString() method in Planet class, and use below code :
public String toString(){
String result = "";
for(int i = 0; i < planets.length; i++){
result += planets[i].toString(); // append comma if you need to separate it,
// and most of all handle nulls
}
return result;
}

public String toString() {
StringBuilder mainresult = new StringBuilder();
for(int i = 0; i < planets.length; i++){
StringBuilder result = new StringBuilder();
String newLine = System.getProperty("line.separator");
result.append( planets[i].getClass().getName() );
result.append( " Object {" );
result.append(newLine);
//determine fields declared in this class only (no fields of superclass)
Field[] fields = this.getClass().getDeclaredFields();
//print field names paired with their values
for ( Field field : fields ) {
result.append(" ");
try {
result.append( field.getName() );
result.append(": ");
//requires access to private field:
result.append( field.get(this) );
} catch ( IllegalAccessException ex ) {
System.out.println(ex);
}
result.append(newLine);
}
result.append("}");
//if it is the first one then no new line added
if(i==0)
{
mainresult.append(result.toString());
continue;
}
mainresult.append(newLine);
mainresult.append(result.toString());
}
return mainresult.toString();
}

Override toString() Method
#Override
public String toString() {
return "SolarSystem [te=" + Arrays.toString(te) + ", position=" + position + "]";
}

If you have this overidden method in your planet class
public String toString(){
StringBuilder result = new StringBuilder();
String NEW_LINE = System.getProperty("line.separator");
result.append(" planetProperty1: ").append (planetProperty1).append(NEW_LINE);
result.append(" planetProperty2: ").append (planetProperty2).append(NEW_LINE);
return result.toString();
}
then from the calling class you can iterate over the collection calling
System.out.println (planets[i].toString());

Related

arraylist not printing successfully

i am trying to print object of a class using arraylist, but why I am getting this output
list is Test#27b4de03
list is Test#27b4de03
this is the way I am trying to iterate arraylist
for (int q=0;q<list.size();q++){
System.out.println("list is "+list.get(q));
}
and that is my main method where I am calling method
public static void main(String[] args) {
Test t=new Test ();
ArrayList<Test> list=new ArrayList<Test>();
System.out.println("size"+list.size());
Scanner sc = new Scanner(System.in);
String b = "";
int count = 0;
for (int i = 0; b != "stop"; i++) {
System.out.print("==> ");
String input = sc.nextLine();
count++;
if (input.equals("stop")) {
b = "stop";
}
else {
String temp = "";
char d;
String c="";
char cd=' ';
char ab=' ';
for (i = 0; i < input.length()&& c!="comment"; i++) {
if (ab=='s') {
if (input.charAt(i)=='\"') {
temp=temp+"\"";
t. word(temp,count,vp,cp);
list.add(t);
temp="";
ab=' ';
}
else {
temp=temp+input.charAt(i);
}
}
and that is my word method where I am passing the word which I get I get from another method
void word(String word ,int count,String cp,String vp) {
switch (word) {
case "int":
case "char":
case "float":
case "string":
case "boolean":
cp="datatype";
vp=word;
line=count;
System.out.println("Token: [ CP: " + cp + ", VP: " + vp + ", Line: " + line + "]");
break;
Override the toString method of the Object class. example:
public class Employee {
private String Name;
public Employee(String name) {
Name = name;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
#Override
public String toString() {
return "Employee{" +
"Name='" + Name + '\'' +
'}';
}
public static void main(String[] args) {
List<Employee> list = new ArrayList();
list.add(new Employee("Bert"));
list.add(new Employee("Ernie"));
for (int q=0;q<list.size();q++){
System.out.println("list is "+list.get(q));
}
//alternate shorter for each for java 8+
list.forEach(System.out::println);
}
}
https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html

toString Not Following Correct Format

I am having trouble when I call my toString method and my code isn't following the correct format like it should, this is how I've been trying to call it.
public static void loadQueue(Queue<String> queue, String str) {
String elementArray[] = str.split(",");
for(int i = 0; i < elementArray.length; i++){
queue.push(elementArray[i]);
queue.toString();
}
}
Here is the toString that I want to format it to:
#Override
public String toString() {
String str = "[ ";
if ( !isEmpty() ) {
for (int i = 0; i < queue.length - 1; i++){
str += queue[i] + ", ";
}
str += queue[queue.length - 1] + " ";
}
str += "]";
return str;
Is there a better way to be calling this so that it prints out the correct out put?
Correct format should be [ a, b, c, d ] but all I'm getting is [ abcd ].
Edit, added toString method
If you're trying to use the values between commas in the str as the values to push onto the queue then you don't need to call toString().
Does this work for you?
public static void loadQueue(Queue<String> queue, String str) {
if (null == queue) throw new IllegalArgumentException("Expected non-null queue");
if (null == str) throw new IllegalArgumentException("Expected non-null str");
String elementArray[] = str.split(",");
for(int i = 0; i < elementArray.length; i++){
queue.push(elementArray[i]);
}
}
I can't tell which class your toString override is on, but it wouldn't be on string or queue.
Queue.toString will probably not be what you want. Is there some reason you want to override toString rather than just have a method by another name?
Technique #1
Put all the methods in your existing class
public String queueToString(Queue<String> queue) {
String str = "[ ";
if ( !isEmpty() ) {
for (int i = 0; i < queue.length - 1; i++){
str += queue[i] + ", ";
}
str += queue[queue.length - 1] + " ";
}
str += "]";
return str;
}
...
public static void loadQueue(Queue<String> queue, String str) {
String elementArray[] = str.split(",");
for(int i = 0; i < elementArray.length; i++){
queue.push(elementArray[i]);
}
System.out.println( queueToString(queue) );
}
Technique #2
Create a custom class for your queue and modify the behavior.
public class MyStringQueue extends Queue<String>
{
#Override
/* override the toString method here */
}
...
/* in your class, create an use a MyStringQueue instead of Queue<String> */
public static void loadQueue(MyStringQueue queue, String str) {
String elementArray[] = str.split(",");
for(int i = 0; i < elementArray.length; i++){
queue.push(elementArray[i]);
}
System.out.println( queue.toString() );
}

Hashset compare 2 string in ArrayList to find code

Hi I am trying to find a way to compare 2 String codes in a dynamic table that I made here's how I declare it:
this adds students
public void ajouteretudiants(Etudiant unetudiants) throws Exception {
if (nbreetudiantss >= 30) {
throw new Exception("Exces d'etudiants");
} else {
etudiants.add(unetudiants);
}
nbreetudiantss++;
this is to get the code of student (first letter of name + first letter of last name + birth year)
public String getCode() {
return this.code;
}
and here's how I try to get it for now:
public String toString() {
String chaine = " ";
for (int i = 0; i < nbreetudiantss; i++) {
chaine += etudiants.get(i).toString();
}
return chaine;
}
this is to class name in alphabetical order
public String listTriee(){
// trier le tableau etudiants en ordre alphabetique
Etudiant temp = null ;
for (int i=0; i<etudiants.size(); i++){
for (int j=i+1; j<etudiants.size(); j++)
if (etudiants.get(i).getNom().compareTo(etudiants.get(j).getNom()) > 0){
temp = etudiants.get(j);
etudiants.set(j,etudiants.get(i));
etudiants.set(i,temp);
}
}
return toString() ;
}
this is to search if the string we look for is in the table of students(here is my problem)
public String rechercher(String code){
Set<String> monHashSet=new HashSet<String>();
monHashSet.add(new String(etudiants.get(i).getCode()));
for (int i=0; i<etudiants.size(); i++){
}
return toString() ;
}
If you are able to use Java 8, you can implement something like this
Set<String> monHashSet = etudiants.stream()
.filter(code::equals)
.collect(Collectors.toSet());

Replace words in a string without using replace in Java

I am trying to replace all occurrences of a word in a string. However with this code I can only find the first occurrence of it and replace it. Is there any way to expand this code to replace the words in the entire string? I am attempting to do this without using the replace built in methods in Java since I already know how to use those function, I was wondering if there was another way to go about it.
public static String replace(String old, String newWord, String input) {
int i = input.indexOf(old);
if (i < 0) {
return input;
}
String partBefore = input.substring(0, i);
String partAfter = input.substring(i + old.length());
return partBefore + newWord + partAfter;
}
First, you need a loop of some kind. Probably a while.
In the loop, since you're replacing the "old" string, you could just keep looping until you don't find it anymore. But if you want to avoid re-searching the first part of the string, or if you want to allow the replacement to contain the string it's replacing (without then looping infinitely), then once you've done each replacement, use String#indexOf(String str, int fromIndex), which lets you continue from the middle of the string.
There is a simple solution that uses recursion. Once you have replaced the word for the first time in the string, you can then replace the word in the partAfter part of the string by calling the replace method again:
public static String replace(String old, String newWord, String input) {
int i = input.indexOf(old);
if (i < 0) {
return input;
}
String partBefore = input.substring(0, i);
String partAfter = input.substring(i + old.length());
return partBefore + newWord +
replace(old, newWord, partAfter); // <<-- Note recursion here
}
This only changes one line from your original source.
public static String replace(String old, String newWord, String input) {
int i = input.indexOf(old);
if (i < 0) {
return input;
}
String partBefore = input.substring(0, i);
String partAfter = input.substring(i + old.length());
return partBefore + newWord + replace(old, newWord, partAfter );
}
However, it's more efficient to collect the bits and pieces in a StringBuilder.
public static String replace(String oldStr, String newStr, String input) {
StringBuilder sb = new StringBuilder();
int i;
int prev = 0;
while( (i = input.indexOf(oldStr, prev)) >= 0 ){
sb.append( input.substring(prev, i) ).append( newStr );
prev = i + oldStr.length();
}
sb.append(input.substring(prev));
return sb.toString();
}
First of all, don't use new for a variable name. It's a reserved word.
Second of all, in order to replace multiple occurences, you should have a loop.
Finally, it's better to create the new String using a StringBuilder, not String concatenation.
This is untested, but something like this should work:
public static String replace(String oldStr, String newStr, String input) {
int i = input.indexOf(oldStr);
if (i < 0) {
return input;
}
StringBuilder buffer = new StringBuilder();
int prev = 0;
while (i >= 0) {
String partBefore = input.substring(prev, i);
prev = i + oldStr.length();
buffer.append(partBefore);
buffer.append(newStr);
i = input.indexOf(oldStr, i + oldStr.length());
}
buffer.append(input.substring(i+oldStr.length()));
return buffer.toString();
}
Use Recursion:
public static String replaceAll(String old, String newWord, String input) {
int i = input.indexOf(old);
if (i < 0)
return input;
String partBefore = input.substring(0, i);
String partAfter = input.substring(i + old.length());
return replaceAll(old, newWord, partBefore + newWord + partAfter);
}
Use do-While and go on replacing words:
public static String replaceAll(String old, String newWord, String input) {
boolean loop = true;
do {
int i = input.indexOf(old);
if (i > 0) {
String partBefore = input.substring(0, i);
String partAfter = input.substring(i + old.length());
input = partBefore + newWord + partAfter;
} else
loop = false;
} while (loop);
return input;
}
Here is the Code
import java.util.Scanner;
public class replacechar {
String line;
String s = "";
char from ;
char to ;
public replacechar()
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter The String");
line = scan.nextLine();
System.out.println("Enter The Character you want to changer");
from = scan.nextLine().charAt(0);
System.out.println("Enter the Character you want to replace with");
to = scan.nextLine().charAt(0);
replacecharacter(from,to);
}
public void replacecharacter(char f,char t)
{
for(int i =0;i< line.length();i++)
{
if(line.charAt(i) == f)
{
s += t;
}
else
{
s += line.charAt(i);
}
}
System.out.println(s);
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
replacechar obj = new replacechar();
}
}
Not too sure if OP is still looking for answers but it might help others. Here is my code with just for loop and java's substring method...
public static void main(String ar[])
{
String str = "This is some string. replace lower case is with IS";
String pattern = "is";
String replaceWith = "IS"; // word to replace with
System.out.println(replaceString(str, pattern, replaceWith));
}
static String replaceString(String str, String pattern, String replaceWith) {
String temp = "";
String replacedString = ""; // Replaced String
int remainingString = 0; // append the rest of the string after last
// occurance of pattern.
for (int i = 0; i <= str.length() - pattern.length(); i++) {
temp = str.substring(i, i + 1);
if (str.substring(i, i + pattern.length()).equals(pattern)) {
temp = replaceWith + " ";
i += pattern.length();
}
remainingString = i;
replacedString += temp;
}
replacedString += str.substring(remainingString + 1, str.length());
return replacedString;
}
}
Posting this here incase somebody needs an implementation without using StringUtils helper methods.
static String replaceAll(String str, String oldW, String newW) {
// code here
char[] ch = str.toCharArray();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < ch.length;i++) {
if (ch[i] == oldW.charAt(0) && checkForString(i+1,oldW,str)) {
sb.append(newW);
i += oldW.length() -1;
}
else
sb.append(ch[i]);
}
return sb.toString();
}
static boolean checkForString(int i, String str,String ogStr) {
int start = i;
for (int j = 1; j < str.length() && i < ogStr.length(); j++, i++) {
if (ogStr.charAt(i) != str.charAt(j))
return false;
}
return (i-start+1) == str.length()?true:false;
}

Recursion - Double each char of a string input and cut of the last char afterwards with one method [duplicate]

I have the following problem.
The recursive method public static String doSomeMagic("Test") should return:
TTeesstt
TTeess
TTee
TT
I've implemented this behaviour already like this:
public static String rowFunction(String s) {
String toReturn = new String();
if (!s.isEmpty()) {
toReturn = String.valueOf(s.charAt(0));
toReturn += toReturn + rowFunction(s.substring(1));
}
return toReturn;
}
public static String doSomeMagic(String s) {
String toReturn = new String();
if (!s.isEmpty()) {
toReturn = rowFunction(s) + "\n" + doSomeMagic(s.substring(0, s.length() - 1));
}
return toReturn;
}
How can one achieve this with just one function? Any ideas?
I noticed you wanted to do this without a loop and in one function call. You can probably clean this up a lot more. Here it is:
public static String doSomeMagic(String s) {
if (!s.isEmpty()) {
StringBuffer sb = new StringBuffer();
return sb.append(s.replaceAll("(\\S)", "$1$1"))
.append("\n")
.append(doSomeMagic( s.replaceAll(".$", "") )
.toString();
}
return "";
}
To do it in one function, just iterate over the string rather than calling another recursive function.
public static String doSomeMagic(String s) {
String doubled = new String();
if (s.length() == 0) return s;
for(int i=0;i<s.length();i++)
doubled += s.substring(i,i+1) + s.substring(i,i+1)
return doubled + "\n" + doSomeMagic(s.substring(0, s.length()-1));
}
Quick solution could be like
testMethod(string ip){
if(ip.length()==1){
ip=ip.toUppercase();
}
For(int i=0;i<ip.length()-1;i++){
System.out.print(ip.charAt(i)+""+ip.charAt(i));
}
if(ip.length()>1){
System. out. println();
testMethod(ip.substring(1));
}
}
Haven't tested it... But should work fairly

Categories