my output of my java application is running null values for the output of Q4 and 5, tried fixing it but had no luck swapping out the null values for the actual string question needed to be shown just before the user input
MultipleChoiceQuestions.java
import java.util.Arrays;
import java.util.Scanner;
public class MultipleChoiceQuestion extends Question{
private int count = 0 ;
private String cho1, cho2, cho3, cho4 ;
private boolean bool1, bool2, bool3, bool4 ;
private final String[] newchoice = new String[4];
public MultipleChoiceQuestion(String text, String cho1, boolean bool1,
String cho2, boolean bool2,
String cho3, boolean bool3,
String cho4, boolean bool4) {
super(text);
this.cho1 = cho1; this.cho2 = cho2;
this.cho3 = cho3; this.cho4 = cho4;
this.bool1 = bool1; this.bool2 = bool2;
this.bool3 = bool3; this.bool4 = bool4;
}
public void addChoice(String Choices, boolean isCorrect){
this.newchoice[count]= Choices;
if(isCorrect) {
super.setCorrectResponse(Choices);
}
count++ ;
}
public void initQuestion(){
addChoices(cho1, bool1);
addChoices(cho2, bool2);
addChoices(cho3, bool3);
addChoices(cho4, bool4);
}
#Override
public String toString(){
StringBuilder sbf = new StringBuilder(super.toString());
sbf.append(Arrays.toString(newchoice));
return sbf.toString();
}
private void addChoices(String cho1, boolean bool1) {
throw new UnsupportedOperationException("Not supported yet."); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody
}
}
FillInTheBlankQuestion.java
import java.util.Scanner;
public class FillInTheBlankQuestion extends Question{
public FillInTheBlankQuestion(String text){
super(text);
}
public void extractQA(){
Scanner scan = new Scanner(super.getQuestionText());
scan.useDelimiter("_");
super.setQuestionText(scan.next());
super.setCorrectResponse(scan.next());
}
public String toString(){
return super.toString() + "______________";
}
}
Question.java
import java.util.Scanner;
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
/**
*
* #author --
*/
public class Question {
private String questionText;
private String correctResponse;
//Creates a question with an empty question and answer
public Question(){
this.setQuestionText("");
this.setCorrectResponse("");
}
public Question(String text){
this.setQuestionText(text);
}
public Question(String text, String answer){
this.setQuestionText(text);
this.setCorrectResponse(answer);
}
//sets the text of this question
public void setQuestionText(String text){
this.questionText = text;
}
//sets the answer for this question
public void setCorrectResponse(String answer){
this.correctResponse = answer;
}
public String getQuestionText(){
return this.questionText;
}
public String getCorrectResponse(){
return this.correctResponse;
}
/*
checks the response/answer given for correctness
#param givenResponse The response to check
return true if the response is correct, false otherwise
*/
public boolean verifyAnswer(String givenResponse){
//it does not take into account upper/lower case characters.
return givenResponse.equalsIgnoreCase(this.getCorrectResponse());
}
//allows user to type the answer
public void inputAnswer(Scanner scan){
System.out.print("Type your answer:");
System.out.println(this.verifyAnswer(scan.nextLine()));
}
//display the question
#Override
public String toString(){
return this.getQuestionText();
}
}
QuestionTester.java
import java.util.Scanner;
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Main.java to edit this template
*/
/**
*
* #author ---
*/
public class QuizTester {
public QuizTester(){
Scanner in = new Scanner(System.in);
//declare an array quiz that can hold a mixture of Question and Fill in blank type
Question[] quiz = new Question[6];
quiz[0] = new Question("Which class is used to get user input?", "Scanner");
quiz[1] = new Question("How many primitive data types are there in Java? Enter in words.", "eight");
quiz[2] = new FillInTheBlankQuestion("The inventor of Java was _James Gosling_");
quiz[3] = new FillInTheBlankQuestion("Every class in Java inherits from _Object_");
quiz[4] = new MultipleChoiceQuestion("What represents the collection of related data?",
"String", false,"Array", true, "Integer", false,
"Iterator", false);
quiz[5] = new MultipleChoiceQuestion("Which method does not belong to Scanner class?",
"nextInt()", false,
"next()", false,
"nextboolean()", false,
"nextChar()", true);
for(int i = 0; i < quiz.length; i++){
if(quiz[i] instanceof FillInTheBlankQuestion){
((FillInTheBlankQuestion)quiz[i]).extractQA();
}
System.out.println("Q" + (i + 1) + ": " + quiz[i].toString());
quiz[i].inputAnswer(in);
}
}
public static void main(String[] args) {
new QuizTester();
}
}
I thank you so much in advance
Related
Newbie here I am trying to compare the brand and display to an array of Strings. Seems to be working now but I don't know how to make the comparison case-insensitive. All the options I found so far is to compare a string to another string. There is any way I can make that comparison? Right now only accept the values as stated in the array of strings.
P.S. This was an existing homework that our instructor wanted us to build on it, hence why I am using the "isValid" methods for validation.
Thanks!
import com.entertainment.Television;
import java.util.Arrays;
import java.util.Scanner;
class TelevisionConsoleClient {
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
welcomeMessage();
}
public static void welcomeMessage() {
//Welcome message to buyer
System.out.println("Welcome to Our Online Ordering System.");
System.out.println("Please answer the questions below to submit your order.");
String brand = brandChoice();
String display = displayChoice();
int size = sizeChoice();
System.out.println("Thank you. The television you ordered is: ");
television(brand, display, size);
//close scanner
scanner.close();
}
public static String brandChoice() {
String brandChoice = null;
boolean hasBrand = false;
while (!hasBrand) {
System.out.println("Please enter the desired brand " + Arrays.toString(Television.VALID_BRANDS) + ":");
brandChoice = scanner.nextLine();
if (Television.isValidBrand(brandChoice))
hasBrand = true;
else
System.out.println("Sorry " + brandChoice + " is not a valid brand");
}
return brandChoice;
}
private static String displayChoice() {
String displayChoice = null;
boolean hasDisplay = false;
while (!hasDisplay) {
System.out.println("Please enter the desired display type " + Arrays.toString(Television.VALID_DISPLAY) + ":");
displayChoice = scanner.nextLine();
if (Television.isValidDisplay(displayChoice))
hasDisplay = true;
else
System.out.println("Sorry " + displayChoice + " is not a valid display type");
}
return displayChoice;
}
private static int sizeChoice() {
Integer sizeChoice = null;
boolean hasSize = false;
while (!hasSize) {
System.out.println("Please enter the desired size " + Arrays.toString(Television.VALID_SIZES) + ":");
sizeChoice = Integer.parseInt(scanner.nextLine());
if (Television.isValidSize(sizeChoice))
hasSize = true;
else
System.out.println("Sorry " + sizeChoice + " is not a valid size");
}
return sizeChoice;
}
private static void television(String brand, String display, int size) {
System.out.println(new Television(brand, display, size));
}
}
package com.entertainment;
public class Television {
// CLASS OR STATIC VARIABLES - STORED IN THE SHARED AREA ASSOCIATED WITH A CLASS
public static final String[] VALID_BRANDS = {"Samsung", "LG", "Sony", "Toshiba"};
public static final String[] VALID_DISPLAY = {"LED", "OLED", "PLASMA", "LCD", "CRT"};
public static final int[] VALID_SIZES = {32, 40, 43, 50, 55, 60, 65, 70, 75, 80};
// FIELDS - AKA 'INSTANCE VARIABLES', 'ATTRIBUTES', 'PROPERTIES'
private String brand;
private String display;
private int size;
// CONSTRUCTORS
// No-arg constructor.
public Television() {
// possible additional "setup" or initialization code here
// want it to run for every instance created
}
// 3-arg constructor
public Television(String brand, String display, int size) {
this.brand = brand;
this.display = display;
this.size = size;
}
// ACCESSOR METHODS (getters/setters)
public String getBrand() {
return brand;
}
public String getDisplay() {
return display;
}
public int getSize() { return size; }
public static boolean isValidBrand(String brand) {
boolean isValid = false;
for (String currentBrand : VALID_BRANDS) {
if (currentBrand.equals(brand)) {
isValid = true;
break;
}
}
return isValid;
}
public static boolean isValidDisplay(String display) {
boolean isValid = false;
for (String currentDisplay : VALID_DISPLAY) {
if (currentDisplay.equals(display)) {
isValid = true;
break;
}
}
return isValid;
}
public static boolean isValidSize(int size) {
boolean isValid = false;
for (int currentSize : VALID_SIZES) {
if (currentSize == size) {
isValid = true;
break;
}
}
return isValid;
}
public String toString() {
return "Television: " + getBrand() + ", Display: " + getDisplay() + ", Size: " + getSize() + " inches.";
}
}
Change String.equals(Object) to String.equalsIgnoreCase(String). That is,
if (currentBrand.equals(brand))
if (currentDisplay.equals(display))
to
if (currentBrand.equalsIgnoreCase(brand))
if (currentDisplay.equalsIgnoreCase(display))
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");
}
I am trying to remove errors in the following code.
package in.citydoor.imports.catalog.tools;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class Main {
/**
* #param args
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String file_name="C:/aman/textfile.txt";
try {
CatFeedWriterToMemory obj = new CatFeedWriterToMemory(file_name);
String[] arryLines = obj.ReadFile();
/*
* int i;
* for(i=0;i<arryLines.length;i++){
* System.out.println(arryLines[i]);
* }
*/
} catch(IOException e) {
System.out.println(e.getMessage());
System.out.println("Keep file on specified path");
}
}
}
package in.citydoor.imports.catalog.tools;
import java.util.ArrayList;
public class CatFeedBean {
ArrayList<ProductVo> parsedList = new ArrayList<ProductVo>();
ArrayList<PriceVo> priceList = new ArrayList<PriceVo>();
ArrayList<SkuVo> SkuList = new ArrayList<SkuVo>();
**String[] columns = arryLines.split("/");**
String productid = columns[0];
String productname = columns[1];
String skuid = columns[2];
String price = columns[3];
ProductVo productObj = new ProductVo(productid,productname);
**parsedList.add(productObj);**
SkuVo skuObj = new SkuVo(skuid);
// SkuList.add(skuObj);
PriceVo priceObj = new PriceVo(price);
// priceList.add(priceObj);
}
package in.citydoor.imports.catalog.tools;
public class ProductVo {
private String product_id;
private String product_name;
public ProductVo(String i, String n) {
product_id = i;
product_name = n;
}
public String getProductId() {
return this.product_id;
}
public void setProductId(String product_id) {
this.product_id = product_id;
}
public String getProductName() {
return this.product_name;
}
public void setProductname(String product_name){
this.product_name = product_name;
}
}
1) For the line String[] columns = arryLines.split("/"); in main class,
I am getting error "arryLines cannot be resolved".
2). For line parsedList.add(productObj);" in CatFeedBean class,
I am getting error "Syntax error on token"productObj",VariableDeclaratorId expected after this token".
Yes,
The arryLines is a local variable in your Main class.
The code is not in a method, it is in the declaration part of the
class.
You should call the add-method inside of a method or constructor.
like:
public CatFeedBean() {
parsedList.add(productObj);
}
see stackoverflow.com/questions/17499455
I have created an sql database with a table containing information about Airplanes, I want to be able to take this information and insert it into an ArrayList of type Aircraft(object) although the different info in the sql table are different primitive types........can this be done?`package uk.ac.qub.sqldbflights;
This is the Aircraft object with all the attributes which are the
public class Aircraft {
/**
* private String containing the airline name of the aircraft
* -Can't be blank
*/
private int aircraft_number;
/**
* private String containing the flight number belonging to the aircraft
* -Can't be blank
*/
private String airline_company;
/**
* private String containing the aircrafts city of origin
* -Can't be blank
*/
private String departure_airport;
/**
* private int which holds the aircrafts fuel level
* -Must be over 0 and less than 100
*/
private float passenger_number;
/**
* private int containing the number of passengers aboard the aircraft
* -Must be over 0 and less than 300
*/
private float fuel_percentage;
/**
* private Boolean indicting wether the aircraft is in the landing queue or not
*/
private int flight_time_remaining;
/**
* private Boolean indicating wether the aircraft is landed or not
*/
private boolean in_queue;
private boolean is_landed;
public Aircraft() {
}
/**
* Song creation
* #param name -not null
* #param artist -not null
* #param album -not null
* #param genre- not null and one of Pop, Dance, Rock
* #throws IllegalArgumentException
*/
public Aircraft(int aircraft_number, String airline_company, String departure_airport, int passenger_number, float fuel_percentage, int flight_time_remaining, boolean in_queue, boolean is_landed)
throws IllegalArgumentException {
try {
// set name
this.setAircraft_number(aircraft_number);
this.setAirline_company(airline_company);
this.setDeparture_airport(departure_airport);
this.setPassenger_number(passenger_number);
this.setFuel_percentage(fuel_percentage);
this.setFlight_time_remaining(flight_time_remaining);
this.setIn_queue(in_queue);
this.setIs_landed(is_landed);
} catch (IllegalArgumentException ex) {
System.out.println("Unable to create song due to arguments passed");
throw ex;
}}
public int getAircraft_number() {
return aircraft_number;
}
public void setAircraft_number(int aircraft_number) {
this.aircraft_number = aircraft_number;
}
public String getAirline_company() {
return airline_company;
}
public void setAirline_company(String airline_company) {
this.airline_company = airline_company;
}
public String getDeparture_airport() {
return departure_airport;
}
public void setDeparture_airport(String departure_airport) {
this.departure_airport = departure_airport;
}
public float getPassenger_number() {
return passenger_number;
}
public void setPassenger_number(float passenger_number) {
this.passenger_number = passenger_number;
}
public float getFuel_percentage() {
return fuel_percentage;
}
public void setFuel_percentage(float fuel_percentage) {
this.fuel_percentage = fuel_percentage;
}
public int isFlight_time_remaining() {
return flight_time_remaining;
}
public void setFlight_time_remaining(int flight_time_remaining) {
this.flight_time_remaining = flight_time_remaining;
}
public boolean isIn_queue() {
return in_queue;
}
public void setIn_queue(boolean in_queue) {
this.in_queue = in_queue;
}
public boolean isIs_landed() {
return is_landed;
}
public void setIs_landed(boolean is_landed) {
this.is_landed = is_landed;
}
}
This is the code which makes the connection to the sql DB and trys to add the info to an arraylist...
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class FlightsDbtoArrayList {
ArrayList<Aircraft> allFlights = new ArrayList<Aircraft>();
public static void main(String[] args) {
// Entering username to verify connection to SQL Server
String url = "jdbc:mysql://";
Connection con;
Statement statement1;
try {
Class.forName("com.mysql.jdbc.Driver");
//Catching any errors and printing a message to the user
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
// Entering username and password to verify connection to SQL Server
con = DriverManager.getConnection(url);
//Creating platform for a SQL query Statement
statement1 = con.createStatement();
//Creating and executing the designed SQL query statement
ResultSet results1 = statement1.executeQuery("SELECT aircraft_number, airline_company, departure_airport, passenger_number, fuel_Percentage, flight_time_remaining, in_queue, is_landed FROM flights");
//Displaying the results of the query to screen
printResults(results1);
con.close();
statement1.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
}
/**
* Method to display the results of the three SQL queries
* #param results
* #throws SQLException
*
*
*/
public ArrayList<Aircraft> allFlights() {
return allFlights;
}
/**
* set songs on the system
* #param allSongs
*/
public void setSongs(ArrayList<Aircraft> allSongs) {
allSongs = this.allFlights;
}
private static void printResults(ResultSet results) throws SQLException {
while (results.next()) {
int aircraft_number = results.getInt("aircraft_number");
String airline_company = results.getString("airline_company");
String departure_airport = results.getString("departure_airport");
int passenger_number = results.getInt("passenger_number");
float fuel_percentage = results.getFloat("fuel_percentage");
int flight_time_remaining = results.getInt("flight_time_remaining");
boolean in_queue = results.getBoolean("in_queue");
boolean is_landed = results.getBoolean("is_landed");
Aircraft a1;
ArrayList<Aircraft> allFlights = new ArrayList<Aircraft>();
a1 = new Aircraft(aircraft_number, airline_company, departure_airport, passenger_number, fuel_percentage, flight_time_remaining, in_queue, is_landed);
allFlights.add(a1);
System.out.println(allFlights);
}
}
}
`
Yes it is definitely possible to have list of objects(Aircraft) derived from database. But in this case your while loop inside the PrintResult has some errors.
You are creating list allFights within the while loop which will create new list in each iteration and add a1 to it so in the end you will only have a list with one aircraft details in it.
System.out.println(allFlights) will not give much desired output (or it might), but I would advice you should override toString() method in your AirCraft class.
Try to change your PrintResult method as following.
private static void printResults(ResultSet results) throws SQLException {
ArrayList<Aircraft> allFlights = new ArrayList<Aircraft>();
Aircraft a1;
while (results.next()) {
int aircraft_number = results.getInt("aircraft_number");
String airline_company = results.getString("airline_company");
String departure_airport = results.getString("departure_airport");
int passenger_number = results.getInt("passenger_number");
float fuel_percentage = results.getFloat("fuel_percentage");
int flight_time_remaining = results.getInt("flight_time_remaining");
boolean in_queue = results.getBoolean("in_queue");
boolean is_landed = results.getBoolean("is_landed");
a1 = new Aircraft(aircraft_number, airline_company, departure_airport, passenger_number, fuel_percentage, flight_time_remaining, in_queue, is_landed);
allFlights.add(a1);
//Instead of this line System.out.println(allFlights);
//write following code
For(AirCraft aircraft : allFlights){
System.out.println(aircraft.toString());
}
}
}
Edit 2: Write the following method in your AirCraft class.
#Override
Public String toString(){
String string;
//Write some code here so that you can represent you object using this method
//for example I am adding just the aircraft_number
string = getAircraft_number()+"";
return string;
}
Important: The toString() method I wrote is just an example you need to learn how to correctly write toString() method for any of your class. this and this are good starting point to learn that. And stop worrying about your your list of allFlights because as per this code it is getting created but you can not print it the way you are trying to.
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());