Here is the main problem:
java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at ExamAnalysis.main(ExamAnalysis.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:271)
The program compiles and runs. It's just that I am either getting the java.util.NoSuchElementException along with my five jother errors with (answer.charAt(i) == char) near the bottom. Here is my program:
import java.io.*;
import java.util.Scanner;
class ExamAnalysis
{
public static void main(String [] args) throws FileNotFoundException
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please type the correct answers to the exam questions, one right after the other: ");
String answers = keyboard.nextLine();
System.out.println("Where is the file with all the student responses? ");
String responses = keyboard.nextLine();
Scanner read = new Scanner(new File(responses));
while (read.hasNextLine())
{
for (int i = 0; i <= 10; i++)
{
responses = read.nextLine();
int p = 1;
p += i;
System.out.println("Student " + p + " responses: " + responses.substring(0,10));
}
System.out.println("Thank you for the data on 9 students. Here's the analysis: ");
resultsByStudents(responses, answers);
analysis(responses);
}
}
public static void resultsByStudents(String responses, String answers)
{
System.out.println ("Student # Correct Incorrect Blank");
System.out.println ("~~~~~~~~~ ~~~~~~~ ~~~~~~~~~ ~~~~~");
int student = 0;
int correct = 0;
int incorrect = 0;
int blank = 0;
for (int i = 0; i <= 9; i++)
{
for (int j = 0; j <= responses.length(); j++)
{
if ((responses.charAt(j)) == answers.charAt(j))
correct++;
else if ((responses.charAt(j)) != answers.charAt(j))
incorrect++;
else
blank++;
}
System.out.println(student + " " + correct + " " + incorrect + " " + blank);
student++;
}
}
public static void analysis(String responses)
{
System.out.println("QUESTION ANALYSIS (* marks the correct response)");
System.out.println("~~~~~~~~~~~~~~~~~");
//stores the percentage of each choice chosen
double A = 0;
double B = 0;
double C = 0;
double D = 0;
double E = 0;
double X = 0;
// tallys every variable chosen per question
for (int i = 0; i <= 10; i++) // go through all the questions
{
for (int j = 0; j <= responses.charAt(i); j++) //go through all the student responses
{
// variable that are being tallied
int chooseA = 0;
int chooseB = 0;
int chooseC = 0;
int chooseD = 0;
int chooseE = 0;
int chooseBlank = 0;
//variables take percentage of choices that have been chosen from each student
A = chooseA/9;
B = chooseB/9;
C = chooseC/9;
D = chooseD/9;
E = chooseE/9;
X = chooseBlank/9;
// variables that will print the asterisk with certain character of correct answer
String a = "A";
String b = "B";
String c = "C";
String d = "D";
String e = "E";
String blank = "blank";
if (responses.charAt(j) == A)
chooseA++;
else if (responses.charAt(j) == B)
chooseB++;
else if (responses.charAt(j) == C)
chooseC++;
else if (responses.charAt(j) == D)
chooseD++;
else if (responses.charAt(j) == E)
chooseE++;
else
chooseBlank++;
System.out.println("Question #" + i);
if (answers.charAt(i) == 'A') a = "A*"; // answers cannot be resolved(I already made it a global variable in my main method.)
else if (answers.charAt(i) == 'B') b = "B*";// answers cannot be resolved
else if (answers.charAt(i) == 'C') c = "C*";// answers cannot be resolved
else if (answers.charAt(i) == 'D') d = "D*";// answers cannot be resolved
else if (answers.charAt(i) == 'E') e = "E*";// answers cannot be resolved
System.out.println(a + " " + b + " " + c + " " + d + " " + e + " " + blank);
System.out.println (chooseA + " " + chooseB + " " + chooseC + " " + chooseD + " " + chooseE + " " + chooseBlank );
System.out.println (A + " " + B + " " + C + " " + D + " " + E + " " + X);
}
}
}
}
while (read.hasNextLine())
{
for (int i = 0; i <= 10; i++)
{
responses = read.nextLine();
int p = 1;
p += i;
System.out.println("Student " + p + " responses: " + responses.substring(0,10));
}
System.out.println("Thank you for the data on 9 students. Here's the analysis: ");
resultsByStudents(responses, answers);
analysis(responses);
}
}
Your logic here is confusing you. read.nextLine(); "Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line."
So you are saying, does it have a line? If so, read the next 10...well...11 lines, which isn't what you want. You don't know if there are 11 lines past this point. Don't know what that text file looks like, but you will want to restructure this part to either say, "While it has a next line", or "Read 11 lines"
Remove the for loop may resolve the issue. You are checking only once by using while(hasNextLine() ) but calling read.nextLine() 10 times in for loop.
for (int i = 0; i <= 10; i++)
{
responses = read.nextLine();
.......
}
int i = 0;
int numberOfStudents = 9;
while (i < numberOfStudents && read.hasNextLine()){
responses = read.nextLine();
i++;
System.out.println("Student " + i + " responses: " + responses.substring(0,10));
}
System.out.println("Thank you for the data on "+ numberOfStudents +" students. Here's the analysis: ");
resultsByStudents(responses, answers);
analysis(responses);
i < numberOfStudents : makes the required number of inserts
read.hasNextLine() : checks if there is input from console. If not the program waits for input.
for (int i = 0; i <= 10; i++)
count from 0 -> 10 = 11 students
Related
On the for loop I have the Java applet is showing me that I have an error. I am trying to use the for loop to count the repetition of letter.
String countString = "";
for (int i = 0; i < 26; i++){
// at the line below, my java applet says I have an error, and that the
//"letterCounts" should be a int and not a string, but I need it to be a string
String n = letterCounts[i];
if (n.equals("0")) {
countString = countString + " ";
} else if (n.length() == 1) {
countString = countString + " " + n + " ";
} else {
countString = countString + n + " ";
}
}
this.countLabel.setText(countString);
You donot show the definition of letterCounts, but I bet it is int[] letterCounts.
So since letterCounts is an array of int, you cannot just assign it to a String.
Just change String n to int n and your comparison to n == 0 and it should work. See below:
String countString = "";
for (int i = 0; i < 26; i++)
{
int n = letterCounts[i];
if (n == 0) {
countString = countString + " ";
} else if (n < 10) {
countString = countString + " " + n + " ";
} else {
countString = countString + n + " ";
}
}
this.countLabel.setText(countString);
I wrote a program for my Computer Science class where it reads a file and imports the data and then just adds the numbers but it seems to be adding an extra addition sign.
import java.io.*; //necessary for File and IOException
import java.util.*; //necessary for Scanner
public class Tester
{
public static void main( String args[] ) throws IOException
{
Scanner sf = new Scanner(new File("/Volumes/DVLUP Flash/Numbers.txt"));
int maxIndx = -1; //-1 so when we increment below, the first index is 0
String text[] = new String[1000]; //To be safe, declare more than we
while(sf.hasNext( ))
{
maxIndx++;
text[maxIndx] = sf.nextLine( );
//System.out.println(text[maxIndx]); //Remove rem for testing
}
sf.close();
for(int j =0; j <= maxIndx; j++)
{
Scanner sc = new Scanner(text[j]);
}
String answer = ""; //We will accumulate the answer string here.
int sum; //accumulates sum of integers
for(int j = 0; j <= maxIndx; j++)
{
Scanner sc = new Scanner(text[j]);
sum = 0;
answer = "";
while(sc.hasNext())
{
int i = sc.nextInt();
answer = answer + i + " + ";
sum = sum + i;
}
//sc.next();
answer = answer + " = " + sum;
System.out.println(answer);
}
}
}
The output is
12 + 10 + 3 + 5 + = 30
18 + 1 + 5 + 92 + 6 + 8 + = 130
2 + 9 + 3 + 22 + 4 + 11 + 7 + = 58
There's an extra after the last number, how do I fix that?
After the last iteration you are having an "extra" plus sign because that´s the way you are printing it. You are ending the String with a + as it can be seen in your while loop.
to change it either add the + before the value as
if(sc.hasNext()) {
int i = sc.nextInt();
answer = i + "";
sum += i;
while(sc.hasNext())
{
i = sc.nextInt();
answer = answer + " + " + i;
sum = sum + i;
}
}
Or if you use Java 8 you could use the StringJoiner as
StringJoiner joiner = new StringJoiner(" + ");
while(sc.hasNext())
{
i = sc.nextInt();
// This automaticly includes a " + " between the values.
joiner.add(String.valueOf(i));
sum = sum + i;
}
After
while(sc.hasNext())
{
int i = sc.nextInt();
answer = answer + i + " + ";
sum = sum + i;
}
put
answer = answer.substring(0, answer.length()-1);
One option would be to conditionally prepend a plus sign before appending each number in any case other than the first number:
answer = "";
while(sc.hasNext()) {
int i = sc.nextInt();
if (answer.length() > 0) {
answer += " + ";
}
answer = answer + i;
sum = sum + i;
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
This is my code for a program that should count the number of each letter in an inputted string. When I run the program, it says that there is 0 of each letter, no matter what I input. Thanks for the help in advance!
import java.util.Scanner;
public class stringprogram {
public static void stringinputmethod()
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a String");
String strs = scan.nextLine();
int strslength = strs.length();
int numa = 0;
int numb = 0;
int numc = 0;
int numd = 0;
int nume = 0;
int numf = 0;
int numg = 0;
int numh = 0;
int numi = 0;
int numj = 0;
int numk = 0;
int numl = 0;
int numm = 0;
int numn = 0;
int numo = 0;
int nump = 0;
int numq = 0;
int numr = 0;
int nums = 0;
int numt = 0;
int numu = 0;
int numv = 0;
int numw = 0;
int numx = 0;
int numy = 0;
int numz = 0;
for(int i = 0; i <= strslength; i++)
{
if (strs.substring(i, i) == "a")
{
numa = numa + 1;
}
if (strs.substring(i, i) == "b")
{
numb = numb + 1;
}
if (strs.substring(i, i) == "c")
{
numc = numc + 1;
}
if (strs.substring(i, i) == "d")
{
numd = numd + 1;
}
if (strs.substring(i, i) == "e")
{
nume = nume + 1;
}
if (strs.substring(i, i) == "f")
{
numf = numf + 1;
}
if (strs.substring(i, i) == "g")
{
numg = numg + 1;
}
if (strs.substring(i, i) == "h")
{
numh = numh + 1;
}
if (strs.substring(i, i) == "i")
{
numi = numi + 1;
}
if (strs.substring(i, i) == "j")
{
numj = numj + 1;
}
if (strs.substring(i, i) == "k")
{
numk = numk + 1;
}
if (strs.substring(i, i) == "l")
{
numl = numl + 1;
}
if (strs.substring(i, i) == "m")
{
numm = numm + 1;
}
if (strs.substring(i, i) == "n")
{
numn = numn + 1;
}
if (strs.substring(i, i) == "o")
{
numo = numo + 1;
}
if (strs.substring(i, i) == "p")
{
nump = nump + 1;
}
if (strs.substring(i, i) == "q")
{
numq = numq + 1;
}
if (strs.substring(i, i) == "r")
{
numr = numr + 1;
}
if (strs.substring(i, i) == "s")
{
nums = nums + 1;
}
if (strs.substring(i, i) == "t")
{
numt = numt + 1;
}
if (strs.substring(i, i) == "u")
{
numu = numu + 1;
}
if (strs.substring(i, i) == "v")
{
numv = numv + 1;
}
if (strs.substring(i, i) == "w")
{
numw = numw + 1;
}
if (strs.substring(i, i) == "x")
{
numx = numx + 1;
}
if (strs.substring(i, i) == "y")
{
numy = numy + 1;
}
if (strs.substring(i, i) == "z")
{
numz = numz + 1;
}
}
System.out.println("Number of a's: " + numa + "\n" + "Number of b's: " + numb + "\n" + "Number of c's: " + numc + "\n" + "Number of d's: " + numd + "\n" + "Number of e's: " + nume + "\n" + "Number of f's: " + numf + "\n" + "Number of g's: " + numg + "\n" + "Number of h's: " + numa + "\n" + "Number of i's: " + numi + "\n" + "Number of j's: " + numj + "\n" + "Number of k's: " + numk + "\n" + "Number of l's: " + numl + "\n" + "Number of m's: " + numm + "\n" + "Number of n's: " + numn + "\n" + "Number of o's: " + numo + "\n" + "Number of p's: " + nump + "\n" + "Number of q's: " + numq + "\n" + "Number of r's: " + numr + "\n" + "Number of s's: " + nums + "\n" + "Number of t's: " + numt + "\n" + "Number of u's: " + numu + "\n" + "Number of v's: " + numv + "\n" + "Number of w's: " + numw + "\n" + "Number of x's: " + numx + "\n" + "Number of y's: " + numy + "\n" + "Number of z's: " + numz);
}
public static void main(String[] args)
{
stringinputmethod();
}
}
Correct usage of the substring method:
strs.substring(i, i)
needs to be
strs.substring(i, i + 1)
because the char at lastIndex is not included in the output.
Correct comparison of Strings in Java
Also, as pointed out in the comments to this answer, you are comparing Strings with the == operator.
This will only works as long as both your Strings are the same object. For proper comparison you need to use strs.substring(..).equals()
Proper storing of data
Additionally, as already suggested in a comment to your question, you should start using arrays to save data like this.
Instead of
int numa = 0;
....
int numz = 0;
you should use arrays, or even better Map<Character,Integer>.
strs.substring(i, i) == "a" have two problems:
substring(i, i) creates string from i (inclusive), till i (exclusive) which means it creates empty string ""
this is not how we compare Strings. == may work sometimes if strings are pooled, but for dynamically created strings you need to use equals instead of == because Strings are objects, or even better use charAt(i) to get primitive char which you can be able to compare like strs.charAt(i) == 'a' (notice ' instead of ").
You can also use enhanced for loop on array of characters representing your string to avoid charAt. You should probably also be working on lower case characters as pointed in this comment. So your code can look more like
for (char ch : strs.toLowerCase().toCharArray()){
//do something based on value of `ch`
}
Try this:
It is a little bit shorter than your implementation (which is very good, but still a little bit verbose). Use Java 8 with this code, otherwise it won't compile.
What does it do?
If you understand that a string is nothing more but an array you can iterate over that array and see what kind of value is at the given index. The value at this index is put in a map (remember, a map is a key-value-store). So if you put the Integer 1 in the map where its key is "a", that means "a" occurs 1 time.
By reading the values at the appropriate indexii (very sophisticated plural form of index) with HashMap.get("a") and then incrementing the value by one, we have a nice little letter counter... without the need to predefine numa=0 and so forth. Give it a try and let me know if it werx.
package lettercounter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
/**
*
* #author edm
*/
public class LetterCounter {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a String");
String strs = scan.nextLine();
//this map will be populated with the occurrence of the letters in the string.
HashMap<String, Integer> countenLetters = new HashMap<>();
//the next line generates a key-value-store whose key is the letter in the string
//and the value is the accumulated occurrence of said letter.
Arrays.asList(strs.split("")).stream().forEach((String letter) -> {
Integer count = 0;
try {
count = countenLetters.get(letter).intValue();
} catch (Exception e) {
//tried to access a non existing value in the map
//this happens if there is a letter which was not set in the map until now.
//i.e. the first time the letter is encountered.
//this is no error. could have done it with an if also.
}
countenLetters.put(letter, ++count);
});
//do with this stuff what you want;
countenLetters.forEach((k,v) -> {
System.out.println("Letter "+k+" occurs "+v+" times in the string.");
});
}
}
I have a code that will give me the coordinates of certain points in an array using user input. What code would I add to make the code output say that the address could not be found if the number in the array is not there? I'm pretty sure I need an else statement but I can't get it to work. Here is the code I have right now.
import java.util.Scanner;
public class LabActivityArray
{
public static void main (String[] args)
{
Scanner scanner = new Scanner (System.in);
int rows;
int columns;
int check1,check2;
System.out.println("Enter number of rows: ");
rows = scanner.nextInt();
System.out.println ("Now enter the number of columns: ");
columns = scanner.nextInt();
int[][] array = new int[rows][columns];
System.out.println("Enter the number to start the array: ");
int value = scanner.nextInt();
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
array[i][j]=value++;
System.out.print(array[i][j] + " " );
}
System.out.println();
}
System.out.println("Please give one integer value to be checked in the array: ");
check1 = scanner.nextInt();
System.out.println ("Please give a second integer value to be checked in the array: ");
check2 = scanner.nextInt();
for ( int i = 0; i < rows; ++i )
{
for ( int j = 0; j < columns; ++j )
{
if ( array[i][j] == check1 )
{
System.out.print(array[i][j] + " is located at address array[" + i + "," + j + "]");
}
if ( array[i][j] == check2 )
{
System.out.print("\n" + array[i][j] + " is located at address array[" + i + "," + j + "]");
System.out.println();
}
}
}
}
}
step 1: make a flag say
boolean check1Found = false;
step 2: if you find the value, set the flag to true
if ( array[i][j] == check1 )
{
System.out.print(array[i][j] + " is located at address array[" + i + "," + j + "]");
check1Found = true;
}
step 3: after your loop is finished, print a message if that flag is still false
if(check1Found == false)
{
System.out.println("check 1 not found");
}
You could add two bool flag which are false at first but when the numbers youre searching are found, they are set to true.
bool foundFlag1 = false;
bool foundFlag2 = false;
Then
if ( array[i][j] == check2 ) {
foundFlag2 = true;
..
}
and do the same for check1.
If the flags are false, you know that you couldn't find those inputs!
You are almost right here. Here is the Pseudocode
Initialize Boolean Flag = false;
Search for number in array. if found set Flag = True.
After searching the number in array, check Flag.
If Flag = False, print "the address could not be found"
I would do this:
boolean check1Flag = false;
boolean check2Flag = false;
for ( int i = 0; i < rows; ++i )
{
for ( int j = 0; j < columns; ++j )
{
if ( array[i][j] == check1 )
{
System.out.println(array[i][j] + " is located at address array[" + i + "," + j + "]");
check1Flag = true;
}
if ( array[i][j] == check2 )
{
System.out.println(array[i][j] + " is located at address array[" + i + "," + j + "]");
check2Flag = true;
}
}
}
if(!check1Flag)
{
System.out.println("Can't find " + check1);
}
if(!check2Flag)
{
System.out.println("Can't find " + check2);
}
The flags are set to true when the array is found, so if either are false than that address could not be found.
I'm trying to populate a 2d list array using 2 user inputs.
Problem I'm having is that in the code below, the 1st for statement isn't producing the outcome I'm expecting, the 2nd for is doing what is needed. Also, with the code below I'm unable to close scanner.
public static void main(String[] args) {
ArrayList<String> listCon = new ArrayList<String>();
ArrayList<String> listCol = new ArrayList<String>();
Scanner txtInput = new Scanner(System.in);
char addTo = 'y';
do {
System.out.println("\nCurrent list is " + listCon + listCol + "\n");
System.out.println("Would you like to add a country to the list?\n\t"
+ "( y ) = YES\n\t( n ) = NO");
addTo = txtInput.next().toLowerCase().charAt(0);
if (addTo == 'y') {
System.out.println("Enter country name: ");
listCon.add(txtInput.next().toLowerCase());
System.out.println("Enter colour: ");
listCol.add(txtInput.next().toLowerCase());
} else if (addTo == 'n') {
int i = 1;
int countCon = listCon.size();
if(countCon == 0) {
System.out.println("No countries have been entered.");
} else {
String str = "country";
if(countCon > 1) {
str = "countries";
}
System.out.println("Thankyou for your input. We found " + countCon + " " +
str + " in the list.");
System.out.println("Listed " + str + ":\n");
for(String n : listCon) {
char[] conDigit = n.toCharArray();
conDigit[0] = Character.toUpperCase(conDigit[0]);
n = new String(conDigit);
for(String b : listCol) {
char[] colDigit = b.toCharArray();
colDigit[0] = Character.toUpperCase(colDigit[0]);
b = new String(colDigit);
System.out.println("Country " + i + " : " + n + " - \t" + b);
i = i + 1;
}
break;
}
break;
}
} else {
System.out.println("Incorrect input detected. please try again. \n");
}
} while (true);
}
}
You need to remove extra break from the first for loop to iterate. Otherwise, you break after first iteration.
for(String n : listCon) {
....
for(String b : listCol) {
...
}
break; //remove this!
}
break;
EDIT
The result im after is Country 1 : France - Blue Country 2 : UK -
White Country 3 : Ireland - Green
You need to iterate like this:
for (int i = 0; i < listCon.size() && i < listCol.size(); i++) {
String n = listCon.get(i);
char[] conDigit = n.toCharArray();
conDigit[0] = Character.toUpperCase(conDigit[0]);
n = new String(conDigit);
String b = listCol.get(i);
char[] colDigit = b.toCharArray();
colDigit[0] = Character.toUpperCase(colDigit[0]);
b = new String(colDigit);
System.out.println("Country " + i + " : " + n + " - \t" + b);
}