import java.util.Scanner;
public class SolverTester
{
public static void main(String[] args)
{
String symbolSubtract;
String symbolMultiply;
String symbolAddition;
String symbolDivide;
Scanner sc = new Scanner(System.in);
System.out.println("Enter your equation: ");
int numberFirst = sc.nextInt();
if(sc.findInLine("-").equals("-"))
{
symbolSubtract = sc.findInLine("-");
} else if(sc.findInLine("*").equals("*"))
{
symbolMultiply = sc.findInLine("*");
} else if(sc.findInLine("+").equals("+"))
{
symbolAddition = sc.findInLine("+");
} else if(sc.findInLine("/").equals("/"))
{
symbolDivide = sc.findInLine("/");
}
int numberSecond = sc.nextInt();
Solver s = new Solver(numberFirst, numberSecond);
if(symbolSubtract.equals("-"))
{
s.subtraction();
System.out.println(s.getAnswer());
} else if(symbolMultiply.equals("*"))
{
s.multiplication();
System.out.println(s.getAnswer());
} else if(symbolDivide.equals("/"))
{
s.division();
System.out.println(s.getAnswer());
} else if(symbolAddition.equals("+"))
{
s.addition();
System.out.println(s.getAnswer());
}
}
}
My error is "variable "symbolSubtract" has not been initialized". The main class is not relevant because the error is involving local variables.
NOTE: This is not a homework assignment... I am just doing it for fun.
if(sc.findInLine("-").equals("-"))
{
symbolSubtract = sc.findInLine("-");
^^^^^^^^^^^^^^---conditional initialization
Only if that if() succeeds will the variable get a value.
But on this line
if(symbolSubtract.equals("-"))
you ALWAYS access the variable, meaning that only SOME of the time will it have a value.
If sc.findInLine("-") does not equal "-", symbolSubtract never gets initialized, so you can't use it. The easiest way around this, IMHO, is just to initialize it with a default value:
String symbolSubtract = "";
IF you change this:
String symbolSubtract;
String symbolMultiply;
String symbolAddition;
String symbolDivide;
to this
String symbolSubtract = "";
String symbolMultiply = "";
String symbolAddition = "";
String symbolDivide = "";
It should work.
You need to initialized your variables like this
String symbolSubtract="-";
String symbolMultiply="*";
String symbolAddition="+";
String symbolDivide="/";
or
String symbolSubtract=null;
String symbolMultiply=null;
String symbolAddition=null;
String symbolDivide=null;
The second way often result in NPE if you do any operation on it.
Other problem is findInLine(String) read the javadoc
Related
I've just started with Java, and so far been only playing around solving problems online, where you're not supposed to write the whole functional of a program, but only adjust a few lines of code to the already organized code.
However, I'm still struggling to organize my code in a compiling program in IntelliJ Idea, getting confused at,e.g. how methods invocations must be properly written.
Here's what I'm getting stuck with: an example from codingbat.com:
- Given a string, return a new string made of every other char starting with the first, so "Hello" yields "Hlo".
I've come up with a solution online, but now I wanna run it in Idea, with main method, with Scanner/BufferedReader input from console etc. Looks like I'm missing something...
import java.util.Scanner;
public class Bat
{
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
printString();
}
public String stringBits(String str) {
String result = "";
for (int i = 0; i<str.length();i += 2) {
result += str.substring(i, i+1);
}
return result;
}
public static void printString () {
System.out.println(result);
}
}
I ask your help to solve it out. What to do to make it:
Read a word from a console;
create a new string;
print it out.
Two alternatives:
make stringBits static
create an instance of the class Bat and invoke the member method
First solution - easy, not much to change
import java.util.Scanner;
public class Bat {
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
printString(stringBits(str));
}
public static String stringBits(String str) {
String result = "";
for (int i = 0; i < str.length();i += 2) {
result += str.substring(i, i + 1);
}
return result;
}
public static void printString (String string) {
System.out.println(string);
}
}
Second solution - a bit more advances
import java.util.Scanner;
public class Bat {
private String string;
public Bat(String string) {
this.string = string;
}
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
Bat bat = new Bat(str);
bat.printStringBits();
}
private String stringBits() {
String result = "";
for (int i = 0; i < string.length(); i += 2) {
result += string.substring(i, i + 1);
}
return result;
}
public void printStringBits() {
System.out.println(stringBits());
}
}
Your result variable is only accessible from within the "stringBits" method. Since the method returns a string you can do the following to print it:
System.out.println(stringBits(string)); //Call in main method in place of printString();
Edited: My code wasn't a working example. Note that stringBits has to be a static method in order to work.
I have an abstract class that contains a variable of type String declared moneyString
String moneyString;
It contains data something like $123,456,789
So inside the abstract class I have function
void convertToInt(){
remove(',');
remove('$');
empMoney = Integer.parseInt(moneyString.substring(0, moneyString.length()) );
}
And my remove function
void remove(char character){
boolean moreFound = true;
String tempString;
int index;
do{
index = moneyString.indexOf(character);
tempString = moneyString;
if(index!=-1){
//From beggining to the character
moneyString = moneyString.substring(0,index);
//After the character to the end
tempString = tempString.substring(index,tempString.length());
moneyString += tempString;
}
else{
moreFound = false;
}
} while(moreFound);
} //END remove()
Isn't it supposed to get out of the loop when when moreFound = false?
The issue with your code is here,
tempString = tempString.substring(index,tempString.length());
Should be index + 1 because you don't want to include that character.
tempString = tempString.substring(index + 1,tempString.length());
But, I suggest you use a DecimalFormat and parse(String) the value. Like,
public static int convertToInt(String money) throws ParseException {
NumberFormat df = new DecimalFormat("$#,###");
return df.parse(money).intValue();
}
Then you can call it like
public static void main(String[] args) {
try {
System.out.println(convertToInt("$123,456,789"));
} catch (ParseException e) {
e.printStackTrace();
}
}
Output is
123456789
Indeed you have to change the line:
tempString = tempString.substring(index,tempString.length());
to:
tempString = tempString.substring(index+1,tempString.length());
The assignment could be done to a variable of type Long:
moneyString="$123,456,789,101";
long empMoney;
remove('$');
remove(',');
empMoney = Long.parseLong(moneyString.substring(0, moneyString.length()) );
I'm having trouble understanding how to parse text documents with unknown amounts of 'students'. All my solutions are coming up strange and I'm having trouble with the Scanner. Breaking down the input, the first integer represents how many classes there are, the first string is the class name, the following are students with respective dates and variables that need to be stored along with the student, with an unknown amount of students. I want to store each student along with the class they are in.
My code is extremely messy and confusing so far:
String filename = "input.txt";
File file = new File(filename);
Scanner sc = new Scanner(file);
Student[] studArr = new Student[100];
int studCounter = 0;
boolean breaker = false;
boolean firstRun = true;
int numClasses = sc.nextInt();
System.out.println(numClasses);
while(sc.hasNextLine()){
String className = sc.nextLine();
System.out.println("Name: " + className);
String test = null;
breaker = false;
sc.nextLine();
// Breaks the while loop when a new class is found
while (breaker == false){
Student temp = null;
// Boolean to tell when the first run of the loop
if (firstRun == true){
temp.name = sc.nextLine();
}
else
temp.name = test;
System.out.println(temp.name);
temp.date = sc.nextLine();
if (temp.date.isEmpty()){
System.out.println("shit is empty yo");
}
temp.timeSpent = sc.nextInt();
temp.videosWatched = sc.nextInt();
temp.className = className;
studArr[studCounter] = temp;
studCounter++;
sc.nextLine();
test = sc.nextLine();
firstRun = false;
}
}
}
}
class Student {
public String name;
public String date;
public String className;
public int timeSpent;
public int videosWatched;
}
I don't need an exact answer, but should I be looking into a different tool then Scanner? Is there a method I can research?
Thanks for any assistance.
I came up with the following solution. Scanner is a fine tool for the job. The tricky part is that you have to sort of look ahead to see if you have a blank line or a date to know if you have a student or a class.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Parser {
private static String nextLine(Scanner sc) {
String line;
while (sc.hasNext()) {
if (!(line = sc.nextLine()).isEmpty()) {
return line;
}
}
return null;
}
public static ArrayList<Student>[] parseFile(String fileName) {
File file = new File(fileName);
try (Scanner sc = new Scanner(file)) {
int numClasses = sc.nextInt();
String className = nextLine(sc);
ArrayList<Student>[] classList = new ArrayList[numClasses];
for (int i = 0; i < numClasses; i++) {
classList[i] = new ArrayList<>();
while (true) {
String studentOrClassName = nextLine(sc);
if (studentOrClassName == null) {
break;
}
String dateOrBlankLine = sc.nextLine();
if (dateOrBlankLine.isEmpty()) {
className = studentOrClassName;
break;
}
int timeSpent = sc.nextInt();
int videosWatched = sc.nextInt();
classList[i].add(new Student(className, dateOrBlankLine, studentOrClassName, timeSpent,
videosWatched));
}
}
return classList;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return new ArrayList[0];
}
public static void main(String[] args) {
for (ArrayList<Student> students : parseFile("classList.txt")) {
if (!students.isEmpty()) {
System.out.println(students.get(0).className);
}
for (Student student : students) {
System.out.println(student);
}
}
}
static class Student {
public String className;
public String date;
public String name;
public int timeSpent;
public int videosWatched;
public Student(String className, String date, String name, int timeSpent,
int videosWatched) {
this.className = className;
this.date = date;
this.name = name;
this.timeSpent = timeSpent;
this.videosWatched = videosWatched;
}
public String toString() {
return name + '\n' + date + '\n' + timeSpent + '\n' + videosWatched + '\n';
}
}
}
Ask yourself, what does a Student contain? A name, date, number and number. So you want to do the following (not actual code) (format written in Lua code, very understandable. This means this will not run in Lua :P)
if line is not empty then
if followingLine is date then
parseStudent() // also skips the lines etc
else
parseClass() // also skips lines
end
end
I'm trying to send a variable out of a 'for' loop, and save it to a string in another class, but I just end up with the latest input when doing a system print in the last class. Now I suspect this is because of;
ProcessInput c = new ProcessInput();
But I cannot for the life of me understand how I work around that particular problem.
I realize this could be avoided if I appended latest input to a string, and sendt the string after the loop finished. Alas my assignment is not so. Also I'm quite new at this, so be gentle.
public class Query {
private void question() {
ProcessInput c = new ProcessInput();
String feedback = "";
for(int i = 0; i < 10; i ++) {
System.out.print("Input information " + (i + 1) + "/10: ");
Scanner userInput = new Scanner(System.in);
feedback = userInput.next();
c.paste(feedback);
}
}
}
public class ProcessInput {
public void paste(String feedback) {
String line = "";
line += feedback + " ";
System.out.println(line);
}
}
The line is in the local scope of the method and therefore, it is reset every time the method is called. You need to make it an instance variable, so that for every instance created, it preserves the value for that instance.
public class ProcessInput {
String line = ""; // outside the paste method, in the class
public void paste(String feedback) {
line += feedback;
System.out.println(line);
}
}
The concept that you must understand is java is pass by value and not reference, So you are only passing the new input entered every time to the method "paste".
Simple solution
public class Query {
private void question() {
ProcessInput c = new ProcessInput();
String feedback = "";
for(int i = 0; i < 10; i ++) {
System.out.print("Input information " + (i + 1) + "/10: ");
Scanner userInput = new Scanner(System.in);
feedback = feedback+userInput.next();
c.paste(feedback);
}
}
public class ProcessInput {
public void paste(String feedback) {
System.out.println(feedback);
}
}
It is more important you understand the underlying concept of passing values between methods in java.
I've been coding a while for an assignment but can't figure out how
to receive a string input from the user to have the sentences filtered by unicode.
When I try to run the code, the input prompt won't happen. What am I doing wrong?
Any advice is appreciated.
package deel1;
import java.util.*;
public class Deel1 {
public static void main(String[] args) {
}
static String getInput() {
Scanner scan = new Scanner(System.in);
String zin = "";
System.out.println("Voer een zin in: ");
if (scan.hasNextLine()) {
zin = scan.nextLine().trim();
}
if (zin.equals("")) {
System.out.println("Geen invoer!");
System.exit(0);
}
return zin;
}
static String filterZin(String zin) {
for (int groteLetters = 65; groteLetters <= 90; groteLetters++) {
groteLetters = groteLetters + 32;
char kleineLetterAlfabet = (char) groteLetters;
}
int specialeTekens1 = 33;
int specialeTekens2 = 58;
int specialeTekens3 = 91;
if (specialeTekens1 <= 47 && specialeTekens2 <= 64 && specialeTekens3 <= 96) {
System.out.println("");
}
System.out.println("Gefilterd: " + zin);
}
}
Nah, come on, nobody posted an answer?
As Rohit pointed out, you never invoked the function!
//this method is the entry point
public static void main(String[] args) {
// invoke getting input, store it in local variable
String input = getInput();
//invoke filtering method, store result in lcal variable
String output = filterZin(input);
}
The filterZin method doesn't really do anything...
Bigger problem, that it is not even valid! The filterZin method is specified to have a String return type - and nothing gets returned. Add a return statement to the end, to get at least a syntactically correct method...
You wrote a method getXYZ() which returns a String when called.
This is your method definition:
static String getInput() {
//your code
return someString;
}
This says, when you'll call this method at any point in the program, this method will return a String object.
Inside your main method:
String returnString = getInput();
This is called method calling or invocation. You will not receive something until you call for it.
Now, about your program asking for input from user.
Here's a simple code for that:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//This will create a chain for input from console
System.out.println("Enter a line:");
String userInput;
try{
userInput = br.readline();
}catch(IOException e){
e.printStackTrace();
}