I am new to programming and I'm starting to create a simple calculator in Java, but I keep getting an error on the line
for (int i = 0; i < user_input.length(); i++)
The error says:
Exception in thread "main" java.lang.NullPointerException
How can I fix this problem?
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.util.Scanner;
public class stringCalculator
{
public static ArrayList<String> input = new ArrayList<String>();
public static ArrayList<String> calcOperators = new ArrayList<String>();
public static ArrayList<Integer> calcOperands = new ArrayList<Integer>();
public static String user_input;
public static String first;
public static int int1;
public static String char1;
public static int int2;
public static String next;
}
public static void input()
{
Scanner user_input = new Scanner(System.in);
int1 = user_input.nextInt();
char1 = user_input.next();
int2 = user_input.nextInt();
next = user_input.nextLine();
}
public void calcOperators()
{
for (int i = 0; i < user_input.length(); i++)
{
if (char1 == "+")
{
calcOperators.add(char1);
}
else if (char1 == "-")
{
calcOperators.add(char1);
}
else if (char1 == "char1")
{
calcOperators.add(char1);
}
else if (char1 == "/")
{
calcOperators.add(char1);
}
}
public void calcOperands()
{
for (int i = 0; i < user_input.length(); i++)
{
if (int1 == 1 || int2 == 1)
{
calcOperands.add(1);
}
else if (int1 == 2 || int2 == 2)
{
calcOperands.add(2);
}
else if (int1 == 3 || int2 == 3)
{
calcOperands.add(3);
}
else if (int1 == 4 || int2 == 4)
{
calcOperands.add(4);
}
else if (int1 == 5 || int2 == 5)
{
calcOperands.add(5);
}
else if (int1 == 6 || int2 == 6)
{
calcOperands.add(6);
}
else if (int1 == 7 || int2 == 7)
{
calcOperands.add(7);
}
else if (int1 == 8 || int2 == 8)
{
calcOperands.add(8);
}
else if (int1 == 9 || int2 == 9)
{
calcOperands.add(9);
}
else if (int1 == 0 || int2 == 0)
{
calcOperands.add(0);
}
}
}
}
public class Main
{
public static void main(String[] args)
{
stringCalculator c = new stringCalculator();
c.input();
c.calcOperators();
c.calcOperands();
}
}
I am kind of confused in here why you have
public static String user_input
and then
Scanner user_input = new Scanner(System.in);
int1 = user_input.nextInt();
char1 = user_input.next();
int2 = user_input.nextInt();
next = user_input.nextLine();
And finally you are using the same var name for strings and ints in loops:
for (int i = 0; i < user_input.length(); i++)
for (int i = 0; i < user_input.length(); i++)
I would highly recommend refactoring this code.
.....
private ArrayList<String> input = new ArrayList<String>();
private ArrayList<String> calcOperators = new ArrayList<String>();
private ArrayList<Integer> calcOperands = new ArrayList<Integer>();
private String user_input;
private String first;
private String next;
private String char1;
private int integer2;
private int integer1;
}
public static void input()
{
Scanner input = new Scanner(System.in);
int int1 = input.nextInt();
int int2 = input.nextInt();
string str = input.next();
string nxt = input.next();
setInteger1(int1);
setInteger2(int2);
setStringFirst(str);
setStringNext(...);
....
// And so on
}
private void setInteger1(int int1) {
this.integer1 = int1;
}
private Integer getInteger1() {
return this.integer1;
}
private void setInteger2(int int2) {
this.integer2 = int2;
}
private Integer getInteger2() {
return this.integer2;
}
private void setStringFirst(String fst) {
this.first = fst;
}
private String getStringFirst() {
return this.first;
}
// And so on. Create all get and set methods for each global variable and for future
// reference do not use variable names that are the same as method, names
// and try to use more meaningful variable names. In fact, if you look at
// Java naming conventions it would do you good.
Could you also tell us perhaps what these loops are meant to do? As I don't really understand what is this? Do you want to iterate over an array of "things" and match each operation to given array element? Or do you just want a single element to match one of the operations?
Side note: Class names should be capitalized:
public class StringCalculator
==================================================================================
OK, I have made a simple program that allows you to add a string into an array and then display it. It is based on what you were doing although you will see it is structured differently. This should give you a head start and allow you to implement this further and finish whatever you are doing.
public class Thing {
private String operator;
private void getUserInput() {
Scanner input = new Scanner(System.in);
if(input.hasNextInt()) {
System.out.println("I have entered an integer: " + input.nextInt());
}
else {
setOperator(input.nextLine());
addOperators();
System.out.println("I have entered a string: " + getOperator());
}
displayThing();
}
private ArrayList<String> addOperators() {
ArrayList<String> operatorsList = new ArrayList<String>();
if(getOperator().equals("+")) {
operatorsList.add(operator);
}
if(getOperator().equals("-")) {
operatorsList.add(operator);
}
else {
operatorsList.add(getOperator());
}
return operatorsList;
}
private void displayThing() {
System.out.println(addOperators());
}
public static void main(String[] args) {
Thing program = new Thing();
program.getUserInput();
}
// Setters and getters
private void setOperator(String operator) {
this.operator = operator;
}
private String getOperator() {
return this.operator;
}
}
You have declared the public static String user_input; which is used in a for loop and not initialised, so thus the exception. Initialise it in your input method, like this.user_input=user_input.nextLine().
You have a static String named user_input defined as:
public static String user_input; // This is null and what the for loop is reading
Set a value to that string when you're using your Scanner... which you shouldn't have also named user_input.
Related
I'm trying to learn java using the basic tictactoe example, but just for fun I wanted to design an ai later.
I'm having an issue flattening the char[] to Array. I'm so confused is there a better way to do this?
Do I need to create another method to specific convert this char[] to array?
ERROR:
The method mapToCharater(Charater.class::cast) is undefined for the type Stream<Object>
CONSOLE OUTPUT
EDIT:
Exception in thread "main" java.lang.ClassCastException: Cannot cast [C to java.lang.Character
at java.base/java.lang.Class.cast(Class.java:3610)
at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
at java.base/java.util.stream.Streams$StreamBuilderImpl.forEachRemaining(Streams.java:411)
at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:658)
at java.base/java.util.stream.ReferencePipeline$7$1.accept(ReferencePipeline.java:274)
at java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:550)
at java.base/java.util.stream.AbstractPipeline.evaluateToArrayNode(AbstractPipeline.java:260)
at java.base/java.util.stream.ReferencePipeline.toArray(ReferencePipeline.java:517)
at java.base/java.util.stream.ReferencePipeline.toArray(ReferencePipeline.java:523)
at aiPackage.game.Board.<init>(Board.java:17)
at aiPackage.game.Tester.main(Tester.java:15)
package aiPackage.game;
import java.util.*;
import java.util.stream.*;
public class Board {
//declaration of private members
private int score;
private Board previousB = null;
private char[][] thisBoard;
// ------------------------------------------------------;
public Board (char [][] inBoard) {
//what
//char[] flats = flatten(inBoard).map
Object[] flats = flatten(inBoard).map(Character.class::cast).toArray(); //mapToCharater(Charater.class::cast).toArray();
int[] flat = flatten(inBoard).mapToInt(Integer.class::cast).toArray();
int flatSize = flat.length;
// ------------------------------------------------------;
//check if square
if (Math.sqrt(flatSize)==3) {
if(inBoard.length == 3) {
thisBoard = inBoard;
}
else {
System.out.println("The array isnt a square.");
}
}
else {
System.out.println("It doesnt match the dimensions of a tictactoe board.");
}
//we'll assume its not gonna break from the input atm
setThisBoard(inBoard);
}
//https://stackoverflow.com/questions/31851548/flatten-nested-arrays-in-java
private static Stream<Object> flatten(Object[] array) {
return Arrays.stream(array)
.flatMap(o -> o instanceof Object[]? flatten((Object[])o): Stream.of(o));
}
public Board getPreviousB() {
return previousB;
}
public void setPreviousB(Board previousB) {
this.previousB = previousB;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public char[][] getThisBoard() {
return thisBoard;
}
public void setThisBoard(char[][] thisBoard) {
this.thisBoard = thisBoard;
}
//if there are even elements on the board, its x's turn
public ArrayList<Board> getChildren(){
return null;
}
public void checkIfEnded() {
for (int i = 0; i < 3; i++) {
//check row wins
if (thisBoard[i][0] != '-' &&
thisBoard[i][0] == thisBoard[i][1] &&
thisBoard[i][1] == thisBoard[i][2]) {
//updates score based on winner
if (thisBoard[0][2] == 'x') {
updateScore(1);
}
else {
updateScore(-1);
}
return;
}
//check column wins
if (thisBoard[i][0] != '-' &&
thisBoard[0][i] == thisBoard[1][i] &&
thisBoard[1][i] == thisBoard[2][i]) {
//updates score based on winner
if (thisBoard[0][2] == 'x') {
updateScore(1);
}
else {
updateScore(-1);
}
return;
}
}
//check diagnals
if (thisBoard[0][0] != '-' &&
thisBoard[0][0] == thisBoard[1][1] &&
thisBoard[1][1] == thisBoard[2][2]) {
//updates score based on winner
if (thisBoard[0][2] == 'x') {
updateScore(1);
}
else {
updateScore(-1);
}
return;
}
if (thisBoard[0][2] != '-' &&
thisBoard[0][2] == thisBoard[1][1] &&
thisBoard[1][1] == thisBoard[2][0]) {
//updates score based on winner
if (thisBoard[0][2] == 'x') {
updateScore(1);
}
else {
updateScore(-1);
}
return;
}
}
//outputs the board's contents as a string
public String toString() {
String result = "";
//gets the previous board's info to output first
result = "" + previousB;
//gets this boards info to output
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
result += thisBoard[i][j] + " ";
}
//adds newline char at end of row
result += "\n";
}
//adds an extra newline char at end of board
result += "\n";
return result;
}
private void updateScore(int win) {
if (win > 0) {
score = 1;
} else if(win == 0){
score = 0;
}else {
score = -1;
}
}
}
package aiPackage.game;
import java.util.*;
public class Tester {
private static Board start;
private static Board finish;
public static void main(String[] args) {
char temp [][] = {
{'o','-','x'},
{'-','-','-'},
{'-','-','-'}};
start = new Board(temp);
finish = minMax(start.getChildren());
System.out.println();
}
public static Board minMax(ArrayList<Board> resultList) {
return null;
}
}
The reason it fails is because Arrays.stream() does not accept char[] The following should work.
Arrays.stream(inBoard)
.flatMap(x -> (Stream<Character>)new String(x).chars().mapToObj(i->(char)i))
.collect(Collectors.toList())
check out
Want to create a stream of characters from char array in java for
and
Why is String.chars() a stream of ints in Java 8?
for better understanding.
Your problem is here:
private static Stream<Object> flatten(Object[] array) {
return Arrays.stream(array)
.flatMap(o -> o instanceof Object[]? flatten((Object[])o): Stream.of(o));
}
You are using the comparation with Object[] to decompose the array, but in reality is a char[].
That makes that your result instead of being an Stream Object is a Stream char[].
The main point is that you can't use a Stream to work with primitives. Stream only works with Objects and char is a primitive.
you can manually flatten the char[][] using a classic loop.
flattening char[][] or impossible doesn't count
char[] array = Stream.of( inBoard ).flatMap( arr -> Stream.of( String.valueOf( arr ) ) )
.collect( Collectors.joining() ).toCharArray(); // [o, -, x, -, -, -, -, -, -]
When running the below method, I do not get anything back. Always getting terminated without any results. Could someone tell me why I am not getting any results back?
I hava adjusted according to the comments but havent worked. I have add the main method below;
public class ModuleGrader {
final int examID = 123;
String excellent =null;
String good=null;
String satisfactory=null;
String compensatableFail=null;
String outrightFail=null;
int grade;
public String gradeModule(int mark) {
String result = null;
if (mark>=70 && mark<=100)
{
result = excellent;
System.out.println(" ");
}
else if (mark>=60 && mark<=69)
{
result = good;
}
else if (mark>=50 && mark<=59)
{
result = satisfactory;
}
else if (mark>=40 && mark<=49)
{
result = compensatableFail;
}
else if (mark>=0 && mark<=39) {
result = outrightFail;
}
else {
System.out.println("Invalid entery, please insert an number between 100-0");
}
return result;
}
So I have add my invoking main method;
the method to call maybe the problem?
public static void main(String[] args) {
ModuleGrader mg=new ModuleGrader();
mg.gradeModule(100);
mg.gradeModule(66);}
You have assigned no values to String excellent;, String good;, so it fails because those values have not been initialized to anything when you call them.
How would you know that it is not working? You have no output of the final result to the console. I added System.out.println() to correct that.
You can't reference something which is not static from something which is static. Change public class ModuleGrader to public static class ModuleGrader.
Final Working Code
public class Main {
public static void main(String[] args) {
ModuleGrader mg=new ModuleGrader();
System.out.println(mg.gradeModule(100));
System.out.println(mg.gradeModule(66));
}
public static class ModuleGrader {
final int examID = 123;
String excellent = null;
String good = null;
String satisfactory = null;
String compensatableFail = null;
String outrightFail = null;
int grade;
public String gradeModule(int mark) {
String result = null;
if (mark >= 70 && mark <= 100) {
result = excellent;
System.out.println(" ");
} else if (mark >= 60 && mark <= 69) {
result = good;
} else if (mark >= 50 && mark <= 59) {
result = satisfactory;
} else if (mark >= 40 && mark <= 49) {
result = compensatableFail;
} else if (mark >= 0 && mark <= 39) {
result = outrightFail;
} else {
System.out.println("Invalid entery, please insert an number between 100-0");
}
return result;
}
}
}
You need to put quotes around the strings you want to assign.
result = excellent; should be result = "excellent"; and soforth for all your assignments to return
public class ModuleGrader {
final int examID = 123;
//String excellent=null;
//String good=null;
//String satisfactory=null;
//String compensatableFail=null;
//String outrightFail=null;
int grade;
public String gradeModule(int mark) {
String result = null;
if (mark>=70 && mark<=100)
{
result = "excellent";
System.out.println(" ");
}
else if (mark>=60 && mark<=69)
{
result = "good";
}
else if (mark>=50 && mark<=59)
{
result = "satisfactory";
}
else if (mark>=40 && mark<=49)
{
result = "compensatableFail";
}
else if (mark>=0 && mark<=39) {
result = "outrightFail";
}
else {
System.out.println("Invalid entery, please insert an number between 100-0");
}
return result;
}
This code is for learning generic class and stack operation.
but it has some error about declare variable type
package lab11_2_590510535;
import java.util.Scanner;
class Queue <TYPE>{
private int count;
private int front;
private int rear;
private int n;
private Object [] item;
private TYPE queueFront;
static void pl(Object a){System.out.println(a);}
static void p(Object a){System.out.print(a);}
Queue(int x){
n = x;
item = new Object[n];
front = 0;
rear = -1;
count = 0;
}
public boolean isEmpty(){
for(int i = 0 ; i<item.length ; i++){
if(item[i] != null){return false;}
}
return true;
}
public boolean isFull(){
if(item[item.length] != null){return true;}
else{return false;}
}
public void enqueue(TYPE v){
if(!isFull()){
if(rear < n-1){
rear++;
item[rear] = v;
count++;
}
}else{pl("Queue is Full.");}
}
public TYPE dequeue(){
if(!isEmpty()){
queueFront = item[front];
front++;
count++;
}else{p("Queue is empty.");}
return queueFront;
}
public void show(){
for(int i = 0 ; i <item.length ; i++){
if(item[i] != null){p(item[i] + ", ");}
}
}
public class Lab11_2_590510535 {
static void pl(Object a){System.out.println(a);}
static void p(Object a){System.out.print(a);}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner keyboard = new Scanner(System.in);
char choice;
int N;
p("Enter N: ");
N = keyboard.nextInt();
p("Choice input type; int(1) , char(2): ");
choice = keyboard.next().charAt(0);
if(choice == '1'){Queue <Integer> q = new Queue(N);}
else if(choice == '2'){Queue <Character> q = new Queue(N);}
do{
pl("1) enqueue"); pl("2) dequeue"); pl("3) show"); pl("4) exit");
p("Enter function number : ");
choice = keyboard.next().charAt(0);
if(choice == '1'){
p("Enter data: ");
Object s = keyboard.next();
q.enqueue(s);
}
else if(choice == '2'){Object s = q.dequeue();
pl(s);
}
else if(choice == '3'){q.show();}
}while(choice != '4');
}
}
1.After user input choice and I create generic object with type casting in do...while loop it can't find "q".
2.In public TYPE dequeue() method line "queueFront = item[front];" Object can't be convert to TYPE ,how can I fix it.
Try to change private Object [] item to private TYPE [] item. Also you will need to know how to create a generic array for your example:
How to create a generic array?
How to create a generic array in Java?
You will need to change item = new Object[n]; to item = (TYPE[]) new Object[n];
However you should avoid creating generic types and instead you should inject them or use a factory to create them.
this is the code for a pig-latin translator in JAVA, it works with one word but never with a sentence. It seems that the code at line 30 is messing everything up, and I'm not sure how it is doing that or how I can fix it. IndexOutOfBoundError on line 8 and line 30. I'm not sure how to fix this, help.
public class Practice
{
public static void main(String[] args)
{
String a = "hello Stranger";
System.out.println(translate(a)); //8
}
private static String translate(String a)
{
String XD = a;
boolean repeat = true;
int first = 1;
int second = 0;
do
{
second = XD.indexOf(" ");
if (second == -1)
{
repeat = false;
XD = vowelFinder(a);
break;
}
else
{
XD = XD + vowelFinder(a.substring(first, second)); //30
}
first = second +1;
}while(repeat == true);
return XD;
}
private static boolean isVowel (char c)
{
if (c == 'a'|| c== 'e'|| c== 'i' || c == 'o' || c== 'u')
{
return true;
}
return false;
}
private static String vowelFinder(String s)
{
String nope = s;
for(int i = 0; i <= s.length(); i++)
{
if(isVowel(s.charAt(i)) == true)
{
nope = nope.substring(i) + "-"+nope.substring(0, i);`
return nope;
}
}
return nope;
}
}
Try this;
import java.util.Scanner;
public class PigLatin {
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
String yourSentence="";
do {
String[] words;
System.out.print("Enter your words here: ");
yourSentence = input.nextLine();
words = yourSentence.split(" ");
for (String word : words) {
if (word.startsWith("a") || word.startsWith("e") || word.startsWith("i") || word.startsWith("o") || word.startsWith("u"))
System.out.print(word + "way ");
else if (word.startsWith("sh") || word.startsWith("ch") || word.startsWith("th"))
System.out.print(word.substring(2)+word.substring(0,2)+"ay ");
else
System.out.print(word.substring(1)+word.substring(0,1)+"ay ");
}
System.out.println();
} while(!yourSentence.equals("quit"));
}
}
I have a quick question. How would I find the most common character in a string in Java. I know logically how to do it, but I am not sure if my syntax in correct:
public class HelloWorld {
public static void main(String[] args){
String votes = "ABBAB";
char[] StoringArray = votes.toCharArray();
int numOFB = 0;
int numOFA = 0;
if (StoringArray.contains("A")) {
numOFA++;
} else if (StoringArray.contains("B")) {
numOFAB++;
}
if (numOFA = numOFB) {
System.out.println("Tie");
} else if (numOFA > B) {
System.out.println("A");
} else {
System.out.println("B");
}
}
}
Could anyone help me with how to correctly do this in Java?
You can not compare char Array with string, below logic should work and give you what you need:
public static void main(String[] args){
String votes = "ABBAB";
char[] storingArray = votes.toCharArray();
int numOFB = 0;
int numOFA = 0;
for(char c : storingArray) {
if(c == 'A') {
numOFA++;
}
if(c == 'B') {
numOFB++;
}
}
if (numOFA == numOFB) {
System.out.println("Tie");
} else if (numOFA > numOFB) {
System.out.println("A");
} else {
System.out.println("B");
}
}
There are couple of mistakes in your code:
You can not use if (numOFA = numOFB) it is not valid expression. You should use == to compare
You can not compare char Array with contains method. It should be used on String object
As the comments said; it looks like you're counting the number of A's or B's, not the longest substring. Are you only analyzing a String composed of A's and B's?
Also, you're using = to check for equality when you should be using ==. I would recommend using an IDE like Eclipse which would show you when you're doing this.
Edit: also, you're not looping through the array. You're just checking if the String contains an A or a B and adding 1 if it does. You need to loop through the entire array.
Actually, I was working with it, and I found this is the nicest way to do it:
String votes = "ABBAB";
char[] StoringArray = votes.toCharArray();
int B = 0;
int A = 0;
for (int i = 0; i < StoringArray.length; i ++) {
if (StoringArray[i] == 'A') {
A++;
} else if (StoringArray[i] == 'B') {
B++;
}
}
if (A == B) {
System.out.println("Tie");
} else if (A > B) {
System.out.println("A");
} else {
System.out.println("B");
}
I would give you a more abstract solution:
public class Counter{
private char c;
private int count;
Counter(char c, int count){
this.c=c;
this.count=count;
}
public char getC() {
return c;
}
public void setC(char c) {
this.c = c;
}
public int getCount() {
return count;
}
public void addOcurrence() {
this.count++;
}
#Override
public boolean equals(Object obj) {
if(obj!=null)
if(((Counter)obj).getC()== this.c)
return true;
return false;
}
}
public static void main(String[] args){
String votes = "whateveryouwanttoputhereorcanbefromaparameter";
char[] storingArray = votes.toCharArray();
List<Counter> listCounter = new ArrayList<Counter>();
for(char aChar : storingArray){
Counter compareCounter = new Counter(aChar,1);
if(listCounter.contains(compareCounter)){
listCounter.get(listCounter.indexOf(compareCounter)).addOcurrence();
}else{
listCounter.add(compareCounter);
}
}
Counter max = listCounter.get(0);
for( Counter c : listCounter){
if(c.getCount() > max.getCount()){
max = c;
}
}
System.out.println("the character with more ocurrence is: "+max.getC());
}