I'm having trouble just return the string of the color. For some reason it will not return the num. Not sure if I need to insert the end of the if statement with an else but I feel like that what the catch statement if for.
Main Class
package edu.computer.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Computer {
public Computer() {
}
public String getProcessor() {
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader keyboard = new BufferedReader(in);
String num = null;
System.out.println("Type red to print red or blue to print blue");
try {
num = keyboard.readLine();
if (num.equals("red"))
num = "red";
if (num.equals("blue"))
num = "blue";
} catch (IOException e) {
System.out.println("Exception occured!");
}
return num;
}
}
Test Class
package edu.computer.test;
public class ComputerTester {
public static void main(String[] args) {
Computer a = new Computer();
a.getProcessor();
}
}
Your code example works just fine. I added the following line to your test and it printed the colour as expected:
public static void main(String[] args) {
Computer a = new Computer();
System.out.println(a.getProcessor());
}
Prints blue or red as appropriate.
Related
I came up with the following code to read information from a file:
import java.io.*;
import java.util.*;
public class Reader {
private Scanner s;
public void openFile() {
try {
s = new Scanner(new File("file.txt"));
} catch (Exception e) {
System.out.println("File not found. Try again.");
}
}
public void readFile() {
while (s.hasNext()) {
String a = s.next();
String b = s.next();
String c = s.next();
int d = s.nextInt();
int e = s.nextInt();
int f = s.nextInt();
}
public void closeFile() {
s.close();
}
}
However, I get a NullPointer error on the (while (s.hasNext())) line and can't find a solution.
I'm working in Eclipse and the file I'm reading from is imported correctly into the project so that should not be an issue.
EDIT:
The way I access the methods:
public class Tester {
public static void main(String[] args) {
Reader read = new Reader();
read.openFile();
read.readFile();
read.closeFile();
}
}
As per the statement where NPE throws, while (s.hasNext()), it's most probable that the s is null pointer, you can add System.out.println(s); before that statement to double confirm it.
And for the reason why the s is null, there are two possible reasons:
You didn't invoke openFile before readFile
Exception is thrown when you open the file. The s is only a declaration and hasn't pointed to any object yet.
Maybe for a better practice, you can assert whether a instance is null or not before invoking its method. And as per my understanding, the readFile depends on the result of openFile, maybe you can set return value of openFile like a boolean value and check the return value before further open file operation. It's impossible to read a file which can't be even open, right?
import java.io.*;
import java.util.*;
public class Reader {
private Scanner s;
public boolean openFile() {
try {
s = new Scanner(new File("file.txt"));
return true;
} catch (Exception e) {
System.out.println("File not found. Try again.");
return false;
}
}
public void readFile() {
while (s.hasNext()) {
String a = s.next();
String b = s.next();
String c = s.next();
int d = s.nextInt();
int e = s.nextInt();
int f = s.nextInt();
}
}
The invoker can do something like below:
Reader reader = new Reader();
if (reader.openFile())
reader.readFile();
Hey guys I have a problem, I would like to assert that when I input 2 specific strings that an array is returned. I want to use the assert statement and parameterized testing to do this however my current assert statement is showing an error, I have placed my code below please help:
My inputs are both String data type and my output from the drop course is an array
import IT_chatbot.drop_course;
#RunWith(Parameterized.class)
public class drop_course_test {
drop_course check;
#Before
public void setUp() throws Exception {
check= new drop_course();
}
private String[] output;
private String input1;
private String input2;
public drop_course_test(String output[],String input1,String input2 )
{
this.output=output;
this.input1=input1;
this.input2=input2;
}
#Parameters
public static Collection testConditions(){
String[] droplist1={"ITE222 Web Development 2","ITE365 Software Quality Management","ITE446 Current Topics in Software Engineering","ITE220 Programming 1"};
return Arrays.asList(new Object [][]{
{droplist1, "216110116","ITE200"},
});
}
#Test
public void test() {
assertEquals(output, drop_course.drop(input1, input2));
}
}
The method i am trying to test can be seen below:
package IT_chatbot;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class drop_course {
public static String[] drop(String studentID, String courseCode){
String filePath = "enrolled_courses"+studentID+".txt";
String disenrolled_subtracted[]=new String[5];
int value_at=0;
System.out.println("Your Course has been dropped the following are your current courses:");
try {
BufferedReader lineReader = new BufferedReader(new FileReader(filePath));
String lineText = null;
while ((lineText = lineReader.readLine()) != null) {
if(lineText.contains(courseCode)){
lineText = lineText.replace(lineText, "");
FileWriter writer = new FileWriter("filePath", true);
writer.write("-disenrolled-"+lineText);
}else{
System.out.println(lineText);
disenrolled_subtracted[value_at]=lineText;
value_at=value_at+1;
}
}
lineReader.close();
} catch (IOException ex) {
System.err.println(ex);
}
return disenrolled_subtracted;
}
Use Method
Assert.assertArrayEquals( expectedResult, result );
Instead of
assertEquals
My code:
public class IOTest {
public static void main(String[] args) {
System.out.println("请在下面输入一行字符 :\n");
try {
System.in.read(buffer,0,255);
}
catch(Exception e) {
System.out.println("读取输入字符出错,错误信息为 :"+e.toString()+"\n");
}
System.out.println("您刚才输入的一行字符为 :\n");
String inputStr=new String(buffer,0);
System.out.println(inputStr);
}
}
Following is the error information when running the code :
D:\dasi\java\javaLab>javac -encoding UTF-8 IOTest.java
`enter code here`IOTest.java:7: 错误: 找不到符号
System.in.read(buffer,0,255);
^
符号: 变量 buffer
位置: 类 IOTest
IOTest.java:13: 错误: 找不到符号
String inputStr=new String(buffer,0);
^
符号: 变量 buffer
位置: 类 IOTest
注: IOTest.java使用或覆盖了已过时的 API。
注: 有关详细信息, 请使用 -Xlint:deprecation 重新编译。
2 个错误
Can someone help me? I really checked and I still don't know why.
By the way, the Chinese words "错误: 找不到符号" means "error : cannot find symbol".
You should create buffer variable like this:
byte[] buffer = new byte[256]
Full code:
public class IOTest {
public static void main(String[] args) {
System.out.println("请在下面输入一行字符 :\n");
byte[] buffer = new byte[256]; // This line was added
try {
System.in.read(buffer,0,255);
}
catch(Exception e) {
System.out.println("读取输入字符出错,错误信息为 :"+e.toString()+"\n");
}
System.out.println("您刚才输入的一行字符为 :\n");
String inputStr=new String(buffer,0);
System.out.println(inputStr);
}
}
You may want to read up on some Java tutorial before proceeding -- such as this one: http://docs.oracle.com/javase/tutorial/essential/io/cl.html
You program has to be changed to something like this:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class IOTest {
public static void main(String[] args) {
System.out.println("请在下面输入一行字符 :\n");
BufferedReader br;
String inputLine = "";
try {
br = new BufferedReader(new InputStreamReader(System.in));
inputLine = br.readLine();
} catch(Exception e) {
System.out.println("读取输入字符出错,错误信息为 :"+e.toString()+"\n");
}
System.out.println("您刚才输入的一行字符为 :\n" + inputLine);
// String inputStr=new String(buffer,0);
// System.out.println(inputStr);
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I have a small assignment for uni which I seem to be stuck with. The application is suppose to be a quiz program which reads questions and answers from a text files and stores them like a flash card. My problem is that my buffered reader seems to be returning the nullPointer exception when it tries to read from the file. I'm unsure why this is. I will provide all code and highlight the error in bold. After doing a bit of debugging I found that the readLine method was returning null. Any thoughts? Thanks a lot. Error is at String[] line = getLine().split(":");
text file is in the format question:answer
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class Quiz {
private ArrayList<FlashCard> flashCards;
public static void main(String[] args){
Quiz quiz1 = new Quiz();
}
public Quiz(){
FlashCardReader cardReader = new FlashCardReader();
try {
if(cardReader.isReady()==true){
flashCards = cardReader.getFlashCards();
play();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void play(){
Scanner userInput = new Scanner(System.in);
String answer = userInput.nextLine();
for(FlashCard card: flashCards){
System.out.println(card.getQuestion());
System.out.println("********************");
sleep(10000);
System.out.println("Enter your answer:");
answer = userInput.nextLine();
if(card.getAnswer() == answer){
System.out.println("Correct.");
}else{
System.out.println("Incorrect. The correct answer is " + card.getAnswer() + ".");
}
}
}
private void sleep(int x){
try {
Thread.sleep(x);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class FlashCardReader {
BufferedReader reader;
public FlashCardReader(){
try {
reader = new BufferedReader(new FileReader("Questions.txt"));
} catch (FileNotFoundException e) {
System.err.println(e.toString());
}
}
public String getLine() throws IOException{
return reader.readLine();
}
public Boolean isReady() throws IOException{
return reader.ready();
}
public ArrayList<FlashCard> getFlashCards(){
ArrayList<FlashCard> flashcards = new ArrayList<FlashCard>();
try {
for(int i = 1; i <= reader.lines().count(); i++){
**String[] line = getLine().split(":");**
System.out.println(line[0]);
flashcards.add(new FlashCard(line[0],line[1]));
}
} catch (IOException e) {
System.err.println(e);
e.printStackTrace();
}
return flashcards;
}
}
public class FlashCard {
private String question;
private String answer;
public FlashCard(String question, String answer){
this.question = question;
this.answer = answer;
}
public String getQuestion(){
return question;
}
public String getAnswer(){
return answer;
}
}
How about changing the for loop to while loop to avoid null condition. As you cannot be sure that your code starts from line one as you expect by assigning i to 1.
String lines ;
while((lines = getLine()) != null){
String[] lineArray = lines.split(":");
System.out.println(lineArray[0]);
flashcards.add(new FlashCard(lineArray[0],lineArray[1]));
}
I get enclosing instance of type error in my java code and i don't know what is that error my java code is below
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class phase45 {
public class Vertex {
public Vertex(Integer na){ name = na;}
private Integer name ;
public Integer getname(){
return name;
}
ArrayList adjs = new ArrayList<Integer>();
}
public class graph {
// public Integer name ;
ArrayList Vertexes = new ArrayList<Vertex>();
public Vertex GetVertex(Integer name){
for(int i = 0; i < Vertexes.size(); i++){
if (((Vertex) Vertexes.get(i)).name == name)
return (Vertex) Vertexes.get(i);
}
return null;
}
public void AddVertex(Vertex V){
Vertexes.add(V);
}
}
public static void CreateGraph(File a , graph g) throws IOException{
String st1 , st2 , line;
Integer vs , es;
try {
BufferedReader br = new BufferedReader(new FileReader(a));
st1 = br.readLine();
st2 = br.readLine();
vs = Integer.parseInt(st1);
es = Integer.parseInt(st2);
while ((line = br.readLine()) != null) {
String[] splited = line.split("\\s+");
//Vertex vTemp = null;
Integer NameV = Integer.valueOf(splited[0]);
System.out.println("line + " + line);
//vTemp.name = NameV;
Vertex vTemp = new Vertex(NameV);
Integer AdjV = Integer.valueOf(splited[1]);
vTemp.adjs.add(AdjV);
if(g.GetVertex(NameV) == null)
g.AddVertex(vTemp);
else
g.GetVertex(NameV).adjs.add(AdjV);
}
System.out.println("vs : " + vs + " es "+ es);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
//try{
File file = new File("/Users/mehran/Desktop/filee.txt");
graph g = null;
System.out.println("hi boy");
CreateGraph(file , g);
//}catch(NullPointerException ee){;}
}
}
I get error in CreateGraph this line : Vertex vTemp = new Vertex(NameV);
and I can't understand why , please fix it?
You try to use a C++-Constructor.
In Java you have to write:
Vertex vTemp = new Vertex(NameV); // Class-names should start with a capital letter
The code you attached here compile fine for me. I tried to compile the class Vertex and found it OK.
I think the problem occurred when you try to create object of this class. Try to create Vetex object like this -
Vetex v = new Vertex(name);
Here's a little edit to your code (of course you can instantiate adjs anywhere in your methods)
package test;
import java.util.ArrayList;
public class vertex {
private Integer name ;
public vertex(Integer na){ name = na;}
public Integer getname(){
return name;
}
public static void main(String[] args) {
ArrayList adjs = new ArrayList<Integer>();
}
}
the code compiled, but didn't want to run because you didn't add the main method