not understanding the output of a static initializers - java

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.

Related

How to alphabetize strings in Java using functions

import java.util.Scanner;
public class alphabetical {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner Alphabet= new Scanner(System.in);
System.out.println("Input First Name");
String UserInput= Alphabet.next();
System.out.println("Input second name");
String UserInput2= Alphabet.next();
System.out.println("Input third name");
String UserInput3= Alphabet.next();
System.out.println(alpha)UserInput,UserInput2,UserInput3));
}
public static void alpha(String fromUser,String fromUser2, String fromUser3)
{
if (fromUser.compareTo(fromUser2)>0)
{
System.out.println(fromUser2);
}
else if(fromUser.compareTo(fromUser3)>0)
{
System.out.println(fromUser3);
}
else if (fromUser2.compareTo(fromUser3)>0)
{
System.out.println(fromUser3);
}
else if (fromUser2.compareTo(fromUser)>0)
{
System.out.println(fromUser);
}
else if (fromUser3.compareTo(fromUser)>0)
{
System.out.println(fromUser);
}
else if (fromUser3.compareTo(fromUser2)>0)
{
System.out.println(fromUser2);
}
}
}
So that's my code but I don't know what I'm doing wrong. I've been working on this for a while and I need a code that will allow the user to input 3 names and then sort the names in alphabetical order
The requirements for this program is to have the user input 3 strings and print them out ordered alphabetically using a function that takes 3 strings-- the return type should be void-- this means that there nothing returned back to main, the function will just print out the three words in alphabetical order there should be 6 cases you need to worry about (think If, elseif...else).
Here is what a sample output might look like in the console (> denotes it's in the console-- you won't actually see this):
input first lowercase string
awesome
input second lowercase string
bogus
input third lowercase string
chillin
(THE FOLLOWING HAPPENS IN THE VOID FUNCTION)
Here are your words in alphabetical order
awesome
bogus
chillin
If you're really not allowed to use arrays or lists, I hope your professor is making you write a long-winded solution, so that he can "reveal" the better, array or list based version later.
For three items, it's true that there are six cases, and you can "just" write an if/else clause for each one:
// case 1 - abc
if(lessThan(a,b) && lessThan(b,c)) {
System.out.println(a + " " + b + " " + c);
}
// case 2 - acb
else if(lessThan(a,c) && lessThan(c,b)) {
System.out.println(a + " " + c + " " + b);
}
// case 3 - bac
else if(lessThan(b,a) && lessThan(a,c)) {
System.out.println(b + " " + a + " " + c);
}
... and so on, for each of abc,acb,bac,bca,cab,cba. For my own sanity I've assumed the existence of a lessThan() method containing a.compareTo(b) < 0 -- but you could use compareTo() directly if your professor also forbids you writing helper methods.
Because of the wording of the question, I guess this is what's expected -- it's not a sensible way to implement a sort, but it could be the basis on which to build something better. It does also allow you to directly count how many comparisons are being made, which could lead to some beginner's insight into the cost of an algorithm.
If you're allowed to use an array, and you're allowed to use a sort routine provided by Java, then just put the values into an array, sort it and print it:
public static void alpha(String a,String b, String c) {
String[] array = new String[] {a,b,c};
Arrays.sort(array);
System.out.println(array[0] + " " + array[1] + " " + array[2]);
}
In java 8 it is simple. You can sort collection of strings with lambda:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner Alphabet = new Scanner(System.in);
System.out.println("Input First Name");
String UserInput = Alphabet.next();
System.out.println("Input second name");
String UserInput2 = Alphabet.next();
System.out.println("Input third name");
String UserInput3 = Alphabet.next();
List<String> list = Arrays.asList(UserInput, UserInput2, UserInput3);
list.sort((String in1, String in2) -> in1.compareTo(in2));
list.forEach(System.out::println);
}
So you can use anything as long as you put it in a method ...
public static void alpha(String fromUser,String fromUser2, String fromUser3){
String[] sArray = {fromUser, fromUser2, fromUser3};
Arrays.sort(sArray);
for (String s : sArray){
System.out.print(s + " ");
}
}
Using java 8 streams you can do it like that:
public static void alpha(String fromUser,String fromUser2, String fromUser3) {
Stream.of(fromUser, fromUser2, fromUser3).sorted().forEach(System.out::println);
}
You're close, but you need to be comparing your String to both other Strings before producing your output. One approach is to create an individual if/else if/else block for each of your three lines of output. For example, here's the middle line given Strings s1, s2, s3.
// First Word
. . .
// Second Word
if ( (s1.compareTo(s2) >= 0) && (s1.compareTo(s3) <= 0) ) {
System.out.println(s1);
} else if ( (s2.compareTo(s1) >= 0) && (s2.compareTo(s3) <= 0) ) {
System.out.println(s2);
} else {
System.out.println(s3);
}
// Third Word
. . .
Another approach is to account for every permutation of how three things can be arranged. {abc, acb, bac, bca, cab, cba }. This is manageable when you have only three things to arrange, but gets quite nasty when you add more.
if ( (s1.compareTo(s2)<=0) && (s1.compareTo(s3)<=0) && (s2.compareTo(s3)<=0) ) {
// abc
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
} else if (s1.compareTo(s2)<=0) && (s1.compareTo(s3)<=0) && (s2.compareTo(s3)>=0) {
// acb
System.out.println(s1);
System.out.println(s3);
System.out.println(s2);
} else if . . .

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.

I want to get pick out a value scanned from a method and get sum of 3 instances of the method

Here is the code
import java.util.ArrayList;
import java.util.Scanner;
public class recycleBeta {
public static void main(String[] args) {
System.out.println("Insert bottles with pant A");
System.out.println(bottleList(1));
System.out.println();
System.out.println("Insert bottles with pant B");
System.out.println(bottleList(2));
System.out.println();
System.out.println("Insert bottles with pant C");
System.out.println(bottleList(3));
}
public static String bottleList(int args) {
Scanner bottler = new Scanner(System.in);
int count = 0;
ArrayList<String> bottles = new ArrayList<String>();
System.out.println("Press 1 and enter for each bottle, end with 0");
String cont;
while (!(cont = bottler.next()).equals("0"))
{
bottles.add(cont);
count++;
}
return ("You have inserted " + count + " bottles");
}
}
I want to add a certain multiplier to each of the bottleList(1),(2) and (3).
So say that "count" value in bottleList(1) would be multiplied by 1.5, bottleList(2) by 2.0 and bottleList(3) by 3.0.
I would also like to sum the total amount of bottles scanned from the 3 instances in the Main method. At this stage though, I'm clueless on how to do so without creating 3 different method to call upon, which seems a bit redundant. If you have any suggestions as to improve the code a bit, I'm all ears (I'm 4 weeks into programming Java).
You don't actually use the "args" parameter you pass to the bottleList method.
Change the type of "args" from int to double, pass in 1.5, 2, 3 then add something like this at the end of the method.
return ("You have inserted " + (count * args) + " bottles");
Unless I've misunderstood what you're trying to do. Also change the name of args to something with meaning, like "multiplier".

Static Blocks - when are they executed

I'm totally new to Java and I'm wondering why my static block is not executing.
public class Main {
public static void main(String[] args) {
Account firstAccount = new Account();
firstAccount.balance = 100;
Account.global = 200;
System.out.println("My Balance is : " + firstAccount.balance);
System.out.println("Global data : " + Account.global);
System.out.println("*******************");
Account secondAccount = new Account();
System.out.println("Second account balance :" + secondAccount.balance);
System.out.println("Second account global :" + Account.global);
Account.global=300;
System.out.println("Second account global :" + Account.global);
Account.add(); }
}
public class Account
{
int balance;
static int global;
void display()
{
System.out.println("Balance : " + balance);
System.out.println("Global data : " + global);
}
static // static block
{
System.out.println("Good Morning Michelle");
}
static void add()
{
System.out.println("Result of 2 + 3 " + (2+3));
System.out.println("Result of 2+3/4 " + (2+3/4));
}
public Account() {
super();
System.out.println("Constructor");
}
}
My output is:
Good Morning Michelle
Constructor
My Balance is : 100
Global data : 200
*******************
Constructor
Second account balance :0
Second account global :200
Second account global :300
Result of 2 + 3 5
Result of 2+3/4 2
I want to know why "Good Morning Michelle" was not displayed when I went in with the second account.
From the research I have done, this static block should execute each time the class is called (new Account).
Sorry for the real beginner question.
Michelle
Your static block that prints "Good Morning Michelle" is a static initializer. They are run only once per class, when that class is first referenced. Creating a second instance of the class will not cause it to run again.
Static blocks are executed the first time the Class is loaded. This is why you see the output once. Check out more details here: Understanding static blocks

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