Java How to programm Deitel Book exercise 6.35 - java

I've been studying Deitel's Book(Java how to program) and I want to solve exercise 6.35. Here's what it asks:
Write a program to assist a student to learn multiplication.Use a Random object to produce two positive integers (one digit each).
The program should show on screen something like this:("How much is 7 times 3")
Then the student should insert the answer and the program controls if the answer is correct or wrong.If it's correct the program continue asking another question,else the program waits until the student answer is correct.For every new question it must be a new method created(this method should be called once when the application starts and when the user answers correct to a question).
How do I do this?
//I have a problem inside the do-while block!
package multiplication;
import java.util.Random;
import java.util.Scanner;
/*Hey again! I've been trying to solve this problem using NetBeans environment
*
*/
public class Ypologismos
{
private int p;
private int a,b;
public Ypologismos(int a,int b,int p)
{
this.a=a;
this.b=b;
this.p=p;
}
public Ypologismos()
{
}
public void Screen()
{
System.out.println("Wrong answer ....please retry");
}
public void askForNumbers()
{
Random r=new Random();
int a,b;
a=r.nextInt(10);
b=r.nextInt(10);
int p;//p=product
p=(a*b);
System.out.println("How much is:"+" "+a+" "+"times"+" "+b+" "+"?");
System.out.println("Please insert your answer!");
Scanner s=new Scanner(System.in);
int ans;//ans=answer
ans=s.nextInt();
do
{
while(ans==p){
System.out.println("Well done!");
askForNumbers();
}
}while(ans!=p);
}
}
//and my main class ...
package multiplication;
public class Main
{
public static void main(String[] args)
{
Ypologismos application=new Ypologismos();
application.askForNumbers();
}
}

Make a terse story book of how to do it.
teach multiplication:
repeat // solving problems
int first number = something random
int second number = something random
int product = first number * second number
repeat
int answer = ask how much is first number times second number
if answer != product
say error!
until answer == product
say solved!
The above is just a first idea, not necessarily following the requirements. But it clears which loop comes in which loop and so on.
Reading your extended question
public class Ypologismos {
/** Entry point to the application. */
public static void main(String[] args) {
Ypologismos application = new Ypologismos();
application.teachMultiplication();
}
private void teachMultiplication() {
while (wantsAProblem()) {
askAProblem();
}
}
private void askAProblem() {
int αλφα = random.nextInt(10);
int βητα = random.nextInt(10);
...
}
}

Related

Java access Thread's class attributes

I'm building a console game in Java that works like this: It prints you an operation (e.g: 3 x 4) and you must write the result (12 in this case), and it will give you operations during a period of 1 minute and then it will finish.
I knew from the beginning I had to use threads to catch the user input, so this is the thread's logic:
public class UserInput extends Thread {
private int answer;
#Override
public void run() {
Scanner in = new Scanner(System.in);
while(true){
answer = in.nextInt();
}
}
public int getAnswer(){
return answer;
}
}
quite simple, now the game's logic:
public static void play() {
Game game = new EasyGame();
UserInput ui = new UserInput();
long beginTime = System.currentTimeMillis()/1000;
ui.start();
boolean accepted = true;
while(timeLeft(beginTime)){
//PrintChallenge() prints an operation and store its result in game
if(accepted) game.PrintChallenge();
accepted = false;
if(ui.getAnswer() == game.getResult()) accepted = true;
}
}
//returns if current time is 60 seconds after initial time
public static boolean timeLeft(long time){
return (System.currentTimeMillis()/1000) < (time + 60);
}
but it isn't working, it simply never matches ui's getAnswer() with game's getResult(). What am I doing wrong on this thread and game logics?
I think your problem is Java caching the value of your int locally, though it could be due to something in your game.getResult(), since I cannot check this. Thread safety is difficult in java.
To confirm:
I built a dumb version of the game, without any game logic or timer.
I added a volatile keyoword to your answer int, this makes Java check main memory rather than local cache for the value of the int.
The following code outputs once the user enters "30", removing the "volatile" keyoword in user input leads to your situation.
See below:
package stackOverflowTests;
import java.util.Scanner;
public class simpleGame {
public static class UserInput extends Thread {
volatile private int answer;
public void run() {
Scanner in = new Scanner(System.in);
while(true){
System.out.print("Answer meeee!:");
answer = in.nextInt();
}
}
public int getAnswer(){
return answer;
}
}
public static void play() throws InterruptedException {
UserInput testInput = new UserInput();
testInput.start();
while(true){
//PrintChallenge() prints an operation and store its result on game
Thread.sleep(10);
if(testInput.getAnswer()==30)System.out.println(testInput.getAnswer()+ " : "+(testInput.getAnswer()==10));
}
}
public static void main(String[] args) throws InterruptedException{
play();
}
}
private int answer;
This variable needs to be volatile, as you are reading and writing it from different threads. Or else you need to synchronize all access to it, both reads and writes.

Server/Client classes with two dimensional array (Java)

I am EXTREMELY new to Java and completely lost on the concept of ARRAYS. I need to create a "World" class to display a two dimensional array that is user specified in size, using a constructor that accepts two values [rows] and [columns] with a character (Lets say "P") located in the array. A separate "Driver" class will hold the main method. Other methods (moveUp, moveDown, moveLeft, and moveRight) need to be created to move the character around inside the array. There needs to be a fifth method to display the world array. I currently have the following code, but nothing is working so I got rid of it. even this code itself won't compile - says "identifier expected before the parenthesis of my second println. I have no idea why this won't go any further. This is the only place I have to seek help since the college offers no tutors for Java, youtube videos are extremely vague and use terminology I do not know, library books I've checked out don't show me the actual code needed to perform these tasks, and the class textbook shows code close, but not quite what is needed. and since I'm extremely new to Java, my last questions garnered me the threat of losing the ability to post on this site, so that would take away my only recourse for help if this is also dubbed inferior. I do not know what to do at this point.
import java.util.*;
public class World
{
public static void main(String[] args)
{
System.out.println(array);
}
Scanner input = new Scanner(System.in);
System.out.println("Enter number of row: ");
private int crow = input.nextInt();
System.out.println("Enter number of columns: ");
private int ccol = input.nextInt();
private String[][] array = newString[crow][ccol];
public int displayWorld()
{
}
public int moveUp()
{
}
public int moveDown()
{
}
public int moveLeft()
{
}
public int moveRight()
{
}
}
Compling problems-> use an IDE (eclipse netbeans idea jdeveloper ...) for developing java applications.
Here you have part of one solution, since you are learning, play with this code before implementing the rest of methods.
Regarding java learning, there are plenty of good tutorials by searching on google.
import java.util.*;
public class World{
private static final String P="P";
private String[][] array;
public World(){
Scanner input = new Scanner(System.in);
System.out.println("Enter number of row: ");
int crow = input.nextInt();
System.out.println("Enter number of columns: ");
int ccol = input.nextInt();
array = new String[crow][ccol];
array[0][0]=P;
}
public void displayWorld(){
System.out.println();
for(int i=0;i<array.length;i++){
for (int j=0;j<array[i].length;j++){
System.out.print(array[i][j]+" ");
}
System.out.println();
}
}
public void moveUp(){
}
public void moveDown(){
for(int i=0;i<array.length;i++){
for (int j=0;j<array[i].length;j++){
if ((array[i][j])!=null){
if (i<array.length-1){
array[i][j]=null;
array[i+1][j]=P;
}
return;
}
}
}
}
public void moveLeft(){
}
public void moveRight(){
}
public static void main(String[] args){
World world=new World();
world.displayWorld();
world.moveDown();
world.displayWorld();
}
}

How do i call a class in the main method java?

OK im kinda new in java and i made this averaging program in one class, but now if i want to like call it from another class, then how do i do it?I tryed some object stuff but its hard to understand for.
this is the code and i want this program to start when i call it.
package Gangsta;
import java.util.Scanner;
public class okidoki {
public static void main(String []args){
Scanner input = new Scanner(System.in);
double average, tests, grades, total = 0;
int cunter = 1, start = 0;
System.out.println("Press 2 to start averaging, or press 1 to end");
start = input.nextInt();
while (cunter<start){
System.out.println("Enter how many tests u have");
tests = input.nextDouble();
System.out.println("Enter tests grades");
int counter = 0;
while (counter<tests){
counter++;
grades = input.nextDouble();
total = grades+total;
}
average = total/tests;
System.out.println(average);
System.out.println("Press 3 to end or 1 to average again");
cunter = input.nextInt();}
}
}
this is the code where i want to execute it
package Gangsta;
public class tuna {
public static void main(String []args){
okidoki okidokiObject = new okidoki();
System.out.println(okidokiObject);
}
}
In java the main method is the main (it's in the name) entry point of a program. That said, there is only one main in your program. Nevertheless if you want to have your code wrapped in another class just do it:
public class MyClass {
public void myFancyMethod() {
Scanner input = new Scanner(System.in);
//....rest of
//....your code
counter = input.nextInt();
}
}
and access it like:
MyClass myClassObject = new MyClass();
myClassObject.myFancyMethod();
You should really start reading (or read them again) the fundamentals of object oriented programming languages, naming conventions etc, because this is something you should understand to make progress in programming.
Object-Oriented Programming Concepts in Java
For now, you can just do this in tuna.java to achieve what you want:
package Gangsta;
public class tuna {
public static void main(String []args){
okidoki okidokiObject = new okidoki();
okidokiObject.main()
}
}
System.out.println(okidokiObject) prints Gangsta.okidoki#659e0bfd because it is the hashcode of your object (Hashcode is something like an ID, See Object toString()). You usually do not want to print objects, but invoke their methods.
If you change your main method in okidoki class to constructor it will work exactly like you wish !
Example:
Example.java
public class Example {
public Example() {
System.out.println("Example class constructed");
}
}
Main.java
public class Main {
public static void main(String[] args) {
System.out.println("Program started.Constructing Example class");
Example exClass = new Example();
System.out.println("Program finished.");
}
}

Why can't I print a variable that is provided by user inside a loop?

I apologize if the answer to this question is so obvious I shouldn't even be posting this here but I've already looked up the error compiling the following code results in and found no explanation capable of penetrating my thick, uneducated skull.
What this program is meant to do is get 2 integers from the user and print them, but I have somehow managed to mess up doing just that.
import java.util.Scanner;
public class Exercise2
{
int integerone, integertwo; //putting ''static'' here doesn't solve the problem
static int number=1;
static Scanner kbinput = new Scanner(System.in);
public static void main(String [] args)
{
while (number<3){
System.out.println("Type in integer "+number+":");
if (number<2)
{
int integerone = kbinput.nextInt(); //the integer I can't access
}
number++;
}
int integertwo = kbinput.nextInt();
System.out.println(integerone); //how do I fix this line?
System.out.println(integertwo);
}
}
Explanation or a link to the right literature would be greatly appreciated.
EDIT: I want to use a loop here for the sake of exploring multiple ways of doing what this is meant to do.
Remove the int keyword when using the same variable for the second time. Because when you do that, it is essentially declaring another variable with the same name.
static int integerone, integertwo; // make them static to access in a static context
... // other code
while (number<3){
System.out.println("Type in integer "+number+":");
if (number<2)
{
integerone = kbinput.nextInt(); //no int keyword
}
number++;
}
integertwo = kbinput.nextInt(); // no int keyword
And it needs to be static as well since you're trying to access it in a static context (i.e) the main method.
The other option would be to declare it inside the main() method but before your loop starts so that it'll be accessible throughout the main method(as suggested by "Patricia Shanahan").
public static void main(String [] args) {
int integerone, integertwo; // declare them here without the static
... // rest of the code
}
How about:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kbinput = new Scanner(System.in);
System.out.println("Type in an integer: ");
int integerone = kbinput.nextInt();
System.out.println("Type another: ");
int integertwo = kbinput.nextInt();
System.out.println(integerone);
System.out.println(integertwo);
}
}

An array only allowing certain values 0-9 & A-F for Java

Full working now and code is complete Thanks for the help.
You can restrict user to enter another value by this: (This program is for if You are taking values from user). This will asks for number until you enter number within 0 to 9.
You can make your code according to this. (This is just for your reference, How can you restrict user to enter wrong thing)
Scanner scan=new Scanner(System.in);
int i=-1;
i=scan.nextInt();
while(i<=0 && i>=9){
i=scan.nextInt();
}
EDIT
As per your comment, In that case you need to change this as:
String s="";
while(!s.matches("^[0-9A-F]+$")){
s=scan.nextLine();
}
I would create a class to hold the RGB values and have it check that the correct values are entered. See the test code below.... you can expand as you need to handle more cases.
import java.util.*;
public class jtest
{
public static void main(String args[])
{
new jtest();
}
public jtest()
{
ArrayList<RGB> RGBarray = new ArrayList<RGB>();
try
{
RGBarray.add(new RGB("F"));
RGBarray.add(new RGB("J"));
}
catch(BadRGBValueException BRGBVE)
{
BRGBVE.printStackTrace();
}
}
class BadRGBValueException extends Exception
{
public BadRGBValueException(String message)
{
super(message);
}
}
class RGB
{
public RGB(String input) throws BadRGBValueException
{
if (!input.matches("^[0-9A-F]+$"))
{
throw new BadRGBValueException(input + " is not a valid RGB value");
}
value = input;
}
private String value = null;
}
}

Categories