• Welcome to TechPowerUp Forums, Guest! Please check out our forum guidelines for info related to our community.

Rhino's "I need Java help" thread

Easy Rhino

Linux Advocate
Staff member
Joined
Nov 13, 2006
Messages
15,449 (2.42/day)
Location
Mid-Atlantic
System Name Desktop
Processor i5 13600KF
Motherboard AsRock B760M Steel Legend Wifi
Cooling Noctua NH-U9S
Memory 4x 16 Gb Gskill S5 DDR5 @6000
Video Card(s) Gigabyte Gaming OC 6750 XT 12GB
Storage WD_BLACK 4TB SN850x
Display(s) Gigabye M32U
Case Corsair Carbide 400C
Audio Device(s) On Board
Power Supply EVGA Supernova 650 P2
Mouse MX Master 3s
Keyboard Logitech G915 Wireless Clicky
Software The Matrix
miss me?? :)

ok im taking an old program and converting it to an applet. the original program was the elementary math program where using JOptionPane the user receives a basic addition or subtraction question and then enters their answer and the program tells them if they are correct or incorrect.

so now im converting it to an applet that does the same thing but on a GUI. here is what i have so far. i need to figure out a way to retrieve the textfield input and see if it matches the actual answer.
(note: i dont think i should use a switch statement here but im still in the process of reworking code)

Code:
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class TeachArithmetic extends JApplet implements ActionListener
{
	private JPanel mathProblem = new JPanel();
	private JPanel enterAnswer = new JPanel();
	private JPanel gradeAnswer = new JPanel();
	private JPanel clickButton = new JPanel();
	private JPanel mainPanel = new JPanel();
	
	private JLabel problem;
	private JTextField userInput = new JTextField(5);
	private JLabel printResult;
	private JButton ok, next;
	
	public void init()
	{
		
		ok = new JButton("OK");
		ok.addActionListener(this);
		ok.setFont(new Font("Comic Sans MS", Font.BOLD,18));
		ok.setForeground(Color.blue);
		ok.setBackground(Color.white);
		
		next = new JButton("NEXT");
		next.addActionListener(this);
		next.setFont(new Font("Comic Sans MS", Font.BOLD,18));
		next.setForeground(Color.blue);
		next.setBackground(Color.white);
		
		mathProblem.setBackground(Color.white);
		mathProblem.setForeground(Color.green);
		mathProblem.add(problem);
		
		enterAnswer.setBackground(Color.white);
		enterAnswer.add(userInput);
		
		gradeAnswer.setBackground(Color.white);
		gradeAnswer.setFont(new Font("Comic Sans MS", Font.BOLD,20));
		gradeAnswer.setForeground(Color.red);
		gradeAnswer.add(printResult);
		
		clickButton.setBackground(Color.white);
		clickButton.add(ok);
		clickButton.add(next);	
		
		mainPanel.setBackground(Color.white);			
		mainPanel.setLayout(new GridLayout(5, 1));
		mainPanel.add(mathProblem);
		mainPanel.add(enterAnswer);
		mainPanel.add(gradeAnswer);
		mainPanel.add(clickButton);
		
		
		Container pane = getContentPane();
		pane.add(mainPanel);
		
	}
	
		public void actionPerformed(ActionEvent e)
		{
			
			if(e.getSource() == ok)
			{
				//check answer to see if it is correct
				//if correct then print correct
				//if incorrect then print incorrect
			}
			if(e.getSource() == next)
			{
				generateProblem(); //generate new math problem
				printResult.setText(""); //clear screen
				userInput.setText(""); //clear textfield
			}
		}
		
		public void generateProblem()
		{
			int num1 = randomNumber();
			int num2 = randomNumber();

			int user_answer = 0;
			int correct_answer = 0;
			boolean correct = false;
			
			switch(simple_math)
			{
				case 1: //addition
					user_answer = num1 + num2; 
					correct_answer = num1 + num2;
					if (user_answer == correct_answer)
					{
						correct = true;
					}
					else
					{
						correct = false;
					}
					break;
				case 2: //subtraction
					if (num1 < num2)// larger number is first
					{
						int num3 = num1;
						num2 = num1;
						num1 = num3;
					}
					user_answer = num1 - num2;
					correct_answer = num1 - num2;
					if (user_answer == correct_answer)
					{
						correct = true;
					}
					else
					{
						correct = false;
					}
					break;
			}
			if(correct)
			{
				printResult.setText("You got it right!");
			}
			else
			{
				printResult.setText("I'm sorry, but that is incorrect.");
			}
		}
		
		public int randomNumber()
		{
			return ((int) (Math.random() * 10));
		}
	
}
 

Easy Rhino

Linux Advocate
Staff member
Joined
Nov 13, 2006
Messages
15,449 (2.42/day)
Location
Mid-Atlantic
System Name Desktop
Processor i5 13600KF
Motherboard AsRock B760M Steel Legend Wifi
Cooling Noctua NH-U9S
Memory 4x 16 Gb Gskill S5 DDR5 @6000
Video Card(s) Gigabyte Gaming OC 6750 XT 12GB
Storage WD_BLACK 4TB SN850x
Display(s) Gigabye M32U
Case Corsair Carbide 400C
Audio Device(s) On Board
Power Supply EVGA Supernova 650 P2
Mouse MX Master 3s
Keyboard Logitech G915 Wireless Clicky
Software The Matrix
edit: solved! just had to run Integer.parseInt on userInput.getText() and it works like a charm.

ok, applet is almost done. i just need to figure out a way to get the number which is input into the textfield to be equal to my class variable user_answer. the problem is i cant grab that entered number and put it into a int variable.

this doesnt work

Code:
user_answer = userInput.getText(); //set what the user enters into the textfield as the user answer

Code:
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.Border;

public class TeachArithmetic extends JApplet implements ActionListener
{
	public int num1, num2, num3, num4;
	public int user_answer, correct_answer;
	
	private JPanel mathProblem = new JPanel();
	private JPanel enterAnswer = new JPanel();
	private JPanel gradeAnswer = new JPanel();
	private JPanel clickButton = new JPanel();
	private JPanel mainPanel = new JPanel();
	
	private JTextArea problem = new JTextArea(1, 3);
	private JTextField userInput = new JTextField(3);
	private JTextArea printResult = new JTextArea(1, 3);
	private JButton ok, next;
	private Border blueline1 = BorderFactory.createLineBorder(Color.blue);
	
	public void init()
	{
		
		ok = new JButton("OK");
		ok.addActionListener(this);
		ok.setFont(new Font("Comic Sans MS", Font.BOLD,25));
		ok.setForeground(Color.blue);
		ok.setBackground(Color.white);
		
		next = new JButton("NEXT");
		next.addActionListener(this);
		next.setFont(new Font("Comic Sans MS", Font.BOLD,25));
		next.setForeground(Color.blue);
		next.setBackground(Color.white);
		
		mathProblem.setBackground(Color.white);
		mathProblem.setForeground(Color.green);
		mathProblem.add(problem);
		
		enterAnswer.setBackground(Color.white);
		enterAnswer.add(userInput);
		userInput.setFont(new Font("Comic Sans MS", Font.BOLD,22));
		
		gradeAnswer.setBackground(Color.white);
		gradeAnswer.setFont(new Font("Comic Sans MS", Font.BOLD,22));
		gradeAnswer.setForeground(Color.red);
		gradeAnswer.add(printResult);
		
		clickButton.setBackground(Color.white);
		clickButton.add(ok);
		clickButton.add(next);	
		
		mainPanel.setBackground(Color.white);			
		mainPanel.setLayout(new GridLayout(5, 1));
		mainPanel.add(mathProblem);
		mainPanel.add(enterAnswer);
		mainPanel.add(gradeAnswer);
		mainPanel.add(clickButton);
		mainPanel.setBorder(blueline1);
		
		
		Container pane = getContentPane();
		pane.add(mainPanel);
		
		
	}
	
		public void actionPerformed(ActionEvent e)
		{
			
			if(e.getSource() == ok)
			{
				if(user_answer == correct_answer)
				{
					printResult.setText("You Got It Right!");
					printResult.setFont(new Font("Comic Sans MS", Font.BOLD,18));
					printResult.setForeground(Color.green);
				}
				else
				{
					printResult.setText("I'm Sorry But That Is Incorrect.");
					printResult.setFont(new Font("Comic Sans MS", Font.BOLD,18));
					printResult.setForeground(Color.red);
				}
			}
			if(e.getSource() == next)
			{
				randomNumber(); //generate random int
				displayProblem(); //generate new math problem
				printResult.setText(""); //clear screen
				userInput.setText(""); //clear textfield
			}
		}
		
		
		public void randomNumber()
		{
			num1 = (int) (Math.random() * 10);
			num2 = (int) (Math.random() * 10);
			num3 = (int) (Math.random() * 10);
			num4 = (int) (Math.random() * 10);
		}
		
		public void displayProblem()
		{
			problem.setText("Your Math Problem is: " + num1 + " + " + num2);
		    problem.setFont(new Font("Comic Sans MS", Font.BOLD,20));
		    problem.setForeground(Color.black);
		    user_answer = userInput.getText(); //set what the user enters into the textfield as the user answer
		    correct_answer = num1 + num2; //set the correct answer to whatever num1 + num2 equals. 
		}
	
}//end of class

edit: solved! just had to run Integer.parseInt on userInput.getText() and it works like a charm.
 
Last edited:

Easy Rhino

Linux Advocate
Staff member
Joined
Nov 13, 2006
Messages
15,449 (2.42/day)
Location
Mid-Atlantic
System Name Desktop
Processor i5 13600KF
Motherboard AsRock B760M Steel Legend Wifi
Cooling Noctua NH-U9S
Memory 4x 16 Gb Gskill S5 DDR5 @6000
Video Card(s) Gigabyte Gaming OC 6750 XT 12GB
Storage WD_BLACK 4TB SN850x
Display(s) Gigabye M32U
Case Corsair Carbide 400C
Audio Device(s) On Board
Power Supply EVGA Supernova 650 P2
Mouse MX Master 3s
Keyboard Logitech G915 Wireless Clicky
Software The Matrix
i'm working on a simple IO program that takes a text file and reads from it and then writes a new text file with some parameters i create using methods. the program works and creates the file but the text file is empty. it isnt actually writing anything to it. i cant for the life of me figure out why! here is my code

Code:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.StringTokenizer;


public class projectIO 
{	
	StringTokenizer tokenizer;
	BufferedReader inFile;
	PrintWriter outFile;	
	
	private String title, inputString;
	private int quantity;
	private double price;
	
	projectIO()
	{
		try
		{
			inFile = new BufferedReader(new FileReader("books.txt"));
			outFile = new PrintWriter(new FileWriter("report.txt"));
			write_report_heading();
			read_data();
			inFile.close();
			outFile.close();
			
		}
		catch(Exception e)
		{
			if(e instanceof FileNotFoundException)
			{
				System.out.println("FILENAME NOT FOUND");
				System.exit(1);
			}			
		}		
	}// end of projectIO constructor
	
	public void read_data() throws IOException
	{
		inputString = inFile.readLine();
		
		while(inputString != null)
		{
			tokenizer = new StringTokenizer(inputString, ",");
			title = tokenizer.nextToken();
			quantity = Integer.parseInt(tokenizer.nextToken());
			price = Double.parseDouble(tokenizer.nextToken());
			
			write_record();
			
			inputString = inFile.readLine();
		}// end of while loop
	}// end of read_data
	
	public void write_record() throws IOException
	{
		outFile.print(quantity);
		outFile.print(price);
		outFile.println(title);
	}
	
	public void write_report_heading() throws IOException
	{
		outFile.print("STOCK REPORT ON BOOKS");
		outFile.println();
		outFile.print("Quantity \t\t Price \t\t Title\n");
		outFile.println();
		
	}
	
	public static void main(String[] args)
	{
		new projectIO();
	}
}// end of class
 

FordGT90Concept

"I go fast!1!11!1!"
Joined
Oct 13, 2008
Messages
26,259 (4.63/day)
Location
IA, USA
System Name BY-2021
Processor AMD Ryzen 7 5800X (65w eco profile)
Motherboard MSI B550 Gaming Plus
Cooling Scythe Mugen (rev 5)
Memory 2 x Kingston HyperX DDR4-3200 32 GiB
Video Card(s) AMD Radeon RX 7900 XT
Storage Samsung 980 Pro, Seagate Exos X20 TB 7200 RPM
Display(s) Nixeus NX-EDG274K (3840x2160@144 DP) + Samsung SyncMaster 906BW (1440x900@60 HDMI-DVI)
Case Coolermaster HAF 932 w/ USB 3.0 5.25" bay + USB 3.2 (A+C) 3.5" bay
Audio Device(s) Realtek ALC1150, Micca OriGen+
Power Supply Enermax Platimax 850w
Mouse Nixeus REVEL-X
Keyboard Tesoro Excalibur
Software Windows 10 Home 64-bit
Benchmark Scores Faster than the tortoise; slower than the hare.

Easy Rhino

Linux Advocate
Staff member
Joined
Nov 13, 2006
Messages
15,449 (2.42/day)
Location
Mid-Atlantic
System Name Desktop
Processor i5 13600KF
Motherboard AsRock B760M Steel Legend Wifi
Cooling Noctua NH-U9S
Memory 4x 16 Gb Gskill S5 DDR5 @6000
Video Card(s) Gigabyte Gaming OC 6750 XT 12GB
Storage WD_BLACK 4TB SN850x
Display(s) Gigabye M32U
Case Corsair Carbide 400C
Audio Device(s) On Board
Power Supply EVGA Supernova 650 P2
Mouse MX Master 3s
Keyboard Logitech G915 Wireless Clicky
Software The Matrix
ah i see, but we the program isnt that detailed for those needs. i was given an example file and it worked fine but my program seems to be missing something.
 

FordGT90Concept

"I go fast!1!11!1!"
Joined
Oct 13, 2008
Messages
26,259 (4.63/day)
Location
IA, USA
System Name BY-2021
Processor AMD Ryzen 7 5800X (65w eco profile)
Motherboard MSI B550 Gaming Plus
Cooling Scythe Mugen (rev 5)
Memory 2 x Kingston HyperX DDR4-3200 32 GiB
Video Card(s) AMD Radeon RX 7900 XT
Storage Samsung 980 Pro, Seagate Exos X20 TB 7200 RPM
Display(s) Nixeus NX-EDG274K (3840x2160@144 DP) + Samsung SyncMaster 906BW (1440x900@60 HDMI-DVI)
Case Coolermaster HAF 932 w/ USB 3.0 5.25" bay + USB 3.2 (A+C) 3.5" bay
Audio Device(s) Realtek ALC1150, Micca OriGen+
Power Supply Enermax Platimax 850w
Mouse Nixeus REVEL-X
Keyboard Tesoro Excalibur
Software Windows 10 Home 64-bit
Benchmark Scores Faster than the tortoise; slower than the hare.
Did you add flushes? It doesn't look like much data so just do outFile.flush() before outfile.close().


Also, make sure it isn't throwing an exception.
 

Easy Rhino

Linux Advocate
Staff member
Joined
Nov 13, 2006
Messages
15,449 (2.42/day)
Location
Mid-Atlantic
System Name Desktop
Processor i5 13600KF
Motherboard AsRock B760M Steel Legend Wifi
Cooling Noctua NH-U9S
Memory 4x 16 Gb Gskill S5 DDR5 @6000
Video Card(s) Gigabyte Gaming OC 6750 XT 12GB
Storage WD_BLACK 4TB SN850x
Display(s) Gigabye M32U
Case Corsair Carbide 400C
Audio Device(s) On Board
Power Supply EVGA Supernova 650 P2
Mouse MX Master 3s
Keyboard Logitech G915 Wireless Clicky
Software The Matrix
Did you add flushes? It doesn't look like much data so just do outFile.flush() before outfile.close().


Also, make sure it isn't throwing an exception.

yea the flush didnt work. im going to email my prof about this. perhaps it is an issue with the text file he supplied us because this is supposed to be a fairly straight forward exercise.
 

Easy Rhino

Linux Advocate
Staff member
Joined
Nov 13, 2006
Messages
15,449 (2.42/day)
Location
Mid-Atlantic
System Name Desktop
Processor i5 13600KF
Motherboard AsRock B760M Steel Legend Wifi
Cooling Noctua NH-U9S
Memory 4x 16 Gb Gskill S5 DDR5 @6000
Video Card(s) Gigabyte Gaming OC 6750 XT 12GB
Storage WD_BLACK 4TB SN850x
Display(s) Gigabye M32U
Case Corsair Carbide 400C
Audio Device(s) On Board
Power Supply EVGA Supernova 650 P2
Mouse MX Master 3s
Keyboard Logitech G915 Wireless Clicky
Software The Matrix
ok apparently im dumb because it wasnt working for the most obvious reason. i had the variables out of order between read_data and write_record. anyway it is outputting the data and i got the formatting worked out.

now the last part of the problem is to get it to total the amount of books in stock and total the value of the books in stock . i can easily get the quantity and the value of one book but i cant seem to get the program to hold the quantity over while the loop continues and then add the second book quantity onto the first.

Code:
import java.io.*;
import java.util.*;


public class projectIO 
{	
	StringTokenizer tokenizer;
	BufferedReader inFile;
	PrintWriter outFile;	
	
	private String title, inputString;
	private int quantity, bookStock;
	private double price, value;
	
	projectIO()
	{
		try
		{
			inFile = new BufferedReader(new FileReader("books.txt"));
			outFile = new PrintWriter(new FileWriter("report.txt"));
			write_report_header();
			read_data();
			write_report_footer();
			inFile.close();
			outFile.close();
			
		}
		catch(Exception e)
		{
			if(e instanceof FileNotFoundException)
			{
				System.out.println("FILENAME NOT FOUND");
				System.exit(1);
			}			
		}		
	}// end of projectIO constructor
	
	public void read_data() throws IOException
	{
		inputString = inFile.readLine();
		
		while(inputString != null)
		{
			tokenizer = new StringTokenizer(inputString, ",");
			quantity = Integer.parseInt(tokenizer.nextToken());
			price = Double.parseDouble(tokenizer.nextToken());
			title = tokenizer.nextToken();
			
			write_record();
			
			inputString = inFile.readLine();
		}// end of while loop
	}// end of read_data
	
	public void write_record() throws IOException
	{
		if(quantity <= 1)
		{
			outFile.print("*** REORDER ***   \t" + quantity + "\t");
		}
		else
		{
			outFile.print("\t\t\t\t\t" + quantity + "\t");
		}
		outFile.print("\t\t  $" + price + "\t");
		outFile.println("\t" + title);
	}
	
	public void write_report_header() throws IOException
	{
		outFile.print("\t\t\t\t\t\tSTOCK REPORT ON BOOKS");
		outFile.println();
		outFile.println();
		outFile.print("\t\t\t\t\tQuantity \t  Price \t Title\n");
		outFile.println();
	}
	
	public void write_report_footer() throws IOException
	{
		outFile.println();
		outFile.print("Number of books in stock " + bookStock);
		outFile.println();
		outFile.println();
		outFile.print("Retail value of books in stock $" + value);
	}
	
	public static void main(String[] args)
	{
		new projectIO();
	}
}// end of class
 

Easy Rhino

Linux Advocate
Staff member
Joined
Nov 13, 2006
Messages
15,449 (2.42/day)
Location
Mid-Atlantic
System Name Desktop
Processor i5 13600KF
Motherboard AsRock B760M Steel Legend Wifi
Cooling Noctua NH-U9S
Memory 4x 16 Gb Gskill S5 DDR5 @6000
Video Card(s) Gigabyte Gaming OC 6750 XT 12GB
Storage WD_BLACK 4TB SN850x
Display(s) Gigabye M32U
Case Corsair Carbide 400C
Audio Device(s) On Board
Power Supply EVGA Supernova 650 P2
Mouse MX Master 3s
Keyboard Logitech G915 Wireless Clicky
Software The Matrix
ok i figured it out. actually quite easy just had to remember that in a loop i can use the += operator to get the value to add itself onto another variable. so in my case i just did

Code:
bookStock += quantity;

and it adds the amount of each title up and stores it.

now to figure out value which is a bit trickier since it has to multiply the number of books by the price.

edit: lol nevermind it was easy. man i am getting tired.
 
Last edited:
Top