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
Related
The problem is that it must compare two Strings (example in a text file), and show the differences in it.
Should in the output also be printed out the equals Elements ?
Instead of using for loops, maybe there are different solutions to reach it.
How can it be done ?
Code
import java.util.ArrayList;
public class ParseTest {
String saR1 = "This is a Test for checking the content and a Test to compare it";
String saR2 = "This is the second Test for checking the seconds content and a second Test to compare it";
String diff1 = "";
String diff2 = "";
int o3;
int o4;
public static void main(String[] args) {
new ParseTest().parseMethod();
}
private void parseMethod() {
String[] sa1 = saR1.split("\\s");
String[] sa2 = saR2.split("\\s");
ArrayList<String> al1 = new ArrayList<String>();
ArrayList<String> al2 = new ArrayList<String>();
for(int o = 0; o<sa1.length; o++) {
al1.add(sa1[o]);
}
for(int o = 0; o<sa2.length; o++) {
al2.add(sa2[o]);
}
if(al1.size() <= al2.size()) {
for(int oi = 0; oi<al2.size()+al1.size(); oi++) {
for(o4 = 0; o4<al2.size(); o4++) {
for(o3 = 0; o3<al1.size(); o3++) {
if(al1.size() == al2.size() && al2.get(o4).equalsIgnoreCase(al1.get(o3))) {
al1.remove(al1.get(o3));
al2.remove(al2.get(o4));
}
if(al2.size() > al1.size() && al2.get(o4).equalsIgnoreCase(al1.get(o3))) {
al1.remove(al1.get(o3));
al2.remove(al2.get(o4));
}
}
}
}
}
for(String or1 : al1) {
diff1 += " " + or1;
} System.out.println("This is saR1 :" + saR1);
System.out.println("This is the difference in saR1 :" + diff1);
for(String or2 : al2) {
diff2 += " " + or2;
} System.out.println("This is saR2 :" + saR2);
System.out.println("This is the difference in saR2 :" + diff2);
}}
A possible solution :
package parsetest;
import java.util.ArrayList;
public class ParseTest {
String saR1 = "This is a Test for checking the content and a Test to compare it";
String saR2 = "This is the second Test for checking the seconds content and a second Test to compare it";
String diff1 = "";
String diff2 = "";
int o3;
int o4;
public static void main(String[] args) {
new ParseTest().parseMethod();
}
private void parseMethod() {
String[] sa1 = saR1.split("\\s"); // split into single words
String[] sa2 = saR2.split("\\s");
ArrayList<String> al1 = new ArrayList<String>(); // create ArrayList with more methods to manipulate, avaiable from the api
ArrayList<String> al2 = new ArrayList<String>();
for(int o = 0; o<sa1.length; o++) { // adding single elements of array[] to ArrayList
al1.add(sa1[o]);
}
for(int o = 0; o<sa2.length; o++) {
al2.add(sa2[o]);
}
if(al1.size() <= al2.size()) {
for(int oi = 0; oi<al2.size()+al1.size(); oi++) {
for(o4 = 0; o4<al2.size(); o4++) {
for(o3 = 0; o3<al1.size(); o3++) {
if(al1.size() == al2.size() && al2.get(o4).equalsIgnoreCase(al1.get(o3))) {
al1.remove(al1.get(o3));
al2.remove(al2.get(o4));
}
if(al2.size() > al1.size() && al2.get(o4).equalsIgnoreCase(al1.get(o3))) {
al1.remove(al1.get(o3));
al2.remove(al2.get(o4));
}
}
}
}
}
for(String or1 : al1) { // walking thru the arraylists with remaining elements and printing out results
diff1 += " " + or1;
} System.out.println("This is saR1 :" + saR1);
System.out.println("This is the difference in saR1 :" + diff1);
for(String or2 : al2) {
diff2 += " " + or2;
} System.out.println("This is saR2 :" + saR2);
System.out.println("This is the difference in saR2 :" + diff2);
}}
I have two Comparators. One for sorting words by first letter (in sort used only for vowel words)
public class FirstLetterComparator extends ComparatorType {
#Override
public int compare(String o1, String o2) {
String upperObject1 = o1.toUpperCase();
String upperObject2 = o2.toUpperCase();
return upperObject1.charAt(0) - upperObject2.charAt(0);
}
}
Another for sorting by length/vowelsCount coef(used for all words in sort class)
public class VowelColComparator extends ComparatorType {
String vowelGroup = "AEIOUaeiou";
#Override
public int compare(String o1, String o2) {
int vCount1 = getVowelCount(o1);
int vCount2 = getVowelCount(o2);
float compareCoef1 = o1.length()/vCount1;
float compareCoef2 = o2.length()/vCount2;
return (int)(compareCoef1 - compareCoef2);
}
public int getVowelCount(String word){
int vowelCount = 0;
for (int i = 0; i < word.length(); i++){
char ch = word.charAt(i);
for (int j = 0; j < vowelGroup.length(); j++){
char v = vowelGroup.charAt(j);
if(ch == v)
vowelCount++;
}
}
return vowelCount;
}
And their superclass
public class ComparatorType implements Comparator<String> {
#Override
public int compare(String o1, String o2) {
return 0;
}
}
In sort class i have two similar methods for sorting my list
public class SortWords {
public static void sortVowelCol(String text, String regex){
Scanner scanner = new Scanner(text);
List<String> words = new ArrayList<>();
System.out.println();
System.out.println("Task1:");
while (scanner.hasNext()){
String word = scanner.next();
if(word.matches(regex)){
words.add(word);
}
}
Collections.sort(words, new VowelColComparator());
int lineCounter = 1;
System.out.println();
System.out.println();
System.out.println("Sorted Words:");
lineCounter = 1;
for(String w : words){
if(lineCounter == 12) {
System.out.print(w + "\n");
lineCounter = 0;
}
else
System.out.print(w + " ");
lineCounter++;
}
}
public static void sortVowelWords(String text, String regex) {
Scanner scanner = new Scanner(text);
List<String> vowelWords = new ArrayList<>();
System.out.println();
System.out.println("Task2: ");
while(scanner.hasNext()){
String word = scanner.next();
if(word.matches(regex)){
vowelWords.add(word);
}
}
Collections.sort(vowelWords, new FirstLetterComparator());
System.out.println();
System.out.println();
System.out.println("Sorted List:");
int lineCounter = 1;
for(String w : vowelWords){
if(lineCounter == 12) {
System.out.print(w + "\n");
lineCounter = 0;
}
else
System.out.print(w + " ");
lineCounter++;
}
}
}
Main class
public class Main {
public static void main(String[] args) {
// write your code here
SingletonText.getInstance().parse();
SingletonText.getInstance().print();
SortWords.sortVowelWords(SingletonText.getInstance().getText().toString(), "^[AEIOUaeiou].*");
SortWords.sortVowelCol(SingletonText.getInstance().getText().toString(), "^[A-Za-z].*");
}
}
The quesuion is how can i make only one method instead of two similar methods in SortWords class? Or how to get comparator type in for Collections.sort argument?
You may use a third parameter to define the comparator to use.
public static void sort(String text, String regex, ComparatorType comp) {
// Code
Collections.sort(words, comp);
// Code
}
you need refactor two function like that:
public static void sortVowel(String text, String regex,Comparator comparator) {
Scanner scanner = new Scanner(text);
List<String> vowelWords = new ArrayList<>();
System.out.println();
System.out.println("Task2: ");
while(scanner.hasNext()){
String word = scanner.next();
if(word.matches(regex)){
vowelWords.add(word);
}
}
Collections.sort(vowelWords, comparator);
System.out.println();
System.out.println();
System.out.println("Sorted List:");
int lineCounter = 1;
for(String w : vowelWords){
if(lineCounter == 12) {
System.out.print(w + "\n");
lineCounter = 0;
}
else
System.out.print(w + " ");
lineCounter++;
}
}
}
public static void sort(String text, String regex, String sortType) {
Collections.sort(words, sorttype.equals("Vowel") ? new VowelColComparator() : new FirstLetterComparator());
// Your code
}
Then we can call like this
SortWords.sort(SingletonText.getInstance().getText().toString(), "^[AEIOUaeiou].*", "Vowel");
SortWords.sort(SingletonText.getInstance().getText().toString(), "^[A-Za-z].*", "firstletter");
First of all your VowelColComparator.getVowelCount may fail due to division by zero when there is no vowel in given string. As you are comparing ratios of length and vowel count, you can do the following:
float compareCoef1 = o1.length()/(vCount1+1);
float compareCoef2 = o2.length()/(vCount2+1);
You can use factory pattern in ComparatorType class. i.e ComparatorType class will decide which instance (comparator) to use depending upon regex. You can add as many comparators as you like.
public abstract class ComparatorType implements Comparator<String> {
final public String vowelFirstLetterRegex = "^[A-Za-z].*";
final public String vowelColRegex = "^[AEIOUaeiou].*]";
public static ComparatorType getInstance(String regex) {
if (regex.equals(vowelColRegex))
return new VowelColComparator();
else if(regex.equals(vowelFirstLetterRegex ))
return new FirstLetterComparator();
return null;
}
}
And your SortWords class will have following method:
public static void sort(String text, String regex){
Scanner scanner = new Scanner(text);
List<String> words = new ArrayList<>();
System.out.println();
System.out.println("Task1:");
while (scanner.hasNext()){
String word = scanner.next();
if(word.matches(regex)){
words.add(word);
}
}
Collections.sort(words, ComparatorType.getInstance(regex));
int lineCounter = 1;
System.out.println();
System.out.println();
System.out.println("Sorted Words:");
lineCounter = 1;
for(String w : words){
if(lineCounter == 12) {
System.out.print(w + "\n");
lineCounter = 0;
}
else
System.out.print(w + " ");
lineCounter++;
}
}
Well, as everyone said, you need to pass Comparator<String> as the third argument to your method:
sortVowelWords(String text, String regex, Comparator<String> cmp) {
//...
}
I'd like to suggest some improvements to comparators themselves. Using lambda syntax, they may be written far more easily:
static final Comparator<String> CMP_BY_FIRST_CHAR =
Comparator.comparing(s -> Character.toUpperCase(s.charAt(0)));
static final Comparator<String> CMP_BY_VOWEL_COEF =
Comparator.comparing(s -> 1f * s.length() / s.replaceAll("[^AEIOUaeiou]+", "").length());
In second comparator, I added explicit cast to float to handle possible infinity values properly.
I'm working on a project where I have a text file with the first line being the size of the array I'll need and then subsequent lines have course information in the following order: dept, num, title. (ex. CSC 101 Basic Computing) My code complies but when it runs the first index in the array becomes the default(i.e. nothing) and therefore the last line in the text file doesn't get stored or printed. I'm wondering how I can fix this error.
import java.util.Scanner;
import java.io.*;
public class Organizer {
public static void main(String[] args) {
Scanner fileScanner = null;
String file;
File f = null;
//Create a Do While loop in order to prompt the user for a input file
//and then continue prompting if the file entered does not exist.
do {
try {
System.out.print("What is the name of the input file? ");
Scanner inputReader = new Scanner(System.in);
file = inputReader.nextLine();
f = new File(file);
fileScanner = new Scanner(new File(file));
//Catch the exception and tell the user to try again
} catch (FileNotFoundException e) {
System.out.println("Error scanning that file, please try again.");
}
} while (!f.exists());
//Testing the Make Array Method
//System.out.print(makeArray(fileScanner));
//Testing the print Array Method
printArray(makeArray(fileScanner));
}
public static Course[] makeArray(Scanner s) {
int arraySize = s.nextInt();
String title = "";
String dept = "";
int num = 0;
Course[] a = new Course[arraySize];
for (int i = 0; i < a.length; i++) {
a[i] = new Course(dept, num, title);
String oneLine = s.nextLine();
Scanner lineReader = new Scanner(oneLine);
while (lineReader.hasNext()) {
dept = lineReader.next();
a[i].setDept(dept);
num = lineReader.nextInt();
a[i].setNum(num);
while (lineReader.hasNext()) {
title = title + lineReader.next() + " ";
}
a[i].setTitle(title);
}
title = " ";
}
return a;
}
public static void printArray(Course[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i].toString());
}
}
}
Here is my other class.
public static class Course {
//INSTANCE VARIABLES
private String dept = "";
private int num = 0;
private String title = "";
//CONSTRUCTORS
public Course(String dept, int num) {
this.dept = dept;
this.num = num;
}
public Course(String dept, int num, String title) {
this.dept = dept;
this.num = num;
this.title = title;
}
public Course() {
this.dept = "AAA";
this.num = 100;
this.title = "A course";
}
//SETTER AND GETTER METHODS
public void setDept(String dept) {
this.dept = dept;
}
public void setNum(int num) {
this.num = num;
}
public void setTitle(String title) {
this.title = title;
}
public String getDept() {
return this.dept;
}
public int getNum() {
return this.num;
}
public String getTitle() {
return this.title;
}
//TOSTRING METHOD
public String toString() {
return dept + " " + num + ": " + title;
}
}
Don't forget where your cursor in your Scanner is at each moment.
s.nextLine() will read the whole line and then the cursor will jump to the next line, while s.nextInt() will read one int from your line and then stay there. It won't check if this has been the last input for that line.
Just fix your code to:
int arraySize = s.nextInt();
s.nextLine();
and your code should run just fine!
(also consider changing a[i].setTitle(title); to a[i].setTitle(title.trim());, since you will always be left with a white space at the end of your title..)
nextInt method does not consume the new line character. Here is a solution that works:
public static Course[] makeArray(Scanner s){
int arraySize = s.nextInt();
String title = "";
String dept = "";
int num = 0;
Course[] a = new Course[arraySize];
s.nextLine();
for (int i = 0; i < a.length; i++){
a[i] = new Course(dept, num, title);
String oneLine = s.nextLine();
Scanner lineReader = new Scanner(oneLine);
while (lineReader.hasNext()){
dept = lineReader.next();
a[i].setDept(dept);
num = lineReader.nextInt();
a[i].setNum(num);
while (lineReader.hasNext()){
title = title + lineReader.next() + " ";
}
a[i].setTitle(title);
}
title = " ";
}
return a;
}
i was wondering how can i create a method where i can get the single instance from a string and give it a numericValue for example, if theres a String a = "Hello what the hell" there are 4 l characters and i want to give a substring from the String a which is Hello and give it numeric values. Right now in my program it gets all the character instances from string so the substring hello would get number values from the substring hell too because it also has the same characters.
my code :
public class Puzzle {
private static char[] letters = {'a','b','c','d','e','f','g','h','i', 'j','k','l','m','n','o','p','q','r','s',
't','u','v','w','x','y','z'};
private static String input;
private static String delimiters = "\\s+|\\+|//+|=";
public static void main(String[]args)
{
input = "help + me = please";
System.out.println(putValues(input));
}
//method to put numeric values for substring from input
#SuppressWarnings("static-access")
public static long putValues(String input)
{
Integer count;
long answer = 0;
String first="";
String second = "";
StringBuffer sb = new StringBuffer(input);
int wordCounter = Countwords();
String[] words = countLetters();
System.out.println(input);
if(input.isEmpty())
{
System.out.println("Sisestage mingi s6na");
}
if(wordCounter == -1 ||countLetters().length < 1){
return -1;
}
for(Character s : input.toCharArray())
{
for(Character c : letters)
{
if(s.equals(c))
{
count = c.getNumericValue(c) - 9;
System.out.print(s.toUpperCase(s) +"="+ count + ", ");
}
}
if(words[0].contains(s.toString()))
{
count = s.getNumericValue(s);
//System.out.println(count);
first += count.toString();
}
if(words[3].contains(s.toString())){
count = s.getNumericValue(s);
second += count.toString();
}
}
try {
answer = Long.parseLong(first)+ Long.parseLong(second);
} catch(NumberFormatException ex)
{
System.out.println(ex);
}
System.out.println("\n" + first + " + " + second + " = " + answer);
return answer;
}
public static int Countwords()
{
String[] countWords = input.split(" ");
int counter = countWords.length - 2;
if(counter == 0) {
System.out.println("Sisend puudu!");
return -1;
}
if(counter > 1 && counter < 3) {
System.out.println("3 sõna peab olema");
return -1;
}
if(counter > 3) {
System.out.println("3 sõna max!");
return -1;
}
return counter;
}
//method which splits input String and returns it as an Array so i can put numeric values after in the
//putValue method
public static String[] countLetters()
{
int counter = 0;
String[] words = input.split(delimiters);
for(int i = 0; i < words.length;i++) {
counter = words[i].length();
if(words[i].length() > 18) {
System.out.println("One word can only be less than 18 chars");
}
}
return words;
}
Program has to solve the word puzzles where you have to guess which digit corresponds to which letter to make a given equality valid. Each letter must correspond to a different decimal digit, and leading zeros are not allowed in the numbers.
For example, the puzzle SEND+MORE=MONEY has exactly one solution: S=9, E=5, N=6, D=7, M=1, O=0, R=8, Y=2, giving 9567+1085=10652.
import java.util.ArrayList;
public class main {
private static String ChangeString;
private static String[] ArrayA;
private static String a;
private static int wordnumber;
private static String temp;
public static void main(String[] args) {
// TODO Auto-generated method stub
a = "hello what the hell";
wordnumber = 0;
identifyint(a,wordnumber);
}
public static void identifyint (String a, int WhichWord){
ChangeString = a.split(" ")[WhichWord];
ArrayA = a.split(" ");
replaceword();
ArrayA[wordnumber] = ChangeString;
//System.out.print(ArrayA[wordnumber]);
a = "";
for(int i = 0; i<ArrayA.length;i++){
if(i==wordnumber){
a = a.concat(temp+ " ");
}
else{
a = a.concat(ArrayA[i]+" ");
}
}
System.out.print(a);
}
public static void replaceword(){
temp = "";
Character arr[] = new Character[ChangeString.length()];
for(int i = 0; i<ChangeString.length();i++){
arr[i] = ChangeString.charAt(i);
Integer k = arr[i].getNumericValue(arr[i])-9;
temp = temp.concat(""+k);
}
a = temp;
}
}
Change wordnumber to the word you want to replace each time. If this is not what you have asked for, please explain your question in more detail.
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());