why not show exact value when Int value start from zero/0? - java

class Method{
String name ;
int Num ;
void text() {
System.out.println(" Hello this code is running coding by "+ name+" number " +Num);
}
}
public class MethodClass {
public static void main(String[] args) {
Method Object = new Method();
Object.name = " NAHIAN " ;
Object.Num = 0123 ;
Object.text();
}
}
Result show:
Hello this code is running coding by NAHIAN number 83
But the 83 should be 0123

when you add a 0 in front, it is refering to an octa (base8) value.
So 0123 is 83 in dec (base10)
To print out a number in octa. You can convert it to string using the following
String convertedString = Integer.toOctalString(0123);
System.out.println("The octa value is " + convertedString);
you can refer to https://www.javatpoint.com/java-decimal-to-octal for more information.

Use String in Num variable instead of integer.
String name ;
String Num ;
void text() {
System.out.println(" Hello this code is running coding by "+ name+" number " +Num);}

Related

not understanding the output of a static initializers

so currently I m preparing for Oracle certified associate java...and I 've run to this question: what is the output of the following code
the solution says that s the output is: u u ucrcr
I know that static initializers only gets called once so
i don t get why the third u is printed
package com.company;
class Order {
static String result = "";
{
result += "c";
}
static {
result += "u";
}
{
result += "r";
}
}
public class Main {
public static void main(String[] args) {
System.out.print(Order.result + " ");
System.out.print(Order.result + " ");
new Order();
new Order();
System.out.print(Order.result + " ");
}
}
It outputs Order.result 3 times, that's why u is printed 3 times.
After the order class is loaded, result is u. You do System.out.print(Order.result + " "); to output it the first time, the you do System.out.print(Order.result + " "); to output it the second time. Then you create 2 instances of the Order class, thus appending "cr" twice, and how your result is ucrcr, so you output ucrcr, where you have your third you.
You must take into account the fact that System.out.print is being used here.

Why isn't my program returning the value of my expression?

I am currently taking an AP Computer Science class in my school and I ran into a little trouble with one of my projects! The project requires me to create a calculator that can evaluate an expression and then solve it. I have got most of that down, but I ran into a little trouble because my teacher asked me to use a while loop to continuously ask for input and display the answer, and I am stuck on that. To end the program the user has to type in "quit" and I can't use system.exit() or any cheating thing like that, the program has to just run out of code. I have got most of that down too, but I am not able to find a why to return the expression in the Method MethodToReadInput(); Does anyone have any tips?
import java.util.*;
public class Calculator {
public static void main(String[] args) {
System.out.println("Welcome to the AP Computer Science calculator!!");
System.out.println();
System.out.println("Please use the following format in your expressions: (double)(space)(+,-,*,/...)(space)(double)");
System.out.println("or: (symbol)(space)(double)");
System.out.println();
MethodToReadInput();
MethodToTestInput(MethodToReadInput());
}
public static String MethodToReadInput() {
Scanner kb = new Scanner(System.in);
System.out.print("Enter an expression, or quit to exit: ");
String expression = kb.nextLine();
if (expression.equalsIgnoreCase("quit")) {
System.out.println("Goodbye!");
}
else {
return expression;
}
}
public static void MethodToTestInput(String expression) {
while (!expression.equalsIgnoreCase("quit")) {
MethodToReadInput();
MethodtoEvaluateInput(expression);
}
System.out.println("Goodbye!");
}
public static void MethodtoEvaluateInput(String expression) {
if (OperatorFor2OperandExpressions(expression).equals("+")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) + SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("*")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) * SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("-")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) - SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("/")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) / SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("^")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + Math.pow(FirstOperandFor2OperandExpressions(expression),SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("|")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.abs(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("v")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.sqrt(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("~")) {
double x = 0.0;
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + (Math.round(OperandFor1OperatorExpressions(expression))+ x));
}
else if (OperatorFor1OperandExpressions(expression).equals("s")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.sin(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("c")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.cos(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("t")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.tan(OperandFor1OperatorExpressions(expression)));
}
}
public static double FirstOperandFor2OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[0];
double y = Double.parseDouble(OperandOrOperator);
return y;
}
public static double SecondOperandFor2OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[2];
double y = Double.parseDouble(OperandOrOperator);
return y;
}
public static String OperatorFor2OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[1];
return OperandOrOperator;
}
public static String OperatorFor1OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[0];
return OperandOrOperator;
}
public static double OperandFor1OperatorExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[1];
double y = Double.parseDouble(OperandOrOperator);
return y;
}
}
You need to put the MethodToReadInput and MethodtoEvaluateInput inside a loop. For example:
public static void main(String[] args)
{
System.out.println("Welcome to the AP Computer Science calculator!!");
System.out.println();
System.out.println("Please use the following format in your expressions: (double)(space)(+,-,*,/...)(space)(double)");
System.out.println("or: (symbol)(space)(double)");
System.out.println();
String input = MethodToReadInput();
while (input != null)//exit the loop and the program when input is null
{
MethodtoEvaluateInput(input);//process the input
input = MethodToReadInput();//ask the user for the next input
}
}
public static String MethodToReadInput()
{
Scanner kb = null;
try
{
kb = new Scanner(System.in);
System.out.print("Enter an expression, or quit to exit: ");
String expression = kb.nextLine();
if (expression.equalsIgnoreCase("quit"))
{
System.out.println("Goodbye!");
return null;
}
else
{
return expression;
}
}
finally
{//always close the Scanner before leaving the method
if (kb != null)
kb.close();
}
}
Also, you should follow the Java Naming Convention and use shorter names for your methods.
Try to simplify your code, and use do-while-loop instead while-loop should produce a better code, do while will at least do one loop and then inspect the next condition before do the next loop, but while will inspect the condition first, if it is okay, it will do the loop. So here is the code:
public class Calculator {
public static void main(String[] args) throws IOException {
System.out.println("Welcome to the AP Computer Science calculator!!");
System.out.println();
System.out.println("Please use the following format in your expressions: (double)(space)(+,-,*,/...)(space)(double)");
System.out.println("or: (symbol)(space)(double)");
System.out.println();
String expression = "";
do {
Scanner kb = new Scanner(System.in);
System.out.print("Enter an expression, or quit to exit: ");
expression = kb.nextLine();
if (expression.equalsIgnoreCase("quit"))
System.out.println("Goodbye!");
else
MethodtoEvaluateInput(expression);
} while (!expression.equalsIgnoreCase("quit"));
inRn.close();
inSw.close();
}
}
Do this:
public static String MethodToReadInput() {
Scanner kb = new Scanner(System.in);
System.out.print("Enter an expression, or quit to exit: ");
String expression = kb.nextLine();
if (expression.equalsIgnoreCase("quit")) {
System.out.println("Goodbye!");
return "";
}
else {
return expression;
}
By returning an empty string you know what to look for when the user wants to exit. It needs to be an empty string that you return because your method is supposed to return a string. Also adding this return statement is needed because the compiler will complain otherwise because it is possible to reach the end of a non-void function (something that returns something) without actually reaching a return statement (so when you enter the if statement as you have it now). You must specify a return case for all possibilities if you specify a return type. In other words you must always return what you say you will.
There are several things that should be fixed about this.
First, let's answer your actual question. You can have a number of choices.
You can just simply return whatever the user has input. In fact, you may not actually need the method for this. But anyway, if your method returns "quit", the while loop can check while ( ! expression.equals("quit") ) just as it does now.
You could return null. This indicates that "The expression is not an actual expression". Then your while could be while ( expression != null ) which is more efficient than string comparison.
But you have other design issues with your program:
You are calling the same methods again and again to retrieve the same things. Those methods split the string - a relatively heavy operation - again and again. You should probably just have a parseExpression() method that returns your tokens, and then something that tests whether these tokens represent a unary operator or a binary one. Something along the lines of:
String [] tokens = parseExpression( expression );
if ( isUnaryExpression( tokens ) ) {
String operator = tokens[0];
String operand = tokens[1];
// Do something with operator and operand.
} else if ( isBinaryExpression( tokens ) ) {
String operator = tokens[1];
String operand1 = tokens[0];
String operand2 = tokens[2];
// Do something with operator and operands {
} else {
System.err.println( "Bad expression!" );
}
You are calling MethodToReadInput twice from your main. This means it will Read one input, do nothing about it, and then read another one which will be passed to MethodToTestInput. Drop the first call, it's unnecessary.
In the cause of better encapsulation, the main method should actually not even call MethodToReadInput. It should become the responsibility of MethodToTestInput to call that method. So you just call MethodToTestInput() from main without passing a parameter at all.
So the structure should be:
main: Display introduction, call your looping method.
looping method: Call input method. Loop while returned expression is still an expression rather than "quit". Inside the loop, call expression handler method.
expression handler method: Call parseExpression() method, check what the tokens are, do the math.
Finally, about your naming issues:
In Java, we name only classes with an uppercase first letter. Constants are named with all capitals (words separated by underscore). Method names begin with a lowercase letter.
You don't name a method MethodThatDoesThis. You should name it doThis, instead. This makes reading your code easier because it actually describe what is happening. So I'd name the methods something like:
The input method: getNextExpression
The looping method: runCalculator, or doCalculatorMainLoop or something like that.
The expression handler method: parseAndCalculate.
Or something along these lines.

How can I get an Output with an increasing number per object with the toString()-Method? Java

I'm using the toString()-Method to get the proper output from my ArrayList.
But I'm still not able to get an Output where the number increases per object.
The current code I have written is as follows:
public class Book {
#Override
public String toString() {
StringBuilder result = new StringBuilder();
int i = 1;
result.append("\n\n-Book "+ i++ +": ");
result.append("\nTitel: " + this.Titel + "§ ");
result.append("\nAuthor: " + this.Autor + "§ ");
return result.toString();
}
by inserting ' i++ ' I'm trying to get an output,
where the number increases for each object from the public class Book();
Current Output:
-Buch **1**:
Titel: Hunger Games§
Author: Suzanne Collins§ ,
-Buch **1**:
Titel: Twilight§
Author: Stephanie Meyer§ ,
-Buch **1**:
Titel: Pride and Prejudice§
Author: Jane Austen§ ,
Output I'm trying to get:
-Buch **1**:
Titel: Hunger Games§
Author: Suzanne Collins§ ,
-Buch **2**:
Titel: Twilight§
Author: Stephanie Meyer§ ,
-Buch **3**:
Titel: Pride and Prejudice§
Author: Jane Austen§ ,
Exactly, you can use a static variable. But instead of increasing it inside the toString() Method id rather increase it in the constructor since your question suggests you want to count the number of objects, not the number of times the toString() method was called on one of your object instances.
public class Book {
private static int i = 0;
public Book(){
i++;
}
#Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append("\n\n-Buch"+ i +": ");
result.append("\nTitel: " + this.Titel + "§ ");
result.append("\nAuthor: " + this.Autor + "§ ");
return result.toString();
}
}
Edit: Below comment is correct, this will always print out how many books have been created the time you call the toString() method of any Book object.
Here is a second Version, you now have one variable per object instance identifing the books number according the time it was created and the same static variable from above, look at the sample output.
public class Book {
private static int i = 0;
private int i2;
public Book() {
i2 = i;
i++;
// or place 'i2 = i;' here if you want to start with "Book 1 of..."
}
#Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append("Book " + i2 + " of " + i + " books in total");
return result.toString();
}
}
Sample Call:
public class SampleCall{
public static void main(String[] args) {
Book b = new Book();
Book b1 = new Book();
Book b2 = new Book();
Book b3 = new Book();
System.out.println(b1);
System.out.println(b1);
}
}
Sample Output:
Book 0 of 4 books in total
Book 1 of 4 books in total
Since you just started using Java consider a solution where you are setting the number for each Book instance by yourself just for completion:
public class Book {
private static int i = 0;
private int bookNumber;
public Book(int bookNumber) {
i++;
/* this.bookNumber means "the variable of the currently in creation book object instance)
* you only need it if its not clear because there is a local variable with the same name
*/
this.bookNumber = bookNumber;
}
// a second (default) constructor in case you want to create book objects and dont yet know the number of it
// after creation you can use the get/set values to access the variable from "outside"
public Book(){
i++;
}
#Override
public String toString() {
StringBuilder result = new StringBuilder();
// Here you dont need this because there is no local variable bookNumber
// You can however always use it when referencing such object variables
result.append("Book " + bookNumber + " of " + i + " books in total");
return result.toString();
}
public int getBookNumber(){
return bookNumber;
}
public void setBookNumber(int bookNumber){
this.bookNumber = bookNumber;
}
}
Sample Call:
public class SumeMain {
public static void main(String[] args) {
Book b = new Book(1);
Book b1 = new Book(2);
Book b2 = new Book();
System.out.println(b);
System.out.println(b1);
//Note below book not yet has a number:
System.out.println("Forgotten book: "+b2);
//But you can set it from "outside" (here)
b2.setBookNumber(3);
System.out.println(b2);
//Also note you now took controll of those numbers so two books can have the same number:
b2.setBookNumber(2);
System.out.println("Duplicate book number: "+b2);
}
}
Sample Output:
Book 1 of 3 books in total
Book 2 of 3 books in total
Forgotten book: Book 0 of 3 books in total
Book 3 of 3 books in total
Duplicate book number: Book 2 of 3 books in total
By such examples i think youre on the best way to learn the language basics, keep up and have fun :)
What you need is to set your i variable as static and class field.
public class Book {
private static int i = 1;
#Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append("\n\n-Book "+ i++ +": ");
result.append("\nTitel: " + this.Titel + "§ ");
result.append("\nAuthor: " + this.Autor + "§ ");
return result.toString();
}
You are calling toString() method on an encapsulated Book object.
It has no knowledge of other Book's in ArrayList.
Try removing those lines from toString() method:
int i = 1;
result.append("\n\n-Book "+ i++ +": ");
And iterate over collection like this:
List<Book> books = ...
for(int i = 0; i < books.size(); i++){
System.out.println("\n\n-Book "+ (i + 1) +": ");
System.out.println(books.get(i));
}
Strange that you know how to use toString() and StringBuilder, but experience problems in iterating collections. Try going back to basic programming techniques.
Also, a lot of answers recommend using a static field. Don't go with that approach. Static fields are not good for this. It won't work in case you have to iterate the collection of books twice.

FileWriter and computing 12-hour based time in java?

I was asked to write a program that will input the employee's id number, time in and time out. The data would be written in a .txt file. I understand that im supposed to use FileWriter but might I ask if its possible to tab the information? Id like to make my .txt file something like this:
Name Time in Time out Total hours worked Salary
Name1 08:00 05:00 9 4000
Name2 09:00 04:00 7 3000
Also, how would i compute the total hours worked in a 12 hour basis?
Here is my source code:
import java.util.Scanner;
import java.io.*;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
class AYANYAN
{static String ans ;
static int empNumber ;
static String timeIn, timeOut;
static Scanner s = new Scanner(System.in);
static String name[] = { "Ayan Ramirez", "Jenifer Sumbi", "Gen Estrada" , "Tugba Cakir", "Lennox Schatje Huisden"};
public static void main(String args[])throws IOException
{
FileWriter fWriter = new FileWriter("EmpData.txt");
for (int i = 0; i < name.length; i++)
{
fWriter.write(name[i] + "\n");
}
fWriter.close();
start () ;
}
public static void control ()
{
System.out.print ("\n\nPlease select one of the following: \nA. Sign Off\nB. Enter Time in\nC. Enter Time out\nD. Exit Program\n") ;
ans = s.next() ;
if (ans.equalsIgnoreCase("A")){
signOff () ;
} else if (ans.equalsIgnoreCase("B")) {
timeIn () ;
} else if (ans.equalsIgnoreCase("C")) {
timeOut () ;
} else if (ans.equalsIgnoreCase("D")){
System.out.print ("\nBYE!\n\n\nProgram made by: Ayan Ramirez\n") ;
} else {
System.out.print ("ERROR!") ;
System.exit(0);
}
}
public static void start ()
{
System.out.print ("Please enter your id number: ") ;
empNumber = s.nextInt();
if (empNumber == 12345){
System.out.print ("\nSigned in as: " + name[0]);
control() ;
} else if (empNumber == 12346){
System.out.print ("\nSigned in as: " + name[1]);
control() ;
}else if (empNumber == 12347){
System.out.print ("\nSigned in as: " + name[2]);
control() ;
}else if (empNumber == 12348){
System.out.print ("\nSigned in as: " + name[3]);
control() ;
} else if (empNumber == 12349){
System.out.print ("\nSigned in as: " + name[4]);
control() ;
}
else {
System.out.print ("\nNTRUDER ALERT!\n\nPLEASE ENTER THE CORRECT ID NUMBER!") ;
start () ;
}
}
public static void signOff ()
{
System.out.print ("Signing off...\n") ;
start () ;
}
public static String timeIn ()
{
System.out.print ("Please enter time in: ") ;
timeIn = s.next () ;
control () ;
return (timeIn) ;
}
public static String timeOut ()
{
System.out.print ("Please enter time out: ") ;
timeOut = s.next () ;
control () ;
return (timeOut) ;
}
}
The easiest way to produce this kind of output is to use String.format() - its format string syntax supports padding as well as date and time formatting.
With regards to tabbing your information, what exactly do you mean by that?
Do you mean to print a white space which is the same as if you pressed the tab button on your keyboard, or do you mean to allow a program such as excel to be able to display items in colums?
For the first one, if you print something like this: str1 + "\t" + str2, this will cause a white space to be placed between str1 and str2, just as if you pressed the tab key on your keyboard.
If it is the second option, you would nee to enter a delimiter, such as a ; to allow a program such as excel to split them for you, so you will need to do something like this: str1 + ";" + str2.
For the second question, you can take a look at the SimpleDateFormat class. You can do something like so:
K:mm a
This should print the time in AM/PM format.
You can use \t as a tabulation char in Java. A slightly better option is the following: you can just determine the length of the current part of the string by int n = s.length() and append a number of spaces to it to get a fixed string length m. This gives you more freedom on the width than \t, and for varying string length you'd need this anyway.
Sample code:
public String tab(String s, int m) {
int n = s.length();
StringBuffer sb = new StringBuffer();
for (int i=n; i<m; i++) sb.append(" ");
return s+sb.toString();
}

Why does my program immediately crash, displaying "java.lang.NoSuchMethodError: main"?

Exercise 1: Write an application that prints the hundreds digit in two integers read from the keyboard. For example, if the data values are 1456 and 254 respectively, your program should print 4 and 2. You may choose the integers yourself. Your output should include the original number followed by the digit in the hundreds position. Label your output appropriately.
That was my question; here's the code I attempted to write using Eclipse.
public class Hundreds
{
int first1 = 1523;
first2 = first1 % 1000;
first3 = first2 / 100;
System.out.println("Original number equals: " + first1);
System.out.println("Hundreds digit equals: " + first3);
int second1 = 589;
second2 = 589 / 100;
System.out.println("Original number equals: " + second1);
System.out.println("Hundreds digit equals: " + second2);
}
I'm sure there would be a better method to naming the numbers; that's just what I came up with… but Eclipse shows an error reading:
java.lang.NoSuchMethodError: main
Exception in thread "main"
when I attempt to run it. Any ideas on what I've done incorrectly here?
You need a main() method. The error message you see is because the JVM wants to run main(), but it cannot find it.
A canonical Java example (taken from http://en.wikipedia.org/wiki/Java_(programming_language)#Hello_world) is:
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
}
You need to put your logic in a main method:
public class Hundreds {
public static void main(String[] args) {
int first1 = 1523;
first2 = first1 % 1000;
first3 = first2 / 100;
System.out.println("Original number equals: " + first1);
System.out.println("Hundreds digit equals: " + first3);
int second1 = 589;
second2 = 589 / 100;
System.out.println("Original number equals: " + second1);
System.out.println("Hundreds digit equals: " + second2);
}
}
You need to have a main method as in the Java programming language, every application must contain a main method (entry point) whose signature is:
public static void main(String[] args)
So your code should look like:
public class Hundreds
{
public static void main(String[] args) {
int first1 = 1523;
int first2,first3,second2;
first2 = first1 % 1000;
first3 = first2 / 100;
System.out.println("Original number equals: " + first1);
System.out.println("Hundreds digit equals: " + first3);
int second1 = 289;
second2 = 589 / 100;
System.out.println("Original number equals: " + second1);
System.out.println("Hundreds digit equals: " + second2);
}
}
You could see The Method main; it's a short explanation of its usages.
You need a main method.
public class Hundreds {
public static void main(String[] args) {
// put code here
}
}
Dude...
Where is your main method?
public static void main.....
The rest of your code should go inside it...
BTW, this is the part where you hit your forehead and say "duh..." ;-)
Good luck

Categories

Resources