So I have an object which I import in another object
First object:
package test;
import java.util.*;
public class Eveniment {
int ziua;
String luna = new String();
public void setZiua(int param){
ziua = param;
}
public void setLuna(String param){
luna = param;
}
public int getZiua(){
return ziua;
}
public String getLuna(){
return luna;
}
}
Second object:
package test;
import test.*;
import java.util.*;
public class EventPlanner {
public static void main(String[] args){
ArrayList<Eveniment> myAr = new ArrayList();
Scanner sc = new Scanner(System.in);
System.out.println("Introduceti ziua urmata de luna evenimentului: ");
int zi = 0;
String luna;
zi = sc.nextInt();
luna = sc.nextLine();
Eveniment first = new Eveniment();
first.setZiua(zi);
first.setLuna(luna);
myAr.add(first);
while(luna!=null && zi!=0)
{
zi = sc.nextInt();
luna = sc.nextLine();
if(zi!=0)
{
Eveniment ev = new Eveniment();
ev.setZiua(zi);
ev.setLuna(luna);
myAr.add(ev);
}
}
String l = new String();
l = "Ianuarie";
System.out.println(myAr.size());*/
for(int i = 0; i < myAr.size(); i++){
if(myAr.get(i).getLuna().equals(l))
System.out.println(1);
else
System.out.println(0);
}
}
public static void afisare(ArrayList<Eveniment> myAr){
System.out.println("---------Array------------");
for(Eveniment i : myAr){
System.out.println(i.getLuna() +" "+i.getZiua());
}
}
}
The thing that bugs me is that inside the for I do a check if a current object has it's luna string equal to l string then I print out 1 else I print 0, but the algorithm prints out 0 even if the strings are equal, what am I doing wrong ?
I'm a newbie with Java so please don't judge too harshly.
Input given to the program:
1 Decembrie
2 Ianuarie
3 Februarie
4 Martie
0//to end the input
The program should write
`Decembrie` 0
`Ianuarie` 1
`Februarie` 0
`Martie` 0
because l is equal to Ianuarie.
this is because
l = "Ianuarie"
and
myAr.get(i).getLuna() =" Ianuarie"
^--->there are space before the Ianuarie
so you will never get 1
Related
I am trying to load data from a txt file and it will only read one line of the txt file. When I specify what the int I variable is in my for loop within my loadData method it will print that particular line. I am not sure why it won't just add and print all my data.
I tried using an outer for loop to see if would print and add the data that way, but no luck
import java.io.*;
import java.util.*;
public class BingoSortTest
{
static BingoPlayer [] test;
public static void main (String [] args) throws IOException
{
Scanner keyboard = new Scanner(System.in);
test = new BingoPlayer [10];
loadData();
System.out.print(Arrays.toString(test));
}
public static void loadData() throws IOException
{
Scanner S = new Scanner(new FileInputStream("players.txt"));
double houseMoney = S.nextDouble();
S.nextLine();
int player = S.nextInt();
S.nextLine();
for(int i = 0; i < test.length; i++)
{
String line = S.nextLine();
String [] combo = line.split(",");
String first = combo [0];
String last = combo [1];
double playerMoney = Double.parseDouble(combo[2]);
BingoPlayer plays = new BingoPlayer(first, last, playerMoney);
add(plays);
}
}
public static void add(BingoPlayer d)
{
int count = 0;
if (count< test.length)
{
test[count] = d;
count++;
}
else
System.out.println("No room");
}
}
Here is the contents of the txt file I am using:
50.00
10
James,Smith,50.0
Michael,Smith,50.0
Robert,Smith,50.0
Maria,Garcia,50.0
David,Smith,50.0
Maria,Rodriguez,50.0
Mary,Smith,50.0
Maria,Hernandez,50.0
Maria,Martinez,50.0
James,Clapper,50.0
Every Time you put a BingoPlayer at Index 0 .
public static void add(BingoPlayer d)
{
int count = 0; // <-------------------- Here
if (count< test.length)
{
test[count] = d;
count++;
}
else
System.out.println("No room");
}
you have to define static counter variable where array of BingoPlayer is defined.
define count variable static
static BingoPlayer [] test;
static int count = 0;
and chane the add function definition like this.
public static void add(BingoPlayer d)
{
if (count< test.length) {
test[count] = d;
count++;
}
else
System.out.println("No room");
}
I would like to add multiple objects to an ArrayList but I can't do it with my code. Here is the code I'm currently using. In the for loop, its adding the same object to the ArrayList 5 times. Why is this occurring?
import java.util.ArrayList;
import java.util.Scanner;
public class newBook {
public int no;
public String isim;
public newBook(int no ,String isim){
this.no = no;
this.isim = isim;
}
#Override
public String toString(){
return " no = " + this.no +", name = " + this.isim;
}
public static void main(String args[]){
Scanner klavye = new Scanner(System.in);
int kitapNo = klavye.nextInt();
String kitapName = klavye.next();
ArrayList<newBook> liste = new ArrayList<>();
for(int i=0 ; i<5 ; i++){
liste.add( new newBook(kitapNo,kitapName));
//System.out.println("Çıkmak için -1 giriniz ");
//int i = klavye.nextInt();
}
for (newBook liste1 : liste) {
System.out.println(liste1);
}
}
}
They are not the same object, they just have the same content. You need to read the input from klavye inside the loop too.
ADDn - The first n (0 ≤ n ≤ 4) bits replicate and are concatenated to the first n bits. The last n bits are deleted
e.g. ADD3 ABCDEFGH becomes ABCABCDE
METHODS -
public class Methods
{
public String ADD(String x, int y)
{
if(y > 0)
{
String output = x.substring(0,y);
String output2 = x.substring(y, x.length() - y);
return output + output + output2;
}else {
return x;
}
}
RUNNER -
import java.io.*;
import java.util.*;
public class Runner
{
public static void main(String []args)throws FileNotFoundException
{
Scanner in = new Scanner(new File("data.txt"));
Methods md = new Methods();
String cell = in.nextLine();
String methods = in.nextLine();
for (int x = 0; x < 5; x++)
{
if(methods.equals(("ADD2"))
{
int i = Integer.parseInt(methods);
System.out.println( );
}
DATAFILE-
ADD2 ABBCDFGG
I need it to print ABABBCDF
class Problem {
public static void main(String[] args) {
for (int num = 1000; num <= 2000; num++) {
if (String.valueof(num).contains("3")) {
System.out.println(num);
}
}
}
}
I have a file with over 1000 names it also include the sex and how many people have the name.
example
Sarah F 2000
I am trying to print the first 10 lines that was created from my for loop, but for some reason what i tried is only printing the last line 10 times.
import java.util.*;
import java.io.*;
import java.util.Collections;
public class NameYear
{
private String year;
ArrayList<OneName> oneName = new ArrayList<OneName>();
public NameYear(String year)
{
String line = "";
String Top = "";
Scanner sc = null;
try
{
sc = new Scanner(new File
("/home/mathcs/courses/cs225/koch/names/yob"+year+".txt"));
}
catch (Exception e)
{
System.out.println("Error Year should be between 1880 and 2013 not "+ year);
System.exit(1);
}
while(sc.hasNextLine())
{
// read a line from the input file via sc into line
line = sc.nextLine();
StringTokenizer stk = new StringTokenizer(line, ",");
String name = stk.nextToken();
char sex = stk.nextToken().charAt(0);
int count = Integer.parseInt(stk.nextToken());
OneName list = new OneName(name, sex, count);
oneName.add(list);
}
for (int i = 0 ; i < 10; i++)
{
System.out.println(descending());
}
public String descending()
{
String x = "";
Collections.sort(oneName, new OneNameCountCompare());
for(OneName b: oneName)
{
x = b.toString();
}
return x;
OneName file
public class OneName
{
private String Name;
private char Sex;
private int Count;
public OneName(String name, char sex, int count)
{
Name = name;
Sex = sex;
Count = count;
}
public String getName()
{
return Name;
}
public char getSex()
{
return Sex;
}
public int getCount()
{
return Count;
}
public void setName(String name)
{
if (name.length() < 1)
{
throw new NullPointerException("Baby name is missing");
}
Name = name;
}
private char M;
private char F;
public void setSex(char sex)
{
if( sex != M)
{
if(sex != F)
{
throw new IllegalArgumentException("Sex has to be M or F");
}
}
Sex = sex;
}
public void setCount(int count)
{
if(count < 0)
{
throw new IllegalArgumentException("Count cant be negative");
}
Count = count;
}
public String toString()
{
return String.format("%s %c %d", Name, Sex, Count);
}
}
OneNameCount
import java.util.Comparator;
import java.util.Collections;
public class OneNameCountCompare implements Comparator<OneName>
{
public int compare(OneName b1, OneName b2)
{
if(b1.getCount() <b2.getCount())
{
return 1;
}
else
{
return -1;
}
}
}
Main Program
import java.io.*;
import java.util.*;
public class TopNames
{
public static void main(String args[])
{
String line = ""; // string var to hold entire line
if (args.length < 1)
{
System.out.println("\nYou forgot to put a Year on the command line.");
System.exit(1);
};
String inFile = args[0]; // file name off command line
String year = inFile;
NameYear list = new NameYear(year);
}
}
Your descending function returns one string, and always the same string (the last one in the order after sorting the collection). It doesn't matter how often you call it, if the data doesn't change, you'll always get back that same, last, string.
If you want the first 10 after sorting, descending would need to return a List<String> containing those 10:
public List<String> descending()
{
List<String> x = new ArrayList<String>(10);
Collections.sort(oneName, new OneNameCountCompare());
for(OneName b: oneName)
{
x.add(b.toString());
if (x.size() == 10) // Or don't use enhanced for, use an index instead
{
break;
}
}
return x;
}
Then when printing it, replace your for (int i = 0 ; i < 10; i++) loop with:
for (String s : descending())
{
System.out.println(s);
}
Your error is here:
for (int i = 0 ; i < 10; i++) {
System.out.println(descending());
}
public String descending() {
String x = "";
Collections.sort(oneName, new OneNameCountCompare());
for(OneName b: oneName) {
x = b.toString();
}
return x;
}
First of all in your for loop you are not using the i variable that is your count indicator. This means that the descending() method has no any awareness of i, how he could return something different?
Try to modify descending() in something like this:
public String descending(int i) {
String x = "";
Collections.sort(oneName, new OneNameCountCompare());
OneName b = oneName.get(i);
x = b.toString();
return x;
}
My program is working fine on all parts except one. I am attempting to post as little code as possible. Please let me know if more is needed.
How do I find the name that occurs the most in a String, or StringBuilder? The "getWinner" method is where I am having trouble. I want to find the name (or winner) that occurs the most in a string. If their is a tie, the name that appears first is sufficient. Thanks in advance!
import java.util.ArrayList;
public class BallotBox
{
private ArrayList<String> ballots;
public BallotBox()
{
ballots = new ArrayList<String>();
}
public void addVote(String candidate)
{
ballots.add(candidate);
}
//****below is the method that's presenting a problem.****
public String getWinner()
{
StringBuilder candidates = new StringBuilder();
String winner = "";
for(int i = 0; i < ballots.size(); i++)
{
}
return winner;
}
public int getVoteCount(String candidate)
{
int count = 0;
for(int i = 0; i < ballots.size(); i++)
{
if(ballots.get(i).equals(candidate))
{
count++;
}
}
return count;
}
public String getResults()
{
StringBuilder resultTable = new StringBuilder();
ArrayList<String> printed = new ArrayList<String>();
for (String candidate : ballots)
{
if (!printed.contains(candidate))
{
resultTable.append(String.format("%s (%d)\n", candidate, getVoteCount(candidate)));
printed.add(candidate);
}
}
return resultTable.toString();
}
}
You can try to convert the list to a Set and use the Collections.frequency method.
Set<String> uniqueSet = new HashSet<String>(list);
for (String temp : uniqueSet)
{
System.out.println(temp + ": " + Collections.frequency(list, temp));
}
You'll get the output as shown below.
d: 1
b: 2
c: 2
a: 4
Check the link for more details
http://www.mkyong.com/java/how-to-count-duplicated-items-in-java-list/
You can use a HashMap to keep the votes for every candidate, and update the winner as soon as you find a new winner (more votes than the current winner):
public String getWinner()
{
final Map<String, Integer> votesCount = new HashMap<String, Integer>();
String winner = ballots.get(0);
int winnerVotes = 1;
for(final String ballot : ballots)
{
if (!votesCount.containsKey(ballot))
votesCount.put(ballot, 0);
votesCount.put(ballot, votesCount.get(ballot)+1);
if (votesCount.get(ballot)>winnerVotes)
{
winner = ballot;
winnerVotes = votesCount.get(ballot);
}
}
return winner;
}
Here is a working example. Hope this explains how the above code can be used in your application.
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class BallotBox
{
private ArrayList<String> ballots;
public BallotBox()
{
ballots = new ArrayList<String>();
ballots.add("John");
ballots.add("Eric");
ballots.add("Mary");
ballots.add("Eric");
ballots.add("Mary");
ballots.add("Mary");
ballots.add("John");
ballots.add("Mary");
}
public void addVote(String candidate)
{
ballots.add(candidate);
}
// ****below is the method that's presenting a problem.****
public String getWinner()
{
String winner = "";
// To check who has the highest votes.
int highestVotes = 0;
Set<String> uniqueSet = new HashSet<String>(ballots);
for (String temp : uniqueSet)
{
// The count of each Candidate's votes.
int count = Collections.frequency(ballots, temp);
// The winner is the one with the highest votes.
if(count > highestVotes)
{
highestVotes = count;
winner = temp;
}
}
return winner;
}
public static void main(String[] args)
{
BallotBox ballotBox = new BallotBox();
System.out.println(ballotBox.getWinner());
}
}