User input and object creation inside method - java

I have a Java Class named Real
public class Real {
private long wholeNumPart;
private long decimalPart;
public Real(){
wholeNumPart =0;
decimalPart=0;
}
public Real(long wholeNumPart, long decimalPart) {
this.wholeNumPart =wholeNumPart;
this.decimalPart = decimalPart;
}
public long getWholeNumPart() {
return wholeNumPart;
}
public long getDecimalPart() {
return decimalPart;
}}
I have another class name RealApplication where I need to create two methods
createRealObject() that allows a user to input a real number and creates an object representing
that number.
2.createRealNumber() which accepts an object of type Real and returns a real number represented
by that object.
I am having difficulty creating these two methods
Here is what I've done so far
import java.util.Scanner;
public class RealApplication {
public void createRealNumber() {
Scanner sc=new Scanner(System.in);
//Allows user input
System.out.print("Please, enter a real number: ");
long n = sc.nextLong();
//Creates Real object ( is this correct????)
Real in = new Real();
}
public long createRealNumber(Real num) {
long realNum=0;
//I do not know what to write here :(
return realNum;
}
}

Your Real class looks good with some changes in the RealApplication class we can achieve what you want:
import java.util.Scanner;
public class RealApplication {
public static Real createRealObject() {
Scanner sc=new Scanner(System.in);
//Allows user input
System.out.print("Please, enter a real number: ");
String n = sc.nextLine();
String[] pieces = n.split("[.,]+"); //special pattern to recognize comma and dot
long wholeNumPart;
long decimalPart;
try {
wholeNumPart = Long.valueOf(pieces[0]);
decimalPart = Long.valueOf(pieces[1]);
}
catch (NumberFormatException e) {
System.out.println("You should enter a number!");
return null;
}
Real in = new Real(wholeNumPart, decimalPart);
sc.close();
return in;
}
The important point is that I declared the both methods as static in this way you can use the methods without creating an instance of RealApplication class.
You should use "double" primitive type to store fractional numbers not "long". Now the method that returns the number equivalent of that object:
public static double createRealNumber(Real num) {
double realNum;
long wholeNumPart = num.getWholeNumPart();
long decimalPart = num.getDecimalPart();
int numOfDigits = (int)(Math.log10(decimalPart)+1);
realNum = wholeNumPart + (decimalPart / Math.pow(10,numOfDigits));
return realNum;
}
And if we write a main method:
public class Main {
public static void main(String[] args) {
Real realObj = new Real(10,2323232);
double number = RealApplication.createRealNumber(realObj);
System.out.println("Equivalent number for the object: " + number);
Real newObj = RealApplication.createRealObject();
if (newObj != null) {
System.out.println("New object's number part: " + newObj.getWholeNumPart());
System.out.println("New object's decimal part: " + newObj.getDecimalPart());
}
else{
return;
}
}
}
Because of the regex pattern we used, the inputs separated with "." and "," are allowed like 10.23 10,23 .

Related

Changing and using one object array in two methods

I'm making a phone class and a phone book class right now. The phone class declares name and phone number fields, and the phone book class has read and run methods. When run() method is executed in the main function, information is input through the read() method, and information is retrieved and output through the run() method. However, I declared an instance array called phonebooks and tried to input the information received from the read() method into the array, but when I tried to output it through the run method, the array instances were not saved properly. There seems to be an issue where something isn't saving properly, how do I fix it?
import java.util.Scanner;
class Phone {
static private String name;
static private String tel;
public String getNum() {
return tel;
}
public String getName() {
return name;
}
public Phone(String name, String tel) {
this.name = name;
this.tel = tel;
}
}
public class PhoneBook {
private Scanner scanner;
static int repeat;
static Phone[] phonebooks;
public PhoneBook() {
scanner = new Scanner(System.in);
}
void read() {
System.out.print("Number of person to store? >> ");
int repeat = scanner.nextInt();
Phone[] phonebooks = new Phone[repeat];
for (int i = 0; i < repeat; i++) {
System.out.print("Name and Tel. No. >> ");
String name = scanner.next();
String tel = scanner.next();
phonebooks[i] = new Phone(name, tel);
if (i == repeat - 1) break;
}
System.out.println("Saved.");
}
void run() {
read();
while (true) {
System.out.print("Who do you wanna search for? >> ");
String search = scanner.next();
if (search.equals("stop")) break;
int i;
for (i = 0; i < repeat; i++) {
if (phonebooks[i].getName() == search)
System.out.println(search + "'s number is " + phonebooks[i].getNum());
break;
}
}
scanner.close();
}
public static void main(String[] args) {
new PhoneBook().run();
}
}
There are few issues in your code, below are some suggestions to make it work--
change member variables from static private to only private in Phone
Don't redeclare repeat & phonebooks in read().
Change if (phonebooks[i].getName() == search) call in run() to if (phonebooks[i].getName().equalsIgnoreCase(search)) so that it will search & match search string.

Checking temperature conditions

How could I set appropriate temperature within these three conditions at least at 98°C, 99°C, 1°C & 2°C etc?
package boiling.freezing;
import java.util.Scanner;
public class BoilingFreezing {
public static void main(String[] args) {
System.out.println("Give the temperature : ");
Scanner sc = new Scanner(System.in);
int temp = sc.nextInt();
if (temp >= 100){
System.out.println("The water is boiling!");
}
else if (temp <= 0){
System.out.println("The water is freezing!");
}
else{
System.out.println("The water is at normal_state!");
}
}
}
I'm going to offer you a pattern, not a simple if-elseif-else block.
You might want to have an interface Temperature
interface Temperature {
/** Returns true if the temperature matches the criteria. */
boolean within(final int temperature);
/** Returns an appropriate, descriptive, message. */
String message();
}
You can then implement this interface to meet your multiple criteria
class BoilingTemperature implements Temperature {
public boolean within(final int temperature) {
return temperature > 99;
}
public String message() {
return "Water boiling";
}
}
class FreezingTemperature implements Temperature {
public boolean within(final int temperature) {
return temperature < 1; // Should be 3 degree! But anyway.
}
public String message() {
return "Water freezing";
}
}
You can use this pattern to write custom temperature handlers
class YourCustomTemperature implements Temperature {
public boolean within(final int temperature) {
return temperature > 6 && temperature < 40;
}
public String message() {
return "Your custom message";
}
}
You need to maintain a list of those concrete implementations and loop them to check which matches.
final List<Temperature> temperatures = new ArrayList<>(6);
temperatures.add(new BoilingTemperature());
temperatures.add(new FreezingTemperature());
temperatures.add(new YourCustomTemperature());
...
And then
public static void main(String[] args) {
System.out.println("Give the temperature : ");
final Scanner sc = new Scanner(System.in);
int temp = sc.nextInt();
for (final Temperature t : temperatures) {
if (t.within(temp)) {
System.out.println(t.message());
}
}
}
Based on LppEdd's answer if you are using Java 8+ you can make use of java predicate
java.util.function.Predicate was introduced that behaves as an assignment target in lambda expressions and
functional interfaces. The functional method of Predicate is
test(Object) .

How can I access my private variables across different classes?

I am working on creating a hangman-like game. It reads from a .txt file of four letter words and randomly selects one of the words and the player will then have 7 tries to guess the word...I have not completed that all yet, I am having trouble accessing my variables from one class to the other. Here is my code:
package wordguessinggame2;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class WordGuessingGame2 {
static class RandomWordProvider {
public final List<String> words;
public RandomWordProvider() {
words = readFile();
}
public int randomInteger() {
int randomInt = (int) (Math.random() * words.size());
return randomInt;
}
private String getWord() {
int randomPosition = randomInteger();
String randomWord = words.get(randomPosition);
return randomWord;
}
private List<String> readFile() {
List<String> wordsList = new ArrayList<>();
try {
File fourLetterWords = new File(System.getProperty("user.home"),"Documents/FourLetterWords.txt");
Scanner in = new Scanner(fourLetterWords);
while (in.hasNextLine()) {
String line = in.nextLine();
if (line!=null && !line.isEmpty()) {
wordsList.add(line);
}
}
}
catch (FileNotFoundException ex) {
System.out.println("File not found.");
}
return wordsList ;
}
}
public static class PlayerCharacterEntry {
private String playerEntry() {
Scanner characterEntry = new Scanner(System.in);
System.out.print("Enter a character: ");
String playerInput = characterEntry.next();
playerInput = playerInput.toUpperCase();
return playerInput;
}
}
public static void main(String[] args) {
Scanner wantToPlay = new Scanner(System.in);
System.out.print("Welcome to the word guessing game! Would you like to play? ");
String playerAnswer = wantToPlay.next();
if (playerAnswer.equalsIgnoreCase("Yes")) {
System.out.print("\nYour objective is to guess a four letter word by entering"
+ "\nletters on your keyboard. If you can not guess the word in seven attempts,"
+ "\nyou lose! You will be told if the letter you entered is in the word, and"
+ "\nyou will be told if the letter you entered is not in the word. You will be"
+ "\nallowed to guess the word any time during your seven attempts. If at anytime"
+ "\nyou would like to terminate the game, enter the word 'terminate'. Good Luck!"
+ "\n \n");
}
if (playerAnswer.equalsIgnoreCase("No")) {
System.out.print("Maybe another time!");
System.exit(0);
}
RandomWordProvider randomWordProvider = new RandomWordProvider();
PlayerCharacterEntry playerCharacterEntry = new PlayerCharacterEntry();
randomWordProvider.getWord();
playerCharacterEntry.playerEntry();
if (randomWord.containsIgnoreCase(playerInput)){
}
}
}
Here at the bottom I am trying to access randomWord and playerInput from my other classes but I don't know how to do that. I am still fairly new to programming so I don't know how to do everything yet. Would I do a get and set method for each variable? I have tried doing that and I'm having a lot of trouble with that. If someone could show me how to access variables across classes it would be greatly appreciated!
Here's a slightly simplified example where the RandomWordProvider and PlayerCharacterEntry classes are NOT nested inside WordGuessingGame2.
I show only the methods I needed to modify:
class RandomWordProvider {
String getWord() {
int randomPosition = randomInteger();
String randomWord = words.get(randomPosition);
return randomWord;
}
// ...
}
class PlayerCharacterEntry {
String playerEntry() {
Scanner characterEntry = new Scanner(System.in);
System.out.print("Enter a character: ");
String playerInput = characterEntry.next();
playerInput = playerInput.toUpperCase();
return playerInput;
}
}
class WordGuessingGame2 {
public static void main(String[] args) {
// ...
RandomWordProvider randomWordProvider = new RandomWordProvider();
PlayerCharacterEntry playerCharacterEntry = new PlayerCharacterEntry();
randomWordProvider.getWord();
playerCharacterEntry.playerEntry();
}
}
Notice that I dropped the private modifier from the getWord and playerEntry methods,
otherwise they are not accessible from WordGuessingGame2.
It's good to start with the strictest possible modifiers,
and then reduce the restrictions as necessary.
No, private variables are only accessable from within the class it self. It's highly recommended that you create public getters and setters to maintain the OO principle of encapsulation.

In java, how do I store each scanner input in a 'for' loop to another method?

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.

How can I unit test user input in java

I am trying to understand how can I test a user's input (please note I am not trying to do a mock test but a test of actual user's input)
Currently as you may see in my program I have hard coded the values for my test case and it is passing all tests but how can I get a user's input and test it .
Is there a way where I can call System.in my constructor and pass it when I create an instance of MyClass1 in the test class?
Please, if possible give me some example code so I can better understand.
If I have a interface as such
public interface IMyClass{
public int getvalue1();
public int getvalue2();
public int getvalue3();
}
and then interface implementation as such
public class MyClass1 implements MyClass{
private int _value1 = 0;
private int _value2 = 0;
private int _value3 = 0;
public MyClass1(int number1, int number2, int number3)
{
_value1 = number1;
_value2 = number2;
_value3 = number3;
}
public void setLength1(int value1)
{
_value1 = value1;
}
public void setLength2(int length2)
{
_value2 = value2;
}
public void setLength3(int length3)
{
_value3 = value3;
}
public int getValue1()
{
return _value1;
}
public int getValue2()
{
return _value2;
}
public int getValue3()
{
return _value3;
}
}
and finally a test class as such:
public class ClasTest extends TestCase {
public void testNumbers()
{
MyClass1 numbers= new MyClass1(1,2,3);
assertThat(numbers.getValue1(),is(not(numbers.getValue2())));
}
}
Thankyou, I appreciate any help.
Use System.setIn(new InputSteam()); and then write to the input stream passed in to System.in
see: JUnit: How to simulate System.in testing?
Single Input
String data = "Users Input";
System.setIn(new ByteArrayInputStream(data.getBytes()));
Scanner scanner = new Scanner(System.in);
System.out.println(scanner.nextLine());
Result
Users Input
Multiple Inputs
String data = "Users Input" +
"\nA second line of user input.";
System.setIn(new ByteArrayInputStream(data.getBytes()));
Scanner scanner = new Scanner(System.in);
System.out.println("Line 1: " + scanner.nextLine());
System.out.println("Line 2: " + scanner.nextLine());
Result
Line 1: Users Input
Line 2: A second line of user input.
If on unix
java MyProgram < sampleinput.txt
user Scanner class
public void testNumbers()
{
Scanner scan = new Scanner(System.in);
System.out.println("value1");
int value1 = scan.nextInt();
System.out.println("value2");
int value2 = scan.nextInt();
System.out.println("value3");
int value3 = scan.nextInt();
MyClass1 numbers= new MyClass1(value1, value2, value3);
assertThat(numbers.getValue1(),is(not(numbers.getValue2())));
}

Categories

Resources