This is a java assignment containing 3 class files. The problem is when I call the "doOperations" method in main. The if statements read the file correctly, but the object methods dont work(e.g. tv.on, tv.volumeUp tv.setChannel(scan.nextInt(), etc.)).
Can anyone see where I am going wrong? Thanks.
TV class file.
import java.io.*;
import java.util.Scanner;
public class TV {
boolean on;
boolean subscribe;
int currentchannel;
int indexChan;
int volume;
File chanList;
Scanner chanScan;
TVChannel[] channels;
final int MaxChannel = 100;
public TV(){
on = false;
currentchannel = 1;
volume = 1;
channels = new TVChannel[MaxChannel]; //Create object of an array, default value = null.
subscribe = false;
}
public void turnOn(){
on = true;
}
public void turnOff(){
on = false;
}
public void channelUp(){
currentchannel++;
}
public void channelDown(){
currentchannel--;
}
public void volumeUp(){
volume++;
}
public void volumeDown(){
volume--;
}
public TVChannel getChannel(){
return channels[currentchannel];
}
public void setChannel(int c){
if(channels[c]!= null)
currentchannel = c;
}
public boolean subscribe(String provider) throws IOException{
chanList = new File(provider);
chanScan = new Scanner(chanList);
if(chanList.exists()){
while(chanScan.hasNext()){
indexChan = chanScan.nextInt();
channels[indexChan] = new TVChannel(indexChan, chanScan.nextLine());
}
chanScan.close();
return true;
}
else return false;
}
public void printAll(){
for(int i = 0; i < MaxChannel; i++){
if(channels[i]!= null)
System.out.println(channels[i].channelNumber+"\t"+channels[i].channelName);
}
}
public void displayChannel(int c){
if(channels[c]!= null)
System.out.println(channels[c].getChannel()+"\t"+channels[c].getName());
}
public void displayCurrentChannel(){
if(channels[currentchannel] != null)
System.out.println(channels[currentchannel].getChannel() +" "+ channels[currentchannel].getName());
}
}
Main function
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class TestTV {
public static void main(String[] args) throws IOException{
TV tv = new TV();
tv.subscribe("chan.txt");
if(tv.subscribe = true){
tv.printAll();
doOperations("operations.txt", tv);
}
}
//Static means only one instance of object.
public static void doOperations(String opFileName, TV tv) throws IOException{
File op = new File(opFileName);
Scanner scan = new Scanner(op);
String opa = scan.next();
while(scan.hasNext()){
System.out.println(scan.next());
if(opa.equals("on")) tv.turnOn();
else if(opa.equals("off")) tv.turnOff();
else if(opa.equals("channelUp")) tv.channelUp();
else if(opa.equals("channelDown")) tv.channelDown();
else if(opa.equals("volumeUp")) tv.volumeUp();
else if(opa.equals("volumeDown")) tv.volumeDown();
else if(opa.equals("showChannel")) tv.displayCurrentChannel();
else if(opa.equals("setChannel"))tv.setChannel(scan.nextInt()); //Error
}
scan.close();
}
}
You forgot to put this
String opa = scan.next(); inside of while loop. You need to store the result of course, on each token.
while(scan.hasNext()){
opa = scan.next();
System.out.println(opa); //don't just call scan.next()
//and discard the result. Unless that's really what you want?
.....
}
Nothing wrong with your code.
make sure your operation.txt looks like this
showChannel
setChannel 2
Note:since you are scan.next(); before the while loop and again in the loop as System.out.println(scan.next());
you are going to ignore the first line of the operation.txt and you would see it set the channel correctly.
Suggestion:
Change it as
String opa= "";// = scan.next();
while(scan.hasNext()){
System.out.println(scan.next());
Related
The scanner is created in one of the constructors but my if-statement isn't working as i intended
private boolean inputStreamExists = false;
public KeyboardScanner(InputStream inputStream) {
if (!inputStreamExists) {
scanner = new Scanner(inputStream);
inputStreamExists = true;
} else {
throw new IllegalArgumentException("Scanner already exists.");
}
}
This is the constructor I'm reffering to.
I did try making the "inputStreamExists" variable static. But in the provided test program that seemed to make my problems even worse by not letting it create even a single instance of the scanner.
This is my full scanner class:
import java.util.Scanner;
import java.io.InputStream;
public class KeyboardScanner {
private Scanner scanner;
private boolean inputStreamExists = false;
public KeyboardScanner(InputStream inputStream) {
if (!inputStreamExists) {
scanner = new Scanner(inputStream);
inputStreamExists = true;
} else {
throw new IllegalArgumentException("Scanner already exists.");
}
}
public KeyboardScanner() {
this(System.in);
}
public int setInt(String ledtext) {
System.out.print(ledtext + " ?>");
int a = scanner.nextInt();
scanner.nextLine();
return a;
}
public double setDouble(String ledtext) {
System.out.print(ledtext + " ?>");
double b = scanner.nextDouble();
scanner.nextLine();
return b;
}
public String setString(String ledtext) {
System.out.print(ledtext + " ?>");
String s = scanner.nextLine();
return s;
}
}
Any help appreciated since I'm new to programming!
So I have to read a file name that is read from the terminal.The user has to be able to search for a word and then look through a list of words that have those same characters. I plan to use the goToNext and getCurrent to read and scan through the list. But i dont know how to scan through the list i previously made in the method loadDataBase
public class GameLL <T>{
private class ListNode{
T data;
ListNode link;
public ListNode(T aData, ListNode aLink){
data = aData;
link = aLink;
}
}
public static GameLL<String> list = new GameLL<String>();
private ListNode head;
private ListNode current;
private ListNode previous;
public Object getCurrent;
public GameLL() {
head = current = previous = null;
}
public void add(T aData){
ListNode newNode = new ListNode(aData, null);
if(head == null){
head = current = newNode;
return;
}
ListNode temp = head;
while (temp.link != null){
temp = temp.link;
}
temp.link = newNode;
}
public void print(){
ListNode temp = head;
while(temp != null){
System.out.println(temp.data);
temp = temp.link;
}
}
public T getCurrent(){
if (current == null){
return null;
}
return current.data;
}
public void reset(){
current = head;
previous = null;
}
public void gotoNext(){
if(current == null){
return;
}
previous = current;
current = current.link;
}
}
Below is my methods that will be called in the main method. Im struggling here! Im not crazy at coding so my code might look like dog poop sorry
package Homework02.src;
import java.util.Scanner;
import java.io.*;
public class OtherMethods {
public static void options() throws IOException{
while (loopStatus.loopRunning){
System.out.println("Enter 1 to load the video game database");
System.out.println("Enter 2 to search the database");
System.out.println("Enter 3 to print current results");
System.out.println("Enter 4 to print current results to file");
System.out.println("Enter 0 to quit");
otherMethods.userOptionCheck();
}
}
public static class LoopStatus{
public static boolean loopRunning;
}
public static class UserInput{
public static int menuChoice;
public static String filePath;
}
public static class Counter{
public static int numOfLines = 0;
}
private static class Game{
private static String contentOnLine;
private static String name;
private static String console;
}
public static void userOptionCheck() throws IOException {
Scanner keyboard = new Scanner(System.in);
UserInput.menuChoice = keyboard.nextInt();
switch (UserInput.menuChoice) {
case 1:
otherMethods.loadDataBase();
System.out.println("\nDone Loading Data Base\n");
break;
case 2:
otherMethods.searchDataBase();
break;
case 3:
// TODO call method to print out the current results
break;
case 4:
// TODO call method to print current results to file
break;
case 0:
loopStatus.loopRunning = false;
break;
default:
System.out.println("You choose an invalid option... Please choose one of the five options listed.\n");
break;
}
}
public static void loadDataBase() throws IOException {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please specify either the relative file path or the absolute filepath: ");
UserInput.filePath = keyboard.nextLine();
GameLL<String> list = new GameLL<String>();
try {
File inputList = new File(UserInput.filePath);
Scanner fileReader = new Scanner(new FileInputStream(inputList));
while (fileReader.hasNextLine()) {
counter.numOfLines++;
Game.contentOnLine = fileReader.nextLine();
list.add(Game.contentOnLine);
}
fileReader.close();
} catch (FileNotFoundException fnf) {
System.out.println("\nhey i cant find the file\n");
fnf.printStackTrace();
}catch (Exception e) {
System.out.println("\nProgram is now exiting\n");
e.printStackTrace();
}
}
public static void searchDataBase(){
GameLL<String> searchResults = new GameLL<String>();
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the name of game or * for all names");
Game.name = keyboard.nextLine().toLowerCase();
System.out.println("Enter the name of the console or * for all consoles");
Game.console = keyboard.nextLine().toLowerCase();
int found = 0;
System.out.println();
for (int i = 0; i < counter.numOfLines;i++){
//THIS DOESNT WORK BECAUSE I CANT REFERENCE MY PREVIOUS "list" IN MY OTHER METHOD
if(list.getCurrent.toLowerCase().contains(Game.name)){
System.out.println("FOUND A WORD THAT CONTAINS PART OF THE NAME");
searchResults.add(list.getCurrent);
found++;
}
else{
System.out.println("Could not find a word on this line");
}
list.gotoNext;
searchResults.gotoNext();
}
System.out.println(found);
}
}
Here is currently my main method!
import Homework02.src.otherMethods.loopStatus;
import java.io.*;
public class FrontEndGameSearch {
public static void main(String[] args) throws IOException {
System.out.println("Welcome to the video game database\n");
loopStatus.loopRunning = true;
while (loopStatus.loopRunning){
otherMethods.options();
}
System.out.println("YOU ARE OUTSIDE THE LOOP");
}
}
My file works the way I want, except for one issue. After it runs prompt_log_out(), if I type n for no, my code does a System.out.print() of my get_temporary_user_credentials(). So the output looks like this:
Username: griffin.keyes
Password: alphabet soup
Hello, Zookeeper!
As zookeeper, you have access to all of the animals' information and their daily monitoring logs. This allows you to track their feeding habits, habitat conditions, and general welfare.
Would you like to log out? Please type "y" for Yes or "n" for No.
n
Username: Password: <---This is what I don't understand
Username: griffin.keyes
Password: alphabet soup
...
My desired output is the two lines below it that prompt for a username and password again. I feel like it may have something to do with my while(!logout) { statement, but I can't really think of why this might be the issue.
Here is my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.security.MessageDigest;
public class Authentication{
public static User temporary_user = new User();
public static File admin_file = new File("admin.txt");
public static File veterinarian_file = new File("veterinarian.txt");
public static File zookeeper_file = new File("zookeeper.txt");
public static int attempt_counter = 0;
public static boolean successful_login = false;
public static Scanner user_input = new Scanner(System.in);
public static boolean log_out = false;
public static void main(String []args) throws Exception{
while (!log_out) {
start_login();
if (successful_login) {
prompt_log_out();
}
}
}
public static void start_login() throws Exception {
User[] all_users = create_users();
attempt_counter = 0;
successful_login = false;
while (attempt_counter < 3 && !successful_login) {
get_temporary_user_credentials(user_input);
for (User u : all_users) {
if (temporary_user.username.equals(u.username)) {
if (temporary_user.encrypted_password.equals(u.encrypted_password)) {
print_file(u.role);
successful_login = true;
break;
}
}
}
attempt_counter++;
}
if (attempt_counter == 3 && !successful_login) {
//user_input.close();
log_out = true;
System.out.println(); //prints out a blank line for easier readability
System.out.println("You have made too many unsuccessful attempts. The program will now exit.");
}
}
public static void prompt_log_out(){
System.out.println(); //prints out a blank line for easier readability
System.out.println("Would you like to log out? Please type \"y\" for Yes or \"n\" for No.");
if ("y".equals(user_input.next())) {
log_out = true;
}
}
public static void get_temporary_user_credentials(Scanner user_input) throws Exception{
System.out.print("Username: ");
temporary_user.username = user_input.nextLine();
System.out.print("Password: ");
temporary_user.encrypted_password = encrypt(user_input.nextLine());
}
public static void check_credentials() {
}
public static String encrypt(String original) throws Exception {
StringBuffer sb = new StringBuffer();
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(original.getBytes());
byte[] digest = md.digest();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
return sb.toString();
}
public static User[] create_users() throws Exception{
User users[] = new User[6];
int index_counter = 0;
File credentials_file = new File("credentials.txt");
String pattern = "[^\"\\s]+|\"(\\\\.|[^\\\\\"])*\"";
Scanner file_reader = new Scanner(credentials_file);
while (file_reader.hasNextLine()) {
users[index_counter] = new User();
users[index_counter].username = file_reader.findInLine(pattern);
users[index_counter].encrypted_password = file_reader.findInLine(pattern);
users[index_counter].password = file_reader.findInLine(pattern);
users[index_counter].role = file_reader.findInLine(pattern);
if (file_reader.hasNextLine() == true) {
file_reader.nextLine();
}
index_counter++;
}
//file_reader.close();
return users;
}
public static void print_file(String role) throws Exception {
System.out.println(); //prints a blank line for easier readability.
if (role.equals("admin")) {
Scanner file_reader = new Scanner(admin_file);
while (file_reader.hasNextLine()) {
System.out.println(file_reader.nextLine());
}
}
else if (role.equals("veterinarian")) {
Scanner file_reader = new Scanner(veterinarian_file);
while (file_reader.hasNextLine()) {
System.out.println(file_reader.nextLine());
}
}
else {
Scanner file_reader = new Scanner(zookeeper_file);
while (file_reader.hasNextLine()) {
System.out.println(file_reader.nextLine());
}
}
}
}
class User {
String username;
String password;
String encrypted_password;
String role;
}
Any help would be greatly appreciated.
You have this method using the same Scanner Object "user_input", by call next(). The linebreak is still in the scanner buffer. Then the while loop back to start_login() if 'n' is enter. The linebreak is then consumed by temporary_user.username = user_input.nextLine();
public static void prompt_log_out(){
System.out.println(); //prints out a blank line for easier readability
System.out.println("Would you like to log out? Please type \"y\" for Yes or \"n\" for No.");
if ("y".equals(user_input.next())) {
log_out = true;
}
// A quick and dirty fix
user_input.nextLine()
}
attempt_counter = 0;
successful_login = false;
while (attempt_counter < 3 && !successful_login) {
Check the above condition its always true based on your declarations
Im fairly new to java and ive been doing som searching for an answer to my problem but i just cant seem to get the output from the arraylist.
I get a red mark under Ordtildikt String arrayoutput = kontrollObjekt.Ordtildikt;saying it cannot be resolved or is not a field. The program is supposed to get userinput and create an arraylist from the input
Interface class
import javax.swing.JOptionPane;
public class Grensesnitt {
public static void main(String[] args) {
Grensesnitt Grensesnitt = new Grensesnitt();
Grensesnitt.meny();
}
Kontroll kontrollObjekt = new Kontroll();
private final String[] ALTERNATIVER = {"Registrere ord","Skriv dikt","Avslutt"};
private final int REG = 0;
private final int SKRIV = 1;
public void meny() {
boolean fortsett = true;
while(fortsett) {
int valg = JOptionPane.showOptionDialog(
null,
"Gjør et valg:",
"Prosjektmeny",
JOptionPane.DEFAULT_OPTION,
JOptionPane.PLAIN_MESSAGE,
null,
ALTERNATIVER,
ALTERNATIVER[0]);
switch(valg) {
case REG: regNy();
break;
case SKRIV: regDikt();
break;
default: fortsett = false;
}
}
}
int i = 0;
public void regNy() {
while(i<=16)
{
String Ord = JOptionPane.showInputDialog("Skriv or til diktet: ");
kontrollObjekt.regNy(Ord);
//String Diktord = JOptionPane.showInputDialog("Skriv ord til diktet: ");
//kontrollObjekt.regNy(Diktord);
i = i + 1;
}
}
public void regDikt() {
String arrayoutput = kontrollObjekt.Ordtildikt;
JOptionPane.showMessageDialog(null, arrayoutput);
}
//JOptionPane.showMessageDialog(null, kontrollObjekt.Diktord);
}
Controll Class
import java.util.ArrayList;
public class Kontroll {
public ArrayList<String> Diktord = new ArrayList<String>();
public void regNy(String Ord) {
Diktord.add(Ord);
Diktord.add("\n");
}
public String Ordtildikt(String Ord) {
return Ord=Diktord.toString();
}
}
This is a method, not a variable.
kontrollObjekt.Ordtildikt;
You are trying to call this?
public String Ordtildikt(String Ord) {
return Ord=Diktord.toString();
}
1) Make it return Diktord.toString();
2) Get rid of String Ord unless you are going to use that parameter
3) Actually call the method, e.g. Put some parenthesis.
String arrayoutput = kontrollObjekt.Ordtildikt();
Also, I think this should be the correct regNy method unless you want to falsely report that the list is twice its size.
public void regNy(String Ord) {
Diktord.add(Ord + "\n");
}
In my program I am using a DoubleStreamto sum the values of an array.
I have the following code
Training P List
import java.io.*;
import java.util.*;
import java.lang.*;
import java.util.stream.DoubleStream;
public class TrainingPList
{
int aSize=500; // size of constant
TrainingP[] arrayTrainingP= new TrainingP[aSize]; // array name + aSize constant called to define size of the array
int nextPosition=0;// size of constant
double[] MoneyList;
public void readPersonal()
{
try
{
BufferedReader br=new BufferedReader(new FileReader("TrainingP.txt"));
String theNextPublicInfo = br.readLine();
nextPosition=0;
while (theNextPublicInfo !=null)
{
String[] arrayStringPersonalInfo = theNextPublicInfo.split(",");
TrainingP tempPInfo = new TrainingP();
tempPInfo.AthleteID = arrayStringPersonalInfo[0];
tempPInfo.rMoneyRaised = Double.parseDouble(arrayStringPersonalInfo[1]);
arrayTrainingP[nextPosition] = tempPInfo;
nextPosition++;
theNextPublicInfo = br.readLine();
}
}
catch(Exception e)
{
System.out.println("Invalid read data");
}
}
public void outputarrayTrainingP()
{
for(int i=0;i<nextPosition;i++)
{
System.out.println ("Position "+":"+arrayTrainingP[i]);
}
}
public void ListAth()
{
AthList = new String[nextPosition];
for(int i=0;i<nextPosition;i++)
{
AthList[i]=arrayTrainingP[i].AthleteID+"";
}
}
public void ListMoney()
{
MoneyList = new double[nextPosition];
for(int i=0;i<nextPosition;i++)
{
MoneyList[i]=arrayTrainingP[i].rMoneyRaised;
}
DoubleStream d = DoubleStream.of(MoneyList);
double dv = d.sum();
System.out.println("The sum is " + dv);
}
public static void main(String[] args)
{
TrainingPList tp = new TrainingPList();
tp.ListMoney();
tp.readPersonal();
tp.outputarrayTrainingP();
}
}
TrainingP
public class TrainingP
{
String AthleteID;
double rMoneyRaised;
public String toString()
{
return AthleteID+","+rMoneyRaised;
}
}
Document
DJ44,136.0
DB15,0.0
There are only two values for rMoneyRaised and they are 136.0 and 0.0. However it only returns 0.0 instead of the value 136.0. Does anyone know what the problem is?
There is a problem in the main method:
public static void main(String[] args)
{
TrainingPList tp = new TrainingPList();
tp.ListMoney();
tp.readPersonal();
tp.outputarrayTrainingP();
}
You should call tp.ListMoney() after reading in the data, not before.