I keep getting null pointer exception when I try to put into messages
( I have removed all unnecessary code)
I dont get the error when I initialize messages inside add function
How can I resolve this?
class Chat {
HashMap< Integer, String> messages;
void Chat() {
this.messages = new HashMap<>();
}
public void add(int id, String newMessage) {
if (!newMessage.isEmpty()) {
System.out.println(newMessage + " "
+ Integer.parseInt(String.valueOf(id)));
this.messages.put(Integer.parseInt(String.valueOf(id)),
newMessage);
System.out.println(messages.values() + "Added to hashset");
}
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Chat obj = new Chat();
int size = Integer.parseInt(sc.nextLine());
for (int i = 0; i < size; i++) {
String str = sc.nextLine();
if (!str.isEmpty()) {
obj.add(i + 1, str);
}
}
}
}
Related
I'm working with Stacks in Java at the moment.
The problem I'm facing is that I want to create a Stack which stores items of the type "candy".
I want to add that "candy" at the Producer.java
But when I run the code shown below I get the error:
Exception in thread "main" java.util.EmptyStackException
at java.util.Stack.peek(Stack.java:102)
at java.util.Stack.pop(Stack.java:84)
at app.fachinformatiker.myMashup.Model.Consumer.(Consumer.java:10)
at app.fachinformatiker.myMashup.Main.Main.initializeConsumers(Main.java:84)
at app.fachinformatiker.myMashup.Main.Main.main(Main.java:42)
These are the corresponding lines
Consumer.java:10
String Candy = candyStack.pop();
Main.java:84
consumerList.add(new Consumer(candyStack));
Main.java:42
initializeConsumers();
I don't get it why my stack isn't properly filled.
Below you will find some snippets of my code.
If you want to download my whole code and run it in an IDE of your choice (I use IntelliJ IDEA), here's a direct link to the archive on GitHub (specific commit) : https://github.com/fachinformatiker/myMashup/archive/97e3ffb.zip
Here's some snippets of my code:
In my Main.java
private static final Stack<String> candyStack = new Stack<>();
private static final ArrayList<Producer> producerList = new ArrayList<>();
private static final ArrayList<Consumer> consumerList = new ArrayList<>();
...
private static void startProducers() {
for (int i = 0; i < producerList.size(); i++) {
System.out.println("I would start producer Nr. " + i + " now.");
producerList.get(i).start();
}
}
private static void startConsumer() {
for (int i = 0; i < consumerList.size(); i++) {
Debug.gebeInfoAus("I would start consumer Nr. " + i + " now.");
consumerList.get(i).start();
}
}
private static void initializeProducers() {
if (ArgController.istAusgewertet) {
Debug.gebeInfoAus("Producer istAusgewertet");
return;
}
for (int i = 0; i < ArgController.getAnzahlProduzenten(); i++) {
Debug.gebeInfoAus("Producer Nr. " + i + " added to candyStack");
producerList.add(new Producer(candyStack, i));
}
}
in my Producer.java
public class Producer {
private Candy candy = new Candy();
private String myCandy;
int hell = candy.getHell();
String hope = candy.getHope();
public Producer(Stack<String> candyStack, int i) {
myCandy = i + ";" + hell + ";" + hope;
candyStack.push(myCandy);
Debug.gebeInfoAus(myCandy);
}
public void start() {
}
}
In my Consumer.java
public class Consumer {
public Consumer(Stack<String> candyStack) {
String Candy = candyStack.pop();
Debug.gebeInfoAus(Candy);
}
public void start() {
}
}
So my Kiir method doesn't work since my last run. The program should write the new values to a .txt file, and give it back the whole text with the new value included.
The program says the issue is in the
public static void Kiir(ArrayList<Versenyzo>versenyzok){
for (Versenyzo f : versenyzok){
System.out.println(f.toString());
}
but I can't see the problem. Any idea?
public class VizsgaMintaA {
static SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd");
static Scanner sc= new Scanner(System.in);
/**
* #param args the command line arguments
* #throws java.text.ParseException
* #throws java.io.FileNotFoundException
*/
public static void main(String[] args) throws ParseException, FileNotFoundException {
ArrayList<Versenyzo> versenyzok = new ArrayList<>();
Feltolt(versenyzok);
Kiir(versenyzok);
Ujversenyzo(versenyzok);
Kiir(versenyzok);
Fajlbair(versenyzok);
}
private static void Feltolt(ArrayList<Versenyzo> versenyzok) throws ParseException{
Versenyzo v = null;
File f = new File("versenyzok.txt");
try {
Scanner scan = new Scanner(f, "iso-8859-2");
while (scan.hasNextLine()) {
String sor = scan.nextLine();
String[] adatok = sor.split(";");
if (adatok.length == 3) {
v = new Versenyzo();
v.nev = adatok[0];
v.szuletes = df.parse(adatok[1]);
v.csapat = adatok[2];
} else if (adatok.length > 3) {
v = new Versenyzo (adatok[0],df.parse(adatok[1]),adatok[2]
,Integer.parseInt(adatok[3])
);
}
versenyzok.add(v);
}
} catch (FileNotFoundException ex) {
System.out.println("Nincs meg a fájl.");
}
}
public static void Kiir(ArrayList<Versenyzo>versenyzok){
for (Versenyzo f : versenyzok){
System.out.println(f.toString());
}
}
private static void Ujversenyzo(ArrayList<Versenyzo>versenyzok)throws ParseException{
Versenyzo v = new Versenyzo();
System.out.println("Adjon meg egy nevet:");
v.nev=sc.nextLine();
System.out.println("Adja meg a születési idejét:");
v.szuletes=df.parse(sc.nextLine());
System.out.println("Adja meg a csapatot:");
v.csapat = sc.nextLine();
System.out.println("Adja meg a vb címek számát:");
v.vbcim = sc.nextInt();
versenyzok.add(v);
}
public static void Fajlbair(ArrayList<Versenyzo>versenyzok) throws FileNotFoundException {
PrintStream f2 = new PrintStream(new File ("versenyzok2.txt"));
for (Versenyzo v : versenyzok){
f2.println(v.toString());
}
}
}
class Versenyzo {
String nev,csapat;
Date szuletes;
int vbcim;
SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd");
#Override
public String toString(){
return "Versenyzo:" +nev + " Született:" + df.format(szuletes)+" Csapata:"+ csapat + " Vb címek:" + vbcim;
}
public Versenyzo(String nev, Date szuletes, String csapat, int vbcim) {
this.nev = nev;
this.szuletes = szuletes;
this.csapat = csapat;
this.vbcim = vbcim;
}
public Versenyzo(){
}
}
First check if the list passed to Kiir() is null:
public static void Kiir(ArrayList<Versenyzo> versenyzok){
if (versenyzok == null)
return;
for (Versenyzo f : versenyzok){
System.out.println(f);
}
}
I did make another change to Kiir().
I removed toString() from f.toString(), since you have overridden it, it is redundant.
Now the only problem with your implementation of the toString() method inside the Versenyzo class is if there exist null values in the szuletes property.
If this is the case then change to this:
#Override
public String toString(){
return "Versenyzo:" + nev + " Született:" + (szuletes == null ? "null" : df.format(szuletes)) + " Csapata:" + csapat + " Vb címek:" + vbcim;
}
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");
}
Im trying to fix my code which is a simple calculator in Java made using stacks and a token class. I am having an error every time I have a decimal number as an answer. For example, if I input 11/2 it will give me 1. Its an odd error and I don't know how to fix it and was wondering if someone could tell me how. Thank you for any help!
public class SimpleCalcSkeleton {
private enum TokenType {WS,LP,RP,NUM,OP};
private static class Token {
// instance variables
private String value;
private TokenType type;
// constructor
public Token(String v, TokenType t) {
this.value = v;
this.type = t;
}
// toString() is important for diagnostic output
public String toString() {
return ("[" + value + ";" + type.toString() + "]");
}
// getter or accessor methods for the instance vars or properties
// setter methods are not needed
public String getValue() {
return value;
}
public TokenType getType() {
return type;
}
}
private static TokenType getTokenType(char c) {
TokenType type=null;
if(c==' '){
type=TokenType.WS;
}
if(c=='('){
type=TokenType.LP;
}
if(c==')'){
type=TokenType.RP;
}
if((c=='+')||(c=='-')||(c=='*')||(c=='/')){
type=TokenType.OP;
}
if((c=='0')||(c=='1')||(c=='2')||(c=='3')||(c=='4')||(c=='5')||(c=='6')||(c=='7')||(c=='8')||(c=='9')){
type=TokenType.NUM;
}
return type;
}
private static int getAssoc(Token token) {
String word = token.getValue();
int number =0;
if((word.equals('+'))||(word.equals('-'))){
number=1;
}
if((word.equals('*'))||(word.equals('/'))){
number=2;
}
return number;
}
private static ArrayList<Token> parse(String s) {
if(s==null||s.length()==0){
return null;
}
ArrayList<Token> list= new ArrayList<Token>();
for(int i=0;i<s.length();i++){
char c=s.charAt(i);
TokenType type = getTokenType(c);
String symbol= Character.toString(c);
if(type==null){
System.out.print("Error: null");
}
else if(!type.equals(TokenType.WS)){
list.add(new Token(symbol,type));
}
}
return list;
}
private static ArrayList<Token> infixToPostfix(ArrayList<Token> intokens) {
Stack astack = new Stack();
ArrayList<Token>outokens=new ArrayList<Token>();
for(int i=0;i<intokens.size();i++){
Token in= intokens.get(i);
if(in.getType()==TokenType.NUM){
outokens.add(in);
}
if(in.getType()==TokenType.LP){
astack.push(in);
}
if(in.getType()==TokenType.RP){
Token top=(Token)astack.peek();
while(top.getType()!=TokenType.LP){
astack.pop();
outokens.add(top);
top=(Token)astack.peek();
if(top.getType()==TokenType.LP){
astack.pop();
break;
}}}
if(in.getType()==TokenType.OP){
if(!astack.isEmpty()){
Token top = (Token)astack.peek();
while((top.getType()==TokenType.OP)&&(getAssoc(top)>=getAssoc(in))){
astack.pop();
outokens.add(top);
if(!astack.isEmpty())
top=(Token)astack.peek();
else break;
}}
astack.push(in);
}
}
while(!astack.isEmpty()){
Token top=(Token)astack.peek();
astack.pop();
outokens.add(top);
if(!astack.isEmpty())
top=(Token)astack.peek();
else break;
}
return outokens;
}
private static Token evalOp(Token op, Token t1, Token t2) {
String one = t1.getValue();
String two = t2.getValue();
String opener = op.getValue();
int output =0;
int first = Integer.parseInt(one);
int second = Integer.parseInt(two);
if(opener.equals("+")){
output = second+first;
}
if(opener.equals("-")){
output = second-first;
}
if(opener.equals("*")){
output = second*first;
}
if(opener.equals("/")){
output = second/first;
}
String last = Integer.toString(output);
Token total = new Token(last,TokenType.NUM);
return total;
}
private static String evalPostfix(ArrayList<Token> intokens) {
Stack right = new Stack();
for(int i=0;i<intokens.size();i++){
Token in=intokens.get(i);
if(in.getType()==TokenType.NUM)
right.push(in);
else if(in.getType()==TokenType.OP){
Token at = (Token) right.pop();
Token bat = (Token) right.pop();
Token cat = evalOp(in,at,bat);
right.push(cat);
}
}
return right.toString();
}
public static String evalExpression(String s) {
ArrayList<Token> infixtokens = parse(s);
System.out.println("\tinfix tokens: " + infixtokens);
ArrayList<Token> postfixtokens = infixToPostfix(infixtokens);
System.out.println("\tpostfix tokens: " + postfixtokens);
return evalPostfix(postfixtokens);
}
public static void commandLine() {
Scanner in = new Scanner(System.in);
while (true){
System.out.print("> ");
String word = in.nextLine();
if (word.equals("quit")) {
break;
}
else {
System.out.println(evalExpression(word));
}
}
}
}
class SimpleCalcTest {
public static void test() {
String[] inputs = {
"3*4 + 5",
"3 + 4*5",
"(1+1)*(5-2)",
"(3*4+5)*(3*3 + 4*4)"
};
for (int i=0; i<inputs.length; i++) {
String s = inputs[i];
System.out.println();
System.out.println();
System.out.println("test: input = " + s);
String r = SimpleCalcSkeleton.evalExpression(s);
System.out.println("\tresult = " + r);
}
}
public static void main(String[] args) {
SimpleCalcSkeleton.commandLine();
SimpleCalcTest.test();
}
}
package macroreader;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class MacroReader {
public static Macro[] macroArray = new Macro[20];
public static int macroID;
public static BufferedReader br;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new FileReader("Macros.txt"));
String currentLine;
while((currentLine = br.readLine()) != null) {
if(currentLine.equalsIgnoreCase("#newmacro")) {
br.mark(1000);
createMacro();
br.reset();
}
}
if (br != null) {
br.close();
}
}
public static void createMacro() throws IOException {
String currentLine;
macroID = getEmptyMacro();
while((currentLine = br.readLine()) != null && !currentLine.equalsIgnoreCase("#newmacro")) {
macroArray[macroID].readMacro(currentLine);
}
macroArray[macroID].inUse = true;
macroArray[macroID].printData();
}
public static int getEmptyMacro() {
for(int i = 0; i < macroArray.length; i++) {
if(!macroArray[i].inUse) {
return i;
}
}
return 0;
}
}
rather than assigning the values read from the file reader to the specified object in the array, in this case 'macroID', it assigns the values to all objects in the array
just edited in the whole file now but the issue is around the createMacro() void
here is my Macro class
package macroreader;
public class Macro {
public static String key;
public static String[] commands = new String[20];
public static boolean inUse;
public static void readMacro(String input) {
if (!input.equals("")) {
if (input.startsWith("key = ")) {
key = input.substring(6);
System.out.println("Key Value for Macro set to " + key);
} else {
for (int i = 0; i < commands.length; i++) {
if (commands[i] == null) {
commands[i] = input;
System.out.println("Command [" + input + "] assigned");
break;
}
}
}
}
}
public static void printData() {
System.out.println("Macro Key: " + key);
for(int i = 0; i < commands.length; i++) {
if(commands[i] != null) {
System.out.println(commands[i]);
}
}
}
}
As I suspected - your inUse is static, so it will always be the same for all instances of the class. As are your other class members.
The classic cause of "changing everything in an array" is if you have actually assigned the same object to every element in the array. We can't tell whether you're doing that because you didn't show us the initialization of macroArray, but it might be like:
Macro m = new Macro();
for (int i = 0; i < macroArray.length; i++) {
macroArray[i] = m;
}
This will cause the results you describe. To fix it, create a separate object for every element of the array:
for (int i = 0; i < macroArray.length; i++) {
macroArray[i] = new Macro();
}