How to write static method call without object instantiation - java

Doing some work, and I need to write the method using Object Oriented Programming, and to make the method without the object instantiation.
I do just not know how to do this. Ive been returned the following feedback:
Your main() method should go in the tester class, while all of the implementation methods and
constructor should go in the object class.
Here's some code, thank you!
public static void main(String[] args) throws IOException
{
// variables
Scanner in = new Scanner(System.in);
File fileRead = new File("/Users/jerome/Desktop/MorseCode.txt");
Scanner withinFile = new Scanner (fileRead);
String userInput = "";
String toMorse = "";
String[] file = new String[25];
String[] alp = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "o", "m", "n", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
for(int i = 0; i < 25; i ++)
{
file[i] = withinFile.nextLine();
}
System.out.print("Enter a word to translate: ");
userInput = in.nextLine();
// static methods
MorseCode2 morse = new MorseCode2();
morse.tooMorse(userInput, alp, file, toMorse);
// output
System.out.print("'"+ userInput+"'"+" translated into Morse Code is: " + tooMorse(userInput, alp, file, toMorse));
}
Annnd some more!
public static String tooMorse(String userInput, String[] alp, String[] file, String toMorse)
{
for(int i = 0; i < userInput.length(); i ++)
{
if(userInput.substring(i, i+1).equals(alp[i])) // a
{
toMorse += " " + file[i];
}
else if(userInput.substring(i, i+1).equals(alp[i+1])) // b
{
toMorse += " " + file[i+1];
}
else if(userInput.substring(i, i+1).equals(alp[i+2])) // c
{
toMorse += " " + file[i+2];
}
else if(userInput.substring(i, i+1).equals(alp[i+3])) // d
{
toMorse += " " + file[i+3];
}
else if(userInput.substring(i, i+1).equals(alp[i+4])) // e
{
toMorse += " " + file[i+4];
}
else if(userInput.substring(i, i+1).equals(alp[i+5])) // f
{
toMorse += " " + file[i+5];
}
else if(userInput.substring(i, i+1).equals(alp[i+6])) // g
{
toMorse += " " + file[i+6];
}
else if(userInput.substring(i, i+1).equals(alp[i+7])) //h
{
toMorse += " " + file[i+7];
}
else if(userInput.substring(i, i+1).equals(alp[i+8])) // i
{
toMorse += " " + file[i+8];
}
else if(userInput.substring(i, i+1).equals(alp[i+9])) // j
{
toMorse += " " + file[i+9];
}
else if(userInput.substring(i, i+1).equals(alp[i+10])) // k
{
toMorse += " " + file[i+10];
}
else if(userInput.substring(i, i+1).equals(alp[i+11])) // l
{
toMorse += " " + file[i+11];
}
else if(userInput.substring(i, i+1).equals(alp[i+12])) // m
{
toMorse += " " + file[i+12];
}
else if(userInput.substring(i, i+1).equals(alp[i+13])) // n
{
toMorse += " " + file[i+13];
}
else if(userInput.substring(i, i+1).equals(alp[i+14])) //o
{
toMorse += " " + file[i+14];
}
else if(userInput.substring(i, i+1).equals(alp[i+15])) // p
{
toMorse += " " + file[i+15];
}
else if(userInput.substring(i, i+1).equals(alp[i+16])) // q
{
toMorse += " " + file[i+16];
}
else if(userInput.substring(i, i+1).equals(alp[i+17])) // r
{
toMorse += " " + file[i+17];
}
else if(userInput.substring(i, i+1).equals(alp[i+18])) // s
{
toMorse += " " + file[i+18];
}
else if(userInput.substring(i, i+1).equals(alp[i+19])) // t
{
toMorse += " " + file[i+19];
}
else if(userInput.substring(i, i+1).equals(alp[i+20])) // u
{
toMorse += " " + file[i+20];
}
else if(userInput.substring(i, i+1).equals(alp[i+21])) // v
{
toMorse += " " + file[i+21];
}
else if(userInput.substring(i, i+1).equals(alp[i+22])) // w
{
toMorse += " " + file[i+22];
}
else if(userInput.substring(i, i+1).equals(alp[i+23])) // x
{
toMorse += " " + file[i+23];
}
else if(userInput.substring(i, i+1).equals(alp[i+24])) // y
{
toMorse += " " + file[i+24];
}
else if(userInput.substring(i, i+1).equals(alp[i+25])) // z
{
toMorse += " " + file[i+25];
}
else
{
return "no";
}
}
return toMorse;

MorseCode2 morse = new MorseCode2();
morse.tooMorse(userInput, alp, file, toMorse);
Change this to:
MorseCode2.tooMorse(userInput, alp, file, toMorse);
If you have other static methods like that, do the same thing.
Unlike normal methods, you don't call static methods on an instance of the class - only on the class itself. If you do write morse.tooMorse(...) the compiler will simply convert it to MorseCode2.tooMorse(...) for you, and emit a warning. So your original code is equivalent to this:
MorseCode2 morse = new MorseCode2();
MorseCode2.tooMorse(userInput, alp, file, toMorse);
which is slightly inefficient since morse isn't used anywhere.

Related

Java for loop TMC testing failed even if it works as intended (Mooc.fi)

The task is to:
Part one:
Write a program which prints the integers from 1 to a number given by the user.
Sample output part 1
Part two:
Ask the user for the starting point as well.
Sample output part 2
My code:
import java.util.Scanner;
import javax.swing.plaf.synth.SynthOptionPaneUI;
public class FromWhereToWhere {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// part one
System.out.println("Where to?");
int end = Integer.valueOf(scanner.nextLine());
for (int i = 1; i < end + 1; i++) {
System.out.println(i);
}
// part two
System.out.println("Where to?");
end = Integer.valueOf(scanner.nextLine());
System.out.println("Where from?");
int start = Integer.valueOf(scanner.nextLine());
for (int i = start; i < end + 1; i++) {
System.out.println(i);
}
}
}
It works as intended my terminal
But I get an error in TMC saying
FAIL:
WhereFromTest test
NoSuchElementException: No line found
The code for testing:
import fi.helsinki.cs.tmc.edutestutils.MockStdio;
import fi.helsinki.cs.tmc.edutestutils.Points;
import fi.helsinki.cs.tmc.edutestutils.ReflectionUtils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.*;
import static org.junit.Assert.*;
#Points("02-16.2")
public class WhereFromTest {
#Rule
public MockStdio io = new MockStdio();
#Test
public void test() {
int[][] pairs = {{1, 1}, {12, 8}, {50, 100}, {-2,2}};
for (int[] pair : pairs) {
test(pair);
}
}
private void test(int[] pair) {
io.setSysIn(pair[0] + "\n" + pair[1] + "\n");
int len = io.getSysOut().length();
ReflectionUtils.newInstanceOfClass(FromWhereToWhere.class);
FromWhereToWhere.main(new String[0]);
String output = io.getSysOut().substring(len);
output = output.replaceAll("[^-\\d]+", " ").trim();
String[] lines = output.split("\\s+");
int linesInOutput = (lines.length == 1 && lines[0].isEmpty()) ? 0 : lines.length;
int linesCount;
if(pair[0] < pair[1]) {
linesCount = 0;
} else {
linesCount = pair[0] - pair[1] + 1;
}
if (linesCount != linesInOutput) {
String numbersCount = (linesCount == 1) ? "number": "numbers";
fail("With the input " + pair[0] + ", " + pair[1] + " output should contain " + linesCount + " " + numbersCount + ", now it contained " + linesInOutput);
}
if(linesCount == 0) {
return;
}
int firstNumber = Integer.valueOf(lines[0]);
if(firstNumber != pair[1]) {
fail("With the input " + pair[0] + ", " + pair[1] + " the first printed number should be " + pair[1] + ", now it was " + firstNumber);
}
int lastNumber = getLastNumber(output);
if(lastNumber != pair[0]) {
fail("With the input " + pair[0] + ", " + pair[1] + " the last printed number should be " + pair[0] + ", now it was " + lastNumber);
}
}
private static int getLastNumber(String inputStr) {
String patternStr = "(?s).*?(-?\\d+)\\s*$";
Matcher matcher = Pattern.compile(patternStr).matcher(inputStr);
assertTrue("The output should be a number.", matcher.find());
int number = Integer.valueOf(matcher.group(1));
return number;
}
}

Array values being set for everything (Java)

In my code below, I am having an issue where I add the customer name to one room, but instead it adds the customer to every room. I can't figure out what in my code the issue is. I have tried removing the procedure but that still produced the same problem.
package test;
import java.util.*;
public class test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String choice, custName = "";
int roomNum = 1;
String[] hotel = new String[12];
String[] customer = new String[12];
hotelInitialise(hotel);
custInitialise(customer);
while ( roomNum < hotel.length-1 ) {
for (int i = 0; i < hotel.length-1; i++) {
System.out.println("This is the Hotel Menu. Please choose from the following options:\n");
System.out.println("A: " + "This will add a new entry\n");
System.out.println("V: " + "View all rooms\n");
choice = input.next().toUpperCase();
if (choice.equals("A")) {
System.out.println("Enter room number(1-10)");
roomNum =input.nextInt();
System.out.println("Enter name for room " + roomNum + " : " ) ;
custName = input.next();
addNewBooking(hotel, custName);
System.out.println(" ");
}
if (choice.equals("V")) {
seeAllRooms(hotel, custName);
}
}
}
}
// When the program loads it will assign all the values of the array as being empty
private static void hotelInitialise( String hotelRef[] ) {
for (int x = 0; x < 11; x++){
hotelRef[x] = "Room " + x + " is empty.";
}
System.out.println( "Welcome to the Summer Tropic Hotel.\n");
}
private static void custInitialise (String custRef[]) {
for (int i = 0; i < 11; i++) {
custRef[i] = ", no customer has occupied this room";
}
}
private static void addNewBooking(String hotel[], String customer) {
for (int x =1; x <11; x++) {
if (hotel[x].equals("Room " + hotel[x] + " is empty."))
System.out.println("Room " + x + " is empty.");
else {
System.out.println("Room " + x + " is occupied by "+ customer);
}
}
}
private static void seeAllRooms(String hotel[], String customer) {
for (int i = 0; i < hotel.length-1; i++) {
int j=0;
String custName = customer;
hotel[j]= custName;
if (hotel[i].equals("Room " + i + " is empty."))
System.out.println("Room " + i + " is empty.");
else {
System.out.println("Room " + i + " is occupied by "+ hotel[j] + ".");
}
}
}
}
In addNewBooking method you have this line:
if (hotel[x].equals("Room " + hotel[x] + " is empty."))
However hotel[x] has a value of "Room x is empty" e.g. hotel[1] is "Room 1 is empty" So the final check is becoming "hotel[x].equals(Room Room x is empty is empty.)" which is never equals to your hotel[x]
You have to change your code to
if (hotel[x].equals("Room " + x + " is empty."))
//do something there like add the booking

How can I use a while to continuously ask for input from a user and exit the program when "quit" is typed without using system.exit()?

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. 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();
next();
}
public static void next() {
Scanner kb = new Scanner(System.in);
System.out.print("Enter an expression, or quit to exit: ");
String expression = kb.nextLine();
next3(expression);
}
public static void next3(String expression) {
while (!expression.equals("quit")) {
next2(expression);
next();
}
}
public static void next2(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;
}
public static boolean QuitFunction(String expression) {
if (expression.equalsIgnoreCase("quit")) {
System.out.println("Goodbye!");
return false;
}
else {
return true;
}
}
}
Take a look at this code. I think this might help you in the right direction. It's similar to what you have already written except it eliminates the need for method calls in your while loop.
Scanner input = new Scanner(System.in);
while (!input.hasNext("quit")) {
String expression = input.nextLine(); // gets the next line from the Scanner
next2(expression); // process the input
}
// once the value "quit" has been entered, the while loop terminates
System.out.println("Goodbye");
Writing it this way drastically cleans up your code and prevents a new declaration of Scanner kb = new Scanner(System.in); each time an input is processed.

Java code prints right but returns wrong

The following code:
public class NewClass1 {
public static String mus = "";
public static String musCal(String[] signal, int[] time) {
int i = 0;
while (i < signal.length) {
switch (signal[i]) {
case "x": {
// System.out.print("x = ");
mus = mus + "x";
int sum = time[i];
if (signal[i + 1] == "C") {
i++;
while (i < signal.length && signal[i] == "C") {
sum += time[i];
i++;
}
} else
i++;
// System.out.print(sum + " ");
mus = sum + " ";
break;
}
case "y": {
// System.out.print("y = ");
mus = mus + "y ";
int sum = time[i];
if (signal[i + 1] == "C") {
i++;
while (i < signal.length && signal[i] == "C") {
sum += time[i];
i++;
}
} else
i++;
// System.out.print(sum + " ");
mus = sum + " ";
break;
}
case "z": {
// System.out.print("z = ");
mus = mus + "z ";
int sum = time[i];
if (signal[i + 1] == "C") {
i++;
while (i < signal.length && signal[i] == "C") {
sum += time[i];
i++;
}
} else
i++;
// System.out.print(sum + " ");
mus = sum + " ";
break;
}
}
}
return mus;
}
public static void main(String[] args) {
String signal[] = { "x", "y", "y", "C", "C", "z", "C", "C", "x", "C" };
int time[] = { 2, 5, 1, 4, 7, 8, 2, 6, 4, 3 };
musCal(signal, time);
System.out.print(mus);
}
}
The expected output from the code is:
x=2 y=5 y=12 z=16 x=7
If the comments signs // are removed to activate the System.out.print statements, the code gives the expected output. But when I was trying to collect this output in the form of 'String mus', as shown in the code, I got only the last element of the output string i.e. 7. Being new comer to java and programming, I need your help. Kindly help me to correct the return statement so that I may get the right output as String 'mus' by concatenating, or by any other suitable method.
you can also use this solution for :
replace mus=sum + " ";
with mus += sum + " ";
You overwrite mus at several places using
mus=sum + " ";
instead of concatenating it like
mus = mus + sum + " "
Also, you don't always use brackets for if and else, which is very bad code style and I condemn the Java inventors for making brackets optional if one only wants to execute a single line.

I'm trying to use 2 user inputs to populate a 2d list array

I'm trying to populate a 2d list array using 2 user inputs.
Problem I'm having is that in the code below, the 1st for statement isn't producing the outcome I'm expecting, the 2nd for is doing what is needed. Also, with the code below I'm unable to close scanner.
public static void main(String[] args) {
ArrayList<String> listCon = new ArrayList<String>();
ArrayList<String> listCol = new ArrayList<String>();
Scanner txtInput = new Scanner(System.in);
char addTo = 'y';
do {
System.out.println("\nCurrent list is " + listCon + listCol + "\n");
System.out.println("Would you like to add a country to the list?\n\t"
+ "( y ) = YES\n\t( n ) = NO");
addTo = txtInput.next().toLowerCase().charAt(0);
if (addTo == 'y') {
System.out.println("Enter country name: ");
listCon.add(txtInput.next().toLowerCase());
System.out.println("Enter colour: ");
listCol.add(txtInput.next().toLowerCase());
} else if (addTo == 'n') {
int i = 1;
int countCon = listCon.size();
if(countCon == 0) {
System.out.println("No countries have been entered.");
} else {
String str = "country";
if(countCon > 1) {
str = "countries";
}
System.out.println("Thankyou for your input. We found " + countCon + " " +
str + " in the list.");
System.out.println("Listed " + str + ":\n");
for(String n : listCon) {
char[] conDigit = n.toCharArray();
conDigit[0] = Character.toUpperCase(conDigit[0]);
n = new String(conDigit);
for(String b : listCol) {
char[] colDigit = b.toCharArray();
colDigit[0] = Character.toUpperCase(colDigit[0]);
b = new String(colDigit);
System.out.println("Country " + i + " : " + n + " - \t" + b);
i = i + 1;
}
break;
}
break;
}
} else {
System.out.println("Incorrect input detected. please try again. \n");
}
} while (true);
}
}
You need to remove extra break from the first for loop to iterate. Otherwise, you break after first iteration.
for(String n : listCon) {
....
for(String b : listCol) {
...
}
break; //remove this!
}
break;
EDIT
The result im after is Country 1 : France - Blue Country 2 : UK -
White Country 3 : Ireland - Green
You need to iterate like this:
for (int i = 0; i < listCon.size() && i < listCol.size(); i++) {
String n = listCon.get(i);
char[] conDigit = n.toCharArray();
conDigit[0] = Character.toUpperCase(conDigit[0]);
n = new String(conDigit);
String b = listCol.get(i);
char[] colDigit = b.toCharArray();
colDigit[0] = Character.toUpperCase(colDigit[0]);
b = new String(colDigit);
System.out.println("Country " + i + " : " + n + " - \t" + b);
}

Categories