Error when transferring code - java

I'm writing code for class, and the code works fine when I run it in Dr. Java in class. However when I input it for grading, I get an error that reads:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Main.main(Main.java:247)
at Ideone.assertRegex(Main.java:94)
at Ideone.test(Main.java:42)
at Ideone.main(Main.java:29)
I have no idea what this means, we haven't covered this sort of thing and I am not a very experienced programmer, sorry. My code is as follows;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int indexFirst = 0;
int indexSecond = 0;
int[] first = new int[10000];
int[] second = new int[10000];
System.out.println("Enter the values for the first array, up to 10000 values, enter a negative number to quit");
do {int value = scanner.nextInt();
if (value < 0) {
break;
}
first[indexFirst++] = value;
} while(true);
System.out.println("Enter the values for the second array, up to 10000 values, enter a negative number to quit");
do {int value = scanner.nextInt();
if (value <= 0) {
break;
}
second[indexSecond++] = value;
} while(true);
System.out.println("First Array:");
for (int i = 0; i < indexFirst; i++) {
System.out.print(first[i] + " ");
}
System.out.println("\n");
System.out.println("Second Array:");
for (int i = 0; i < indexSecond; i++) {
System.out.print(second[i] + " ");
}
System.out.println("\n");
for (int i = 1; i < indexFirst; i++) {
if (first[i-1] > first[i] ) {
System.out.println("ERROR: Array not in correct order");
return;
}
}
for (int i = 1; i < indexSecond; i++) {
if (second[i-1] > second[i] ) {
System.out.println("ERROR: Array not in correct order");
return;
}
}
int[] merged = new int[indexFirst + indexSecond];
int curIdx1 = 0;
int curIdx2 = 0;
for(int mergedIdx = 0; mergedIdx < merged.length; mergedIdx++) {
if (curIdx2 == indexSecond) {
merged[mergedIdx] = first[curIdx1++];
} else if (curIdx1 == indexFirst) {
merged[mergedIdx] = second[curIdx2++];
} else if (first[curIdx1] < second[curIdx2]) {
merged[mergedIdx] = first[curIdx1++];
} else {
merged[mergedIdx] = second[curIdx2++];
}
}
System.out.println("Merged Array:");
for (int i = 0; i < merged.length; i++) {
System.out.print(merged[i] + " ");
}
}
}
If anyone has any input on how to fix this, it would be much appreciated.

Related

Finding the mode of an array from user input java

So I'm making a program that gets an array from user-inputed values but I'm having trouble writing the code for finding the mode of the array. I tried writing my own code and then tried using a version of someone else's code but that didn't work out because I didn't fully understand it to be honest.
import java.util.Scanner;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int length;
Statistics stats = new Statistics();
System.out.println("Welcome to our statistics program!");
System.out.print("Enter the amount of numbers you want to store: ");
length=Integer.parseInt(keyboard.next());
int[] nums = new int[length];
for(int i=0; i<length; i++) {
System.out.println("Enter a number: ");
nums[i]=keyboard.nextInt();
}
System.out.println("Array elements are: ");
for (int i=0; i<length; i++) {
System.out.println(nums[i]);
}
public int Mode (int[] nums) {
double maxValue = -1.0d;
int maxCount = 0;
for(int i = 0; i < data.length; i++) {
double currentValue = data[i];
int currentCount = 1;
for(int j = i + 1; j < data.length; ++j) {
if(Math.abs(data[j] - currentValue) < epsilon) {
++currentCount;
}
}
}
if (currentCount > maxCount) {
maxCount = currentCount;
maxValue = currentValue;
} else if (currentCount == maxCount) {
maxValue = Double.NaN;
}
}
System.out.println("The minimum number is " + stats.Mode(nums));
You could consider using a HashMap to maintain the frequencies of the values in the array in your loop:
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static int getIntegerInput(String prompt, Scanner scanner) {
System.out.print(prompt);
int validInteger = -1;
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
validInteger = scanner.nextInt();
break;
} else {
System.out.println("Error: Invalid input, try again...");
System.out.print(prompt);
scanner.next();
}
}
return validInteger;
}
public static int getPositiveIntegerInput(String prompt, Scanner scanner) {
int num = getIntegerInput(prompt, scanner);
while (num <= 0) {
System.out.println("Error: Integer must be positive.");
num = getIntegerInput(prompt, scanner);
}
return num;
}
public static int getMode(int[] nums) {
if (nums.length == 0) {
throw new IllegalArgumentException("nums cannot be empty");
}
Map<Integer, Integer> valueFrequencies = new HashMap<>();
valueFrequencies.put(nums[0], 1);
int maxFreq = 1;
int candidateMode = nums[0];
for (int i = 1; i < nums.length; i++) {
int value = nums[i];
valueFrequencies.merge(value, 1, Integer::sum);
int candidateFreq = valueFrequencies.get(value);
if (candidateFreq > maxFreq) {
candidateMode = value;
maxFreq = candidateFreq;
}
}
return candidateMode;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numsLength = getPositiveIntegerInput("Enter how many numbers you want to store: ", scanner);
int[] nums = new int[numsLength];
for (int i = 0; i < numsLength; i++) {
nums[i] = getIntegerInput(String.format("Enter number %d: ", i + 1), scanner);
}
int mode = getMode(nums);
System.out.printf("Mode: %d%n", mode);
}
}
Example Usage:
Enter how many numbers you want to store: 0
Error: Integer must be positive.
Enter how many numbers you want to store: 6
Enter number 1: 3
Enter number 2: 2
Enter number 3: 5
Enter number 4: 5
Enter number 5: 3
Enter number 6: 3
Mode: 3

Can this lengthy if-else Java code be improved by using arrays?

I'm trying to simplify this Java code by adding arrays, but I'm having difficulty.
The code that I have so far that works:
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Homework4A {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
System.out.print("Enter name of the input file: ");
String fileName = scan.next();
try (Scanner inFile = new Scanner(new FileReader(fileName))) {
char number0 = '0';
char number1 = '1';
char number2 = '2';
char number3 = '3';
char number4 = '4';
char number5 = '5';
char number6 = '6';
char number7 = '7';
char number8 = '8';
char number9 = '9';
int count0 = 0;
int count1 = 0;
int count2 = 0;
int count3 = 0;
int count4 = 0;
int count5 = 0;
int count6 = 0;
int count7 = 0;
int count8 = 0;
int count9 = 0;
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) == number0) {
count0++;
}
else if (line.charAt(i) == number1) {
count1++;
}
else if (line.charAt(i) == number2) {
count2++;
}
else if (line.charAt(i) == number3) {
count3++;
}
else if (line.charAt(i) == number4) {
count4++;
}
else if (line.charAt(i) == number5) {
count5++;
}
else if (line.charAt(i) == number6) {
count6++;
}
else if (line.charAt(i) == number7) {
count7++;
}
else if (line.charAt(i) == number8) {
count8++;
}
else if (line.charAt(i) == number9) {
count9++;
}
}
}
System.out.println("\n-= Count of Thistles in =-");
System.out.println("-= the Hundred Acre Wood =-\n");
System.out.println(" -----------");
System.out.println(" type count");
System.out.println(" -----------");
System.out.println(" 0 " + count0);
System.out.println(" 1 " + count1);
System.out.println(" 2 " + count2);
System.out.println(" 3 " + count3);
System.out.println(" 4 " + count4);
System.out.println(" 5 " + count5);
System.out.println(" 6 " + count6);
System.out.println(" 7 " + count7);
System.out.println(" 8 " + count8);
System.out.println(" 9 " + count9);
System.out.println(" -----------");
}
}
}
However, it's kind of a brute-force attack. The spot of difficulty I'm running into is figuring out where to create and pass arrays. Since the code has to read the external file, should the arrays be created and passed in the while statement?
For further reference, the text file that is being read looks like this:
Thistle Map
The goal is to count the occurrences of digits only.
As you stated, you could use arrays.
I would suggest 2 arrays
One to hold the digits to catch
Second one for the counts
Initialization of the arrays
char[] numbers = new char[10];
//initialize of numbers(char) to count
for(int i = 0; i < numbers.length; i++) {
numbers[i] = (char) ('0' + i);
}
int[] counts = new int[10]; //no initialization needed because int is default 0
In the for-loop where you iterate over the line, add a nested for loop, that iterates over the numbers-array. Here is the whole while loop:
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
for(int j = 0; j < numbers.length; j++) {
if(line.charAt(i) == numbers[j]) {
counts[j]++;
}
}
}
}
For the output just use another for over the arrays:
for(int i = 0; i < numbers.length; i++) {
System.out.println(" "+ numbers[i] +" " + counts[i]);
}
Edit: Another solution using a Map
//...
Map<Character, Integer> charCounts = new HashMap<>();
for (int i = 0; i < 10; i++) {
charCounts.put((char) ('0' + i), 0);
}
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
charCounts.computeIfPresent(line.charAt(i), (key, val) -> val + 1);
}
}
//...
for (Character number : charCounts.keySet()) {
System.out.println(" " + number + " " + charCounts.get(number));
}
With this solution you can easily extend your program to count any occuring character. Just remove the initialization of the map and add this line below the computeIfPresent.
charCounts.putIfAbsent(line.charAt(i), 1);
With Java 8 you can use Files.lines to get a Stream of all the lines in a file.
Then you can transform the stream to a stream over every char using flatMap and in the end collect it to a map that has the Character as key and the count of the character as value.
try (Stream<String> stream = Files.lines(Paths.get(fileName)) {
Map<Character, Long> charCountMap = stream
.flatMap(line -> line.chars().mapToObj(c -> (char) c))
.collect(Collectors.groupingBy(c -> c, Collectors.counting()));
System.out.println(" 0 " + charCountMap.getOrDefault('0', 0));
} catch (IOException e) {
e.printStackTrace();
}
Probably the way I would do it in a real world scenario, because it's short, but just for practice the other answers are better.
Yes. I would say it can be simplified a great deal with an array. You don't need seperate sentinels for the values, you can check they are in range and then use Character.digit to parse them. Something like,
Scanner scan = new Scanner(System.in);
System.out.print("Enter name of the input file: ");
String fileName = scan.next();
try (Scanner inFile = new Scanner(new FileReader(fileName))) {
int[] count = new int[10];
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) >= '0' && line.charAt(i) <= '9') {
count[Character.digit(line.charAt(i), 10)]++;
}
}
}
System.out.println("\n-= Count of Thistles in =-");
System.out.println("-= the Hundred Acre Wood =-\n");
System.out.println(" -----------");
System.out.println(" type count");
System.out.println(" -----------");
for (int i = 0; i < count.length; i++) {
System.out.printf(" %d %d%n", i, count[i]);
}
System.out.println(" -----------");
}
You can use a single array for this and index notation. Each array index should hold the quantity of digits. Much more clear.
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Homework4A {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
System.out.print("Enter name of the input file: ");
String fileName = scan.next();
try (Scanner inFile = new Scanner(new FileReader(fileName))) {
int[] count = new int[10];
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
try {
int c = Character.getNumericValue(line.charAt(i));
count[c] += 1;
} catch (Exception e) { }
}
}
System.out.println("\n-= Count of Thistles in =-");
System.out.println("-= the Hundred Acre Wood =-\n");
System.out.println(" -----------");
System.out.println(" type count");
System.out.println(" -----------");
for (int i = 0; i < 10; i++)
System.out.println(" " + i + " " + count[i]);
System.out.println(" -----------");
}
}
}

Array out of Bounds? with string split

Array out of bounds ? i'm trying to perform the output in the picture:
Using this INPUT
"JAVA IS A PROGRAMMING LANGUAGE"
This is my code so far
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Input Phrase:");
String s = in.nextLine();
String[] word=s.split(" ");
String rts=" ";
for(int i=0;i<word.length;i++){
if(word[i].length()>=rts.length()){
rts=word[i];
}
}
int thisislength = rts.length();
for (int a = 0; a < thisislength ;a++ ) {
for (int b = 0; b < word.length ;b++ ) {
System.out.print(word[b].charAt(a)+" ");
}
System.out.println();
}
}
}
When the second word reaches its last letter it doesn't continue the for loop, is there any way to continue the loop even if the second word reaches its max length.
< should have been <=. Reversing left and right hand sides makes it more readably I think.
for (int a = 0; a < thisislength; a++) {
System.out.printf("%3d ", a+1);
for (int b = 0; b < word.length; b++) {
if (a >= word[b].length()) {
System.out.print(' ');
} else {
System.out.print(word[b].charAt(a));
}
System.out.print(' ');
}
System.out.println();
}
Or instead of the if-else statement:
for (String w : word) {
System.out.print(a >= w.length() ? ' ' : w.charAt(a));
}
This gives the result you want:
for (int a = 0; a < thisislength ;a++ ){
for (int b = 0; b < word.length ;b++ ){
if(word[b].length() < a + 1){
System.out.print(" ");
}else{
System.out.print(word[b].charAt(a) + " ");
}
}
System.out.println();
}
This line was changed:
if(word[b].length() < a + 1) and not if(word[b].length() < a)
and 2 spaces print in the if statement
TRY THIS SOLUTION HOPE IT WILL HELP YOU :
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
// GET VALUE FROM THE CONSOLE
Scanner in = new Scanner(System.in);
System.out.print("Input Phrase:");
String s = in.nextLine();
// SPLIT STRING TO WORDS
String[] words = s.split(" ");
// CREATE A LIST OF CHAR_ARRAY CALLED : matrix
List<char[]> matrix = new ArrayList<char[]>();
// REFERENCE THE LARGEST WORD IN WORDS ARRAY EX : PROGRAMMING IS THE LARGEST
int max = 0;
// FILL OUR LIST OF ARRAY OF CHARS
for (int b = 0; b < words.length ;b++ ) {
char[] chars = words[b].toCharArray();
max = (chars.length >= max)? chars.length : max ;
matrix.add( chars );
}
// PRINT OUR CHAR
for (int a = 0; a < max ;a++ ) {
for (int b = 0; b < words.length ;b++ ) {
if(a < matrix.get(b).length) {
System.out.print(matrix.get(b)[a]);
System.out.print(" ");
}else {
System.out.print(" ");
System.out.print(" ");
}
}
System.out.println("");
}
}
}

Sorting Arrays, duplicate local variable, error

I am working on this code all day, and I just can't seem to get it right :(
import java.util.Random;
import java.util.Scanner;
import java.io.*;
public class TrialSixthree{
public static void main(String[]args){
Scanner i = new Scanner(System.in);
int c;
int choice;
Random t = new Random();
for (c = 1; c <= 5; c++) {
System.out.println(t.nextInt(1000));
}
System.out.println(" \n1: BUBBLE SORT ");
System.out.println(" 2: SELECTION SORT ");
System.out.println(" 3: QUICK SORT ");
System.out.println(" Choose a number from 1-3 ");
choice= i.nextInt();
if(choice == 1){
System.out.print("You chose BUBBLE sort!");
System.out.println(x[i]+"");//I don't know what's wrong in this line
for(int i = 0 ; i < x.length-1 ; i++){
for (int j = 0 ; j < x.length-1 ; j++){
if ( x[j] > x[j]){
temp = x[j];
x[j] = x[j+1];
x[j+1] = temp;
}
}
}
} else if(choice == 2){
System.out.print("You chose SELECTION sort!");
System.out.println(x[i]+"");
int temp, min;
for(int i=0;i<x.length-1;i++) {
min = i;
for(int j=i+1;j<x.length;j++) {
if(x[min]>x[j]) {
min = j;
}
if(min!=i) {
temp = x[min];
x[min] = x[i];
x[i] = temp;
}
}
}
} else if(choice == 3){
System.out.println("You chose QUICK sort!");
System.out.println(x[i]+"");
int temp;
for(int i=0;i<x.length-1;i++) {
for(int j=i+1;j<x.length;j++) {
if(x[i]>x[j]) {
temp = x[i];
x[i] = x[j];
x[j] = temp;
}
}
}
} else {
System.out.println("Not in the choices!");
}
}
}
I just can't seem to get this right. I'm still new to java. There's an error that says duplicate local variable. It's my homework. Please help me :(
You declared i twice :
Scanner i = new Scanner(System.in);
and
for(int i = 0 ; i < x.length-1 ; i++)
I suggest you give the Scanner variable a more meaningful name.
You are used a i variable in multiple time
So rename a i variable
Scanner i=new Scanner(System.in);
Rename a i varible
Scanner scan=new Scanner(System.in);

Lonely Integer - Output is correct. But still getting additional message

Im trying to find the lonely integer in an array. My output is correct, but still getting the extra message. Please have a look at the code. I’m using Java to write the program.
Code:
import java.util.InputMismatchException;
import java.util.Scanner;
public class LonelyInteger {
private static int inputArray[];
private static int inputLength;
private static final Scanner scanner = new Scanner(System.in);;
public static void main(String[] args) {
try {
if (getInput()) {
sortAndPrintArray();
findLonelyInteger();
} else {
System.out.println("OOPS, something is not right! Try again!");
}
} catch (NumberFormatException | InputMismatchException nfime) {
System.out.print("Number Format Exception or Input Mismatch Exception Occured: " + nfime);
} catch (Exception e) {
System.out.print("Exception Occured: " + e.getMessage());
}
}
private static boolean getInput() throws NumberFormatException, InputMismatchException, Exception {
System.out.print("Enter the array length: ");
inputLength = scanner.nextInt();
if (inputLength <= 0) {
return false;
}
inputArray = new int[inputLength];
System.out.println("Enter the array:");
for (int i = 0; i < inputLength; i++) {
inputArray[i] = scanner.nextInt();
}
return true;
}
private static void sortAndPrintArray() {
sortArray();
printSortedArray();
}
private static void sortArray() {
int temp = 0;
for (int i = 0; i < inputLength; i++) {
for (int j = 0; j < i; j++) {
if (inputArray[i] < inputArray[j]) {
temp = inputArray[i];
inputArray[i] = inputArray[j];
inputArray[j] = temp;
}
}
}
}
private static void printSortedArray() {
System.out.println("Sorted Array:");
for (int i = 0; i < inputLength; i++) {
System.out.print(inputArray[i] + " ");
}
System.out.println();
}
private static void findLonelyInteger() {
boolean foundLonelyInteger = false;
for (int i = 0; i < inputLength; i++) {
if ((i+1) == inputLength) {
System.out.println("Lonely Integer: " + inputArray[i]);
break;
}
if (inputArray[i] == inputArray[++i]) {
continue;
} else {
System.out.println("Lonely Integer: " + inputArray[i-1]);
foundLonelyInteger = true;
i--;
}
}
if (!foundLonelyInteger) {
System.out.println("Lonely integer not available!");
}
}
}
Here is my output, which is seen in Command Prompt:
Output:
Enter the array length: 5
Enter the array:
1
2
2
1
2
Sorted Array:
1 1 2 2 2
Lonely Integer: 2
Lonely integer not available!
You did not set the flag, in your findLonelyInteger() method's first if condition!
if ((i+1) == inputLength) {
System.out.println("Lonely Integer: " + inputArray[i]);
foundLonelyInteger = true; // --> HERE
break;
}
Command Prompt? Start using Eclipse! And learn debugging!
Set your foundLonelyInteger = true; while you are checking for if((i+1) == inputLength)

Categories