Getting the output from a arraylist - java

Im fairly new to java and ive been doing som searching for an answer to my problem but i just cant seem to get the output from the arraylist.
I get a red mark under Ordtildikt String arrayoutput = kontrollObjekt.Ordtildikt;saying it cannot be resolved or is not a field. The program is supposed to get userinput and create an arraylist from the input
Interface class
import javax.swing.JOptionPane;
public class Grensesnitt {
public static void main(String[] args) {
Grensesnitt Grensesnitt = new Grensesnitt();
Grensesnitt.meny();
}
Kontroll kontrollObjekt = new Kontroll();
private final String[] ALTERNATIVER = {"Registrere ord","Skriv dikt","Avslutt"};
private final int REG = 0;
private final int SKRIV = 1;
public void meny() {
boolean fortsett = true;
while(fortsett) {
int valg = JOptionPane.showOptionDialog(
null,
"Gjør et valg:",
"Prosjektmeny",
JOptionPane.DEFAULT_OPTION,
JOptionPane.PLAIN_MESSAGE,
null,
ALTERNATIVER,
ALTERNATIVER[0]);
switch(valg) {
case REG: regNy();
break;
case SKRIV: regDikt();
break;
default: fortsett = false;
}
}
}
int i = 0;
public void regNy() {
while(i<=16)
{
String Ord = JOptionPane.showInputDialog("Skriv or til diktet: ");
kontrollObjekt.regNy(Ord);
//String Diktord = JOptionPane.showInputDialog("Skriv ord til diktet: ");
//kontrollObjekt.regNy(Diktord);
i = i + 1;
}
}
public void regDikt() {
String arrayoutput = kontrollObjekt.Ordtildikt;
JOptionPane.showMessageDialog(null, arrayoutput);
}
//JOptionPane.showMessageDialog(null, kontrollObjekt.Diktord);
}
Controll Class
import java.util.ArrayList;
public class Kontroll {
public ArrayList<String> Diktord = new ArrayList<String>();
public void regNy(String Ord) {
Diktord.add(Ord);
Diktord.add("\n");
}
public String Ordtildikt(String Ord) {
return Ord=Diktord.toString();
}
}

This is a method, not a variable.
kontrollObjekt.Ordtildikt;
You are trying to call this?
public String Ordtildikt(String Ord) {
return Ord=Diktord.toString();
}
1) Make it return Diktord.toString();
2) Get rid of String Ord unless you are going to use that parameter
3) Actually call the method, e.g. Put some parenthesis.
String arrayoutput = kontrollObjekt.Ordtildikt();
Also, I think this should be the correct regNy method unless you want to falsely report that the list is twice its size.
public void regNy(String Ord) {
Diktord.add(Ord + "\n");
}

Related

null output in multiple choice array

my output of my java application is running null values for the output of Q4 and 5, tried fixing it but had no luck swapping out the null values for the actual string question needed to be shown just before the user input
MultipleChoiceQuestions.java
import java.util.Arrays;
import java.util.Scanner;
public class MultipleChoiceQuestion extends Question{
private int count = 0 ;
private String cho1, cho2, cho3, cho4 ;
private boolean bool1, bool2, bool3, bool4 ;
private final String[] newchoice = new String[4];
public MultipleChoiceQuestion(String text, String cho1, boolean bool1,
String cho2, boolean bool2,
String cho3, boolean bool3,
String cho4, boolean bool4) {
super(text);
this.cho1 = cho1; this.cho2 = cho2;
this.cho3 = cho3; this.cho4 = cho4;
this.bool1 = bool1; this.bool2 = bool2;
this.bool3 = bool3; this.bool4 = bool4;
}
public void addChoice(String Choices, boolean isCorrect){
this.newchoice[count]= Choices;
if(isCorrect) {
super.setCorrectResponse(Choices);
}
count++ ;
}
public void initQuestion(){
addChoices(cho1, bool1);
addChoices(cho2, bool2);
addChoices(cho3, bool3);
addChoices(cho4, bool4);
}
#Override
public String toString(){
StringBuilder sbf = new StringBuilder(super.toString());
sbf.append(Arrays.toString(newchoice));
return sbf.toString();
}
private void addChoices(String cho1, boolean bool1) {
throw new UnsupportedOperationException("Not supported yet."); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody
}
}
FillInTheBlankQuestion.java
import java.util.Scanner;
public class FillInTheBlankQuestion extends Question{
public FillInTheBlankQuestion(String text){
super(text);
}
public void extractQA(){
Scanner scan = new Scanner(super.getQuestionText());
scan.useDelimiter("_");
super.setQuestionText(scan.next());
super.setCorrectResponse(scan.next());
}
public String toString(){
return super.toString() + "______________";
}
}
Question.java
import java.util.Scanner;
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
/**
*
* #author --
*/
public class Question {
private String questionText;
private String correctResponse;
//Creates a question with an empty question and answer
public Question(){
this.setQuestionText("");
this.setCorrectResponse("");
}
public Question(String text){
this.setQuestionText(text);
}
public Question(String text, String answer){
this.setQuestionText(text);
this.setCorrectResponse(answer);
}
//sets the text of this question
public void setQuestionText(String text){
this.questionText = text;
}
//sets the answer for this question
public void setCorrectResponse(String answer){
this.correctResponse = answer;
}
public String getQuestionText(){
return this.questionText;
}
public String getCorrectResponse(){
return this.correctResponse;
}
/*
checks the response/answer given for correctness
#param givenResponse The response to check
return true if the response is correct, false otherwise
*/
public boolean verifyAnswer(String givenResponse){
//it does not take into account upper/lower case characters.
return givenResponse.equalsIgnoreCase(this.getCorrectResponse());
}
//allows user to type the answer
public void inputAnswer(Scanner scan){
System.out.print("Type your answer:");
System.out.println(this.verifyAnswer(scan.nextLine()));
}
//display the question
#Override
public String toString(){
return this.getQuestionText();
}
}
QuestionTester.java
import java.util.Scanner;
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Main.java to edit this template
*/
/**
*
* #author ---
*/
public class QuizTester {
public QuizTester(){
Scanner in = new Scanner(System.in);
//declare an array quiz that can hold a mixture of Question and Fill in blank type
Question[] quiz = new Question[6];
quiz[0] = new Question("Which class is used to get user input?", "Scanner");
quiz[1] = new Question("How many primitive data types are there in Java? Enter in words.", "eight");
quiz[2] = new FillInTheBlankQuestion("The inventor of Java was _James Gosling_");
quiz[3] = new FillInTheBlankQuestion("Every class in Java inherits from _Object_");
quiz[4] = new MultipleChoiceQuestion("What represents the collection of related data?",
"String", false,"Array", true, "Integer", false,
"Iterator", false);
quiz[5] = new MultipleChoiceQuestion("Which method does not belong to Scanner class?",
"nextInt()", false,
"next()", false,
"nextboolean()", false,
"nextChar()", true);
for(int i = 0; i < quiz.length; i++){
if(quiz[i] instanceof FillInTheBlankQuestion){
((FillInTheBlankQuestion)quiz[i]).extractQA();
}
System.out.println("Q" + (i + 1) + ": " + quiz[i].toString());
quiz[i].inputAnswer(in);
}
}
public static void main(String[] args) {
new QuizTester();
}
}
I thank you so much in advance

Struggling with objects, program does not work as expected(java)

So I have this cyclingmanager game, and I want to show a list of riders by names, and then I want to show their abilities when the user picks a rider. The program compiles and runs nicely, the problem is in my riders() method.It just does not print out c1, my first rider. Thanks in advance.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CyclingManager2 {
public static void main(String[] args) {
//menyvalgene
Menu m = new Menu();
m.choice();
}
}
class Menu {
Scanner in = new Scanner(System.in);
Cyclist cy = new Cyclist();
//choices
public void choice() {
int choice = -1;
while (choice != 0) {
System.out.println("Choose something: ");
System.out.println("-0 will exit the program" + "\n-Pressing 1 will open the database menu");
choice = in.nextInt();
switch(choice) {
case 0: choice = 0; break;
case 1: database(); break;
default: System.out.println("You have to choose either 0 or 1"); break;
}
}
}
public void database() {
System.out.println("Welcome to the database \nThese are the options:\n0 = Back to menu\n1: Riders");
int dbChoice = -1;
while (dbChoice != 0) {
System.out.println();
dbChoice = in.nextInt();
switch(dbChoice) {
case 0: dbChoice = 0; break;
case 1: cy.riders(); System.out.println("Press 0 for going back to the menu\nPress 1 for showing the riders");break;
default: System.out.println("Choose either 0 or 1"); break;
}
}
}
}
class Cyclist {
List<Cyclist> cyclists = new ArrayList<>();
private String name;
private int mountain;
private int timeTrial;
private int sprint;
private int age;
Cyclist c1 = null;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setMountain(int mountain) {
this.mountain = mountain;
}
public int getMountain() {
return mountain;
}
public void setTimeTrial(int timeTrial) {
this.timeTrial = timeTrial;
}
public int getTimeTrial() {
return timeTrial;
}
public void setSprint(int sprint) {
this.sprint = sprint;
}
public int getSprint() {
return sprint;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void riders() {
abilities();
for (int i = 0; i < cyclists.size(); i++){
System.out.print(((Cyclist) cyclists).getName());
}
}
public void abilities() {
//Pardilla is created
c1 = new Cyclist();
c1.setName("Sergio Pardilla");
c1.setMountain(75);
c1.setTimeTrial(60);
c1.setSprint(60);
c1.setAge(30);
/*System.out.println(c1.getName() + "'s abilities:");
System.out.println("Mountain - " + c1.getMountain());
System.out.println("TimeTrial - " + c1.getTimeTrial());
System.out.println("Sprint - " + c1.getSprint());
System.out.println("Age - " +c1.getAge());
cyclists.add(c1); //adds Pardilla to cyclists arraylist*/
}
}
You have this for-loop:
for (int i = 0; i < cyclists.size(); i++) {
System.out.print(((Cyclist) cyclists).getName());
}
It is not going to work. You are casting the entire cyclists (an ArrayList) to one cyclist instance. You probably want to iterate over the contents of the ArrayList and get each Cyclist-object in the cyclists array. Try a foreach-loop:
for (Cyclist cyclist : cyclists) {
System.out.print(cyclist.getName());
}
or use a for loop with index based retrieval:
for (int i = 0; i < cyclists.size(); i++) {
cyclists.get(i).getName());
}
I think you want more something like:
public void riders() {
abilities();
for (int i = 0; i < cyclists.size(); i++){
System.out.print(cyclists.get(i).getName());
}
}
Another thing, is that I'm not sure you want List<Cyclist> cyclists = new ArrayList<>(); to be part of Cyclist class.
Two issues:
The part where you add your rider to the ArrayList is commented out.
The way you loop over your ArrayList is by no means correct. Try like this:
for (Cyclist cyclist : cyclists) {
System.out.println(cyclist.getName());
}
You should get Objects from List by calling it number: cyclists.get(i).getName())

Cannot resolve method 'get(java.lang.String)' in my code

I'm doing little school project where I have to make adressbook where I can add, print contacts and I have to use Hashmap for search. This is my code and I think I have to call method get with public string in my class kontakt but I'm not quiet sure, so your help would be really appreciated.
import java.util.HashMap;
public class adresar {
class kontakt {
String ime;
String broj;
String grad;
kontakt(String ime, String broj, String grad) {
this.ime = ime;
this.broj = broj;
this.grad = grad;
}
}
private HashMap<String, kontakt> osobe =
new HashMap<String, kontakt>();
public boolean ispisi(String ime, String broj, String grad) { //stampam kontakt iz adresara
if (osobe.containsKey(ime)) {
System.out.println("Osoba iz adresara je: " + ime + broj + grad);
return false;
} else {
osobe.put(ime, new kontakt(ime, broj, grad)); //u slucaju da nema osobe za stampanje upisujem je
return true;
}
}
public kontakt search(String ime) { //pretrazujem po glavnom key-u, tj imenu
return kontakt.get(ime);
}
public static void main (String[] args) {
}
}
get is undefined for class kontakt
return kontakt.get(ime);
should be
return osobe.get(ime);
Aside: Take a look at Java Naming Conventions which show that class names start with an uppercase character, e.g. Kontakt

Method in main wont call method of a object instance?

This is a java assignment containing 3 class files. The problem is when I call the "doOperations" method in main. The if statements read the file correctly, but the object methods dont work(e.g. tv.on, tv.volumeUp tv.setChannel(scan.nextInt(), etc.)).
Can anyone see where I am going wrong? Thanks.
TV class file.
import java.io.*;
import java.util.Scanner;
public class TV {
boolean on;
boolean subscribe;
int currentchannel;
int indexChan;
int volume;
File chanList;
Scanner chanScan;
TVChannel[] channels;
final int MaxChannel = 100;
public TV(){
on = false;
currentchannel = 1;
volume = 1;
channels = new TVChannel[MaxChannel]; //Create object of an array, default value = null.
subscribe = false;
}
public void turnOn(){
on = true;
}
public void turnOff(){
on = false;
}
public void channelUp(){
currentchannel++;
}
public void channelDown(){
currentchannel--;
}
public void volumeUp(){
volume++;
}
public void volumeDown(){
volume--;
}
public TVChannel getChannel(){
return channels[currentchannel];
}
public void setChannel(int c){
if(channels[c]!= null)
currentchannel = c;
}
public boolean subscribe(String provider) throws IOException{
chanList = new File(provider);
chanScan = new Scanner(chanList);
if(chanList.exists()){
while(chanScan.hasNext()){
indexChan = chanScan.nextInt();
channels[indexChan] = new TVChannel(indexChan, chanScan.nextLine());
}
chanScan.close();
return true;
}
else return false;
}
public void printAll(){
for(int i = 0; i < MaxChannel; i++){
if(channels[i]!= null)
System.out.println(channels[i].channelNumber+"\t"+channels[i].channelName);
}
}
public void displayChannel(int c){
if(channels[c]!= null)
System.out.println(channels[c].getChannel()+"\t"+channels[c].getName());
}
public void displayCurrentChannel(){
if(channels[currentchannel] != null)
System.out.println(channels[currentchannel].getChannel() +" "+ channels[currentchannel].getName());
}
}
Main function
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class TestTV {
public static void main(String[] args) throws IOException{
TV tv = new TV();
tv.subscribe("chan.txt");
if(tv.subscribe = true){
tv.printAll();
doOperations("operations.txt", tv);
}
}
//Static means only one instance of object.
public static void doOperations(String opFileName, TV tv) throws IOException{
File op = new File(opFileName);
Scanner scan = new Scanner(op);
String opa = scan.next();
while(scan.hasNext()){
System.out.println(scan.next());
if(opa.equals("on")) tv.turnOn();
else if(opa.equals("off")) tv.turnOff();
else if(opa.equals("channelUp")) tv.channelUp();
else if(opa.equals("channelDown")) tv.channelDown();
else if(opa.equals("volumeUp")) tv.volumeUp();
else if(opa.equals("volumeDown")) tv.volumeDown();
else if(opa.equals("showChannel")) tv.displayCurrentChannel();
else if(opa.equals("setChannel"))tv.setChannel(scan.nextInt()); //Error
}
scan.close();
}
}
You forgot to put this
String opa = scan.next(); inside of while loop. You need to store the result of course, on each token.
while(scan.hasNext()){
opa = scan.next();
System.out.println(opa); //don't just call scan.next()
//and discard the result. Unless that's really what you want?
.....
}
Nothing wrong with your code.
make sure your operation.txt looks like this
showChannel
setChannel 2
Note:since you are scan.next(); before the while loop and again in the loop as System.out.println(scan.next());
you are going to ignore the first line of the operation.txt and you would see it set the channel correctly.
Suggestion:
Change it as
String opa= "";// = scan.next();
while(scan.hasNext()){
System.out.println(scan.next());

Adding user input to ArrayList using do-while loop

I am trying to add user input to an Arraylist using a do-while loop however I keep ending up with a list consisting of only the final item inputed repeated several times.
public static ArrayList<Item> purchaseItems()
{
ArrayList<Item> toBuy = new ArrayList<Item>();
String response;
System.out.println("What would you like to purchase? (type \"done\" to end) ");
do {
response = in.nextLine();
if(!response.equals("done") ){
toBuy.add(new Item(response, randGen.nextInt(100)));
System.out.println(toBuy);
}
} while(!response.equals("done"));
return toBuy;
}
should work as mentioned in my comment.
Please implement a toString() method in your Item class if not done already.
you should replace your System.out.println as following:
public static ArrayList<Item> purchaseItems()
{
ArrayList<Item> toBuy = new ArrayList<Item>();
String response;
System.out.println("What would you like to purchase? (type \"done\" to end) ");
do {
response = in.nextLine();
if(!response.equals("done") ){
toBuy.add(new Item(response, randGen.nextInt(100)));
}
} while(!response.equals("done"));
for (Item item : toBuy){
System.out.println(item);
}
return toBuy;
}
if this doesn't helps, please share some more code.
Here is fully working example
package stackoverflow;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class Q53837506 {
public static void main(String[] args) {
ArrayList<Item> purchaseItems = purchaseItems();
System.out.println(purchaseItems);
}
public static class Item {
String r;
int v;
public Item(String r, int v) {
super();
this.r = r;
this.v = v;
}
#Override
public String toString() {
return "Item [r=" + r + ", v=" + v + "]";
}
}
static final Random randGen = new Random();
public static ArrayList<Item> purchaseItems() {
ArrayList<Item> toBuy = new ArrayList<Item>();
String response;
System.out.println("What would you like to purchase? (type \"done\" to end) ");
Scanner in = new Scanner(System.in);
do {
response = in.nextLine();
if (!response.equals("done")) {
toBuy.add(new Item(response, randGen.nextInt(100)));
System.out.println(toBuy);
}
} while (!response.equals("done"));
return toBuy;
}
}

Categories