This question already has answers here:
Comparing two integer arrays in Java
(10 answers)
Closed 7 years ago.
The statement before the begining of while loop System.out.println("Value of i before loop = " + i); is not being printed and the value of i in the loop is not being printed starting from 1. Instead it starts printing from a random big int.
package main;
import java.util.Random;
public class Main {
public static void main(String args[]){
Random ran = new Random();
int[] in = {2,5,9};
int[] c_gen = new int[3];
int i = 0;
System.out.println("Value of i before loop = " + i);
while(!(c_gen.equals(in))){
c_gen[0] = ran.nextInt(10);
c_gen[1] = ran.nextInt(10);
c_gen[2] = ran.nextInt(10);
i++;
System.out.println(c_gen[0] + " " + c_gen[1] + " " + c_gen[2] + " .................." + i);
}
System.out.print("in = ");
for(int x : in)
System.out.print(x + " ");
System.out.print("\n" + "c_gen = ");
for(int x : c_gen)
System.out.print(x + " ");
System.out.println("\n" + "i = " + i);
}
}
You are directly comparing arrays resulting in an infinite loop. Those results are being printed but are going to be at the top of tons and tons of output. Fix your comparison.
Sotirios' intuition is correct - your bug is in the line while(!(c_gen.equals(in))). You can't compare arrays for equality using the .equals(...) method because "arrays inherit their equals-method from Object, [thus] an identity comparison will be performed for the inner arrays, which will fail, since a and b do not refer to the same arrays." (source). Thus because c_gen and in will always refer to different arrays (even if their contents are the same), your loop will go forever.
Try Arrays.equals(..) instead:
public static void main(String[] args) {
Random ran = new Random();
int[] in = {2,5,9};
int[] c_gen = new int[3];
int i = 0;
System.out.println("Value of i before loop = " + i);
while(!Arrays.equals(in, c_gen)){
c_gen[0] = ran.nextInt(10);
c_gen[1] = ran.nextInt(10);
c_gen[2] = ran.nextInt(10);
i++;
System.out.println(c_gen[0] + " " + c_gen[1] + " " + c_gen[2] + " .................." + i);
}
System.out.print("in = ");
for(int x : in)
System.out.print(x + " ");
System.out.print("\n" + "c_gen = ");
for(int x : c_gen)
System.out.print(x + " ");
System.out.println("\n" + "i = " + i);
}
This works (terminates in finite time) for me, with sample output:
Value of i before loop = 0
1 9 9 ..................1
5 4 1 ..................2
1 1 6 ..................3
1 3 6 ..................4
.... //Omitted because of space
6 5 8 ..................1028
2 5 9 ..................1029
in = 2 5 9
c_gen = 2 5 9
i = 1029
I get:
Value of i before loop = 0
2 2 1 ..................1
2 2 4 ..................2
...
Suggest you rebuild the project and try again.
As originally posted your code will not terminate because int[].equals(int[]) will not do what you expect.
You could try this though.
private static boolean equals(int[] a, int[] b) {
if (a == null && b == null) {
// Both null
return true;
}
if (a == null || b == null) {
// One null
return false;
}
if (a.length != b.length) {
// Differ in length.
return false;
}
for (int i = 0; i < a.length; i++) {
if (a[i] != b[i]) {
// Mismatch
return false;
}
}
// Same.
return true;
}
public void test() {
Random ran = new Random();
int[] in = {2, 5, 9};
int[] c_gen = new int[3];
int i = 0;
System.out.println("Value of i before loop = " + i);
while (!equals(c_gen, in)) {
c_gen[0] = ran.nextInt(10);
c_gen[1] = ran.nextInt(10);
c_gen[2] = ran.nextInt(10);
i++;
System.out.println(c_gen[0] + " " + c_gen[1] + " " + c_gen[2] + " .................." + i);
}
System.out.print("in = ");
for (int x : in) {
System.out.print(x + " ");
}
System.out.print("\n" + "c_gen = ");
for (int x : c_gen) {
System.out.print(x + " ");
}
System.out.println("\n" + "i = " + i);
}
Related
The task is to:
Part one:
Write a program which prints the integers from 1 to a number given by the user.
Sample output part 1
Part two:
Ask the user for the starting point as well.
Sample output part 2
My code:
import java.util.Scanner;
import javax.swing.plaf.synth.SynthOptionPaneUI;
public class FromWhereToWhere {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// part one
System.out.println("Where to?");
int end = Integer.valueOf(scanner.nextLine());
for (int i = 1; i < end + 1; i++) {
System.out.println(i);
}
// part two
System.out.println("Where to?");
end = Integer.valueOf(scanner.nextLine());
System.out.println("Where from?");
int start = Integer.valueOf(scanner.nextLine());
for (int i = start; i < end + 1; i++) {
System.out.println(i);
}
}
}
It works as intended my terminal
But I get an error in TMC saying
FAIL:
WhereFromTest test
NoSuchElementException: No line found
The code for testing:
import fi.helsinki.cs.tmc.edutestutils.MockStdio;
import fi.helsinki.cs.tmc.edutestutils.Points;
import fi.helsinki.cs.tmc.edutestutils.ReflectionUtils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.*;
import static org.junit.Assert.*;
#Points("02-16.2")
public class WhereFromTest {
#Rule
public MockStdio io = new MockStdio();
#Test
public void test() {
int[][] pairs = {{1, 1}, {12, 8}, {50, 100}, {-2,2}};
for (int[] pair : pairs) {
test(pair);
}
}
private void test(int[] pair) {
io.setSysIn(pair[0] + "\n" + pair[1] + "\n");
int len = io.getSysOut().length();
ReflectionUtils.newInstanceOfClass(FromWhereToWhere.class);
FromWhereToWhere.main(new String[0]);
String output = io.getSysOut().substring(len);
output = output.replaceAll("[^-\\d]+", " ").trim();
String[] lines = output.split("\\s+");
int linesInOutput = (lines.length == 1 && lines[0].isEmpty()) ? 0 : lines.length;
int linesCount;
if(pair[0] < pair[1]) {
linesCount = 0;
} else {
linesCount = pair[0] - pair[1] + 1;
}
if (linesCount != linesInOutput) {
String numbersCount = (linesCount == 1) ? "number": "numbers";
fail("With the input " + pair[0] + ", " + pair[1] + " output should contain " + linesCount + " " + numbersCount + ", now it contained " + linesInOutput);
}
if(linesCount == 0) {
return;
}
int firstNumber = Integer.valueOf(lines[0]);
if(firstNumber != pair[1]) {
fail("With the input " + pair[0] + ", " + pair[1] + " the first printed number should be " + pair[1] + ", now it was " + firstNumber);
}
int lastNumber = getLastNumber(output);
if(lastNumber != pair[0]) {
fail("With the input " + pair[0] + ", " + pair[1] + " the last printed number should be " + pair[0] + ", now it was " + lastNumber);
}
}
private static int getLastNumber(String inputStr) {
String patternStr = "(?s).*?(-?\\d+)\\s*$";
Matcher matcher = Pattern.compile(patternStr).matcher(inputStr);
assertTrue("The output should be a number.", matcher.find());
int number = Integer.valueOf(matcher.group(1));
return number;
}
}
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;
}
I am having an incredibly difficult time trying to figure out why I am getting this error.
When I use a driver file to test the program it fails horribly.
Here's my code:
import java.util.Scanner;
import java.lang.Math.*;
public class Histogram
{
private int[] arrayData;
private int[] arrayRange;
private final int LOW = 1;
private final int HIGH = 100;
public Histogram()
{
int[] arrayData = new int[11];
}
public void getInput()
{
int[] arrayRange = new int[11];
for(int count = 1; count < arrayRange.length; count++)
{
arrayRange[count] = count * 10;
}
Scanner input = new Scanner(System.in);
System.out.println("Enter numbers from 1 to 100, Type -999 to quit.");
int nextNumb = input.nextInt();
while(nextNumb != -999)
{
if(nextNumb >= LOW && nextNumb <= HIGH)
{
for(int i = 0; i <= arrayRange.length; i++)
{
if(nextNumb > arrayRange[i] && nextNumb <= arrayRange[i+1])
arrayData[i]++;
}
nextNumb = input.nextInt();
}
else arrayData[10]++;
nextNumb = input.nextInt();
}
}
public String starPrint(double count)
{
String star = "";
count = (Math.round(count) / 5);
for(int i = 1; i <= count; i++)
{
star = star + "*";
}
return star;
}
public String toString()
{
String results = " Range | Histogram" + "\n";
results = results + "1 - 10 | " + starPrint(arrayData[0]) + "\n";
results = results + "11 - 20 | " + starPrint(arrayData[1]) + "\n";
results = results + "21 - 30 | " + starPrint(arrayData[2]) + "\n";
results = results + "31 - 40 | " + starPrint(arrayData[3]) + "\n";
results = results + "41 - 50 | " + starPrint(arrayData[4]) + "\n";
results = results + "51 - 60 | " + starPrint(arrayData[5]) + "\n";
results = results + "61 - 70 | " + starPrint(arrayData[6]) + "\n";
results = results + "71 - 80 | " + starPrint(arrayData[7]) + "\n";
results = results + "81 - 90 | " + starPrint(arrayData[8]) + "\n";
results = results + "91 - 100 | " + starPrint(arrayData[9]) + "\n";
results = results + "Outliers: " + starPrint(arrayData[10]) + "\n";
return results;
}
}
I believe that the problem is in my getInput method
right here to be precise:
if(nextNumb > arrayRange[i] && nextNumb <= arrayRange[i+1])
arrayData[i]++;
I have no idea what's wrong with it though I am a beginner programmer and couldn't find a solution to this particular problem.
Thanks for any help you're able to give!
public Histogram()
{
int[] arrayData = new int[11];
}
You're shadowing your arrayData field in the constructor. This is creating a local variable with the same name as your class's arrayData field, initializing it, then immediately discarding it. When you try to use the field later in your code, it's null. Get rid of the int[] part.
Note that your next exception will be an ArrayIndexOutOfBoundsException ... you should look at your loop ;)
this: for(int i = 0; i <= arrayRange.length; i++)
wont work since you are trying to access arrayRange[i] and arrayRange[i+1]
which dont exists for i = arrayRange.length-1 and further
so change it to:
for(int i = 0; i < arrayRange.length-1; i++)
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);
}
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