I keep getting error:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at Result.gradingStudents(Solution.java:32)
at Solution.main(Solution.java:83)"
This was a challenge on hackerrank.I have replaced nextInt() with nextLine() as per some other answers but it doesn't fix the problem.
Also using "hasNext()"/ "hasNextLine()" will just skip asking for input.
I tried an online compiler where I put the code directly in main function, is that the problem, and that worked.
Also tried Buffer reader but that is giving me an error aswell.
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import java.util.Scanner;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
class Result {
public static List<Integer> gradingStudents(List<Integer> grades)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of students :");
int n=0, tempGrade=0;
List<Integer> returnGrades = new ArrayList<Integer>();
String num = scanner.nextLine();
n = Integer.parseInt(num);
System.out.println("Enter their grades :");
for(int i=0;i<n;i++)
{
String tempSGrade = scanner.nextInt();
tempgrade = Integer.parseInt(tempSGrade);
grades.add(tempGrade);
}
for(int i=0; i<n; i++)
{
int item = grades.get(i);
if (item >= 38)
{
if((item+2)%5==0)
{
item=item+2;
}
}
returnGrades.add(item);
}
return returnGrades;
}
}
public class Solution {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int gradesCount = Integer.parseInt(bufferedReader.readLine().trim());
List<Integer> grades = IntStream.range(0, gradesCount).mapToObj(i -> {
try {
return bufferedReader.readLine().replaceAll("\\s+$", "");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
})
.map(String::trim)
.map(Integer::parseInt)
.collect(toList());
List<Integer> result = Result.gradingStudents(grades);
bufferedWriter.write(
result.stream()
.map(Object::toString)
.collect(joining("\n"))
+ "\n"
);
bufferedReader.close();
bufferedWriter.close();
}
}
You are trying to read the user inputs twice as the input values are already being read in the main function. So, you don't need to scan the inputs again in the method. You are only supposed to implement the gradingStudents.
Your approach for solving the problem also seems to be wrong.
You can find the next multiple of 5 as:
int nextMultipleOf5 = (item/5 + 1) * 5;
Related
I am trying to take an integer as user input and store it in a list until the user hits 'q'. At the moment the user inputs 'q', the loop gets terminated.
The code is showing an InputMismatch error:
import java.util.*;
public class SampleArrayList {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s;
int n;
List<Integer> array = new ArrayList();
while (true) {
n = sc.nextInt();
s = sc.nextLine();
if (s.equals("q")) {
break;
} else {
array.add(n);
}
}
Collections.sort(array);
System.out.println(array);
}
}
Just try this,
Inside your while loop to get input for a string use,
s = sc.next();
Instead of sc.nextLine();.
Are you trying to implement it like the example below?
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s;
List<Integer> array = new ArrayList();
while (true) {
s = sc.nextLine();
if (s.equalsIgnoreCase("q")) {
break;
}
int num = Integer.parseInt(s);
array.add(num);
}
Collections.sort(array);
System.out.println(array);
}
}
Looks like q is trying to be stored as an int, so this should work:
All numbers stored as a String can be parsed as an int with the parseInt() method.
s = sc.nextLine();
if (!s.equals("q"))
{
array.add(Integer.parseInt(s));
}
else
{
break;
}
I'm creating a program made up of two java files. The first one involves creating a class that accepts a binary from the user and returns its decimal value. The second involves creating a class that reads a list of binary strings from a text file and writes their decimal values to the console. This class should call methods from the first java class in order to achieve its tasks, and should be able to indicate if one of the strings in this file is not binary.
I have the first java class completed, but I'm having difficulty on the second, specifically on how I can get the program to read each individual String from the text file and then either print out their values or declare that they are not a binary. I also need some help on how to call methods from the first class. Could someone help lead me in the right direction?
Here are both codes:
Class 1:
import java.util.*;
public class BinaryDecoder {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a binary: ");
String binary = input.nextLine();
System.out.println("---------------");
boolean isBinary = binaryDetector(binary);
if(isBinary) {
int count = 0;
for(int i=0; i<binary.length(); i++) {
if(binary.charAt(i) != ' ') {
count++;
}
}
int binarySize = Integer.valueOf(count);
System.out.println("Binary size: " + binarySize);
int decimalValue = binaryToDecimal(binary);
System.out.println("Value = " + decimalValue);
}
else {
System.out.println("Not a binary");
}
}
public static boolean binaryDetector(String x) {
int copyOfInput = Integer.valueOf(x);
while(copyOfInput != 0) {
if(copyOfInput % 10 > 1) {
return false;
}
copyOfInput = copyOfInput/10;
}
return true;
}
public static int binaryToDecimal(String n) {
String num = n;
int dec_value = 0;
int base = 1;
int len = num.length();
for(int i = len - 1; i>= 0; i--) {
if(num.charAt(i) == '1') {
dec_value += base;
}
base = base * 2;
}
return dec_value;
}
}
Class 2
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class BinaryToDecimalTester {
public static void main(String[] args) throws Exception{
Scanner inFile = new Scanner(new File("Strings.txt"));
while(inFile.hasNext()) {
String inString = inFile.next();
}
}
}
And let's say for reference that the text file has these numbers in it:
1011010011101
1011101110101
1201234000100
1234456000110
1011010100011
Please let me know if you need any more clarification or information. Thank you all very much!
In order to use methods from BinaryDecoder in BinaryToDecimalTester you will have to import them. The best way would be to declare package in each class and import that using it, for example
Decoder class:
package binarynumbers;
import java.util.*;
public class BinaryDecoder {
public static void main(String[] args) { ...
and then import specific ( or all ) methods in BinaryToDecimalTester:
package stackoverflow;
import java.io.File;
import java.util.Scanner;
import static stackoverflow.BinaryDecoder.binaryToDecimal;
public class BinaryToDecimalTester { ...
importing it this way lets you use it normally as you woud expect :
System.out.println(binaryToDecimal(inString));
Concept of packages and imports is more complicated than this and essential to writing programs.
As to reading each individual line as String from the text file and processing it your class is sufficient, FileInputReader is one of another options to read from file. My example would be this:
package binarynumbers;
import java.io.BufferedReader;
import java.io.FileReader;
import static binarynumbers.BinaryDecoder.binaryToDecimal;
import static binarynumbers.BinaryDecoder.binaryDetector;
public class BinaryToDecimalTester {
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new FileReader("Strings.txt"));
String line = "";
while ((line = br.readLine()) != null)
{
System.out.println(binaryDetector(line));
System.out.println(binaryToDecimal(line));
}
}
}
in terms of implementing method detecting binary numbers I can suggest this article
You have to select which class should be your main.
If you keep 2 as your main and then instead of main in 1 you can read both files in 2 and used the static methods you have created in 1 by importing them in 2.
import BinaryDecoder.binaryToDecimal;
I would recommend you do the check for a binary digit as you try to convert the value. Then throw an exception and print the message if the digit is not binary.
There is no need to first check and then convert the value.
Here is an easy way to do the conversion.
public static int binaryToDecimal(String n) {
int val = 0;
for(char c : n.toCharArray()) {
if (c != '1' && c != '0') {
throw new IllegalArgumentException("Number not binary");
}
val = val*2;
val += c-'0';
}
return val;
}
Now all you need to do is read in the values and call the method. In lieu of the exception you could also return an optional.
public static OptionalInt binaryToDecimal(String n) {
int val = 0;
for(char c : n.toCharArray()) {
if (c != '1' && c != '0') {
return OptionalInt.empty();
}
val = val*2;
val += c-'0';
}
return OptionalInt.of(val);
}
Now just check to see if the returned Optional is empty before you print the result. To read in the values from a file, I would recommend using a scanner instance. Here is an example using the data mentioned in your question along with the required imports.
import java.io.File;
import java.io.IOException;
import java.util.OptionalInt;
import java.util.Scanner;
try (Scanner input = new Scanner(new File("f:/numbers.txt"))) {
while (input.hasNextLine()) {
String str = input.nextLine();
OptionalInt op = binaryToDecimal(str);
System.out.printf("%s -> %s%n", str, op.isPresent() ?
op.getAsInt() : "Non binary string");
}
} catch (IOException ie) {
ie.printStackTrace();
}
prints
1011010011101 -> 5789
1011101110101 -> 6005
1201234000100 -> Non binary string
1234456000110 -> Non binary string
1011010100011 -> 5795
I'm new to Java coding, and I'm stuck with a simple ArrayList sum code. I believe that my method is correct, but I don't understand the main method. I tried to run it many times, but it keeps saying that my input, ArrayList ar, is not 'identified'. Help needed!
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
public class Solution {
/*
* Complete the simpleArraySum function below.
*/
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new
FileWriter(System.getenv("OUTPUT_PATH")));
int arCount = Integer.parseInt(scanner.nextLine().trim());
int[] ar = new int[arCount];
String[] arItems = scanner.nextLine().split(" ");
for (int arItr = 0; arItr < arCount; arItr++) {
int arItem = Integer.parseInt(arItems[arItr].trim());
ar[arItr] = arItem;
}
int result = simpleArraySum(ar);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedWriter.close();
}
// Below is my code
public static int simpleArraySum(int n, ar) {
/** It says that 'ar' is not identified. I tried
'Arraylist<Integer>
* ar but it still won't work
int sum = 0;
for (int i = 0; i < ar.size(); i++) {
sum += ar.get(i);
}
return sum;
}
}
This is what it returns:
Compile Message:
Solution.java:39: error: <identifier> expected
public static int simpleArraySum(int n, ar) {
^
1 error
The declaration of type of parameters for the method simpleArraySum is missing.
Try the following signature, it should work
public static int simpleArraySum(int n,int[] ar) {
I'm programming in Java. I'm not good at programming, but I'm trying.
I managed to create a file that generates an array of 10k random (in range 1 through 1 million) numbers into a text file. This class is called 'CreateDataFile'
What I'm trying to do now is read the array from the text file created in 'CreateDataFile' from a completely different class. This new class is called 'ProcessDataFile'
The first thing I thought about doing is 'extends' the class. So both classes communicate.
The thing is, I know how to create a for loop in a program and then find the largest number. I just don't understand how to read this text file, and create a for loop that processes from the text file and finds the max value.
Here's my CreateDataFile class
import java.io.*;
import java.util.Random;
public class CreateDataFile {
public static void main(String[] args) {
int [] integers = new int[10000];
Random r = new Random();
try{
PrintWriter p = new PrintWriter("dataset529.txt");
for (int i = 0; i <integers.length; i++) {
int number = r.nextInt(1000000)+1;
p.print(" " + number);
}
p.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Now this generates the numbers I need into a text file called dataset529.
If everything was in one class, I'd just create a for loop.. something like
int max = integers[0];
for(int i = 0; i<integers.length; i++){
if (integers[i] > max)
System.out.println(integers[i]);
}
But as I'm creating my ProcessDataFile class, I'm having a hard time reading the text file created from the CreateDataFile class.
Any ideas on how I can read this text file and run a for loop over it to find the max number like I used above?
Thanks, any help would be appreciated.
First of all, you should write in the file each number on one line so that it's easier when you read the numbers from the file. This can be done just by doing:
p.print(number + "\n");
After that, you can use this code to get the max of all the numbers:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ProcessDataFile {
public static void main(String[] args) throws IOException {
String fileName = "dataset529.txt";
String temp;
int max = Integer.MIN_VALUE;
int i = 0;
int[] numbers = new int[10000];
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
while((temp = br.readLine()) != null) {
if(temp.isEmpty())
break;
numbers[i++] = Integer.parseInt(temp);
}
}
for(i = 0; i < numbers.length; i++)
if(max < numbers[i])
max = numbers[i];
System.out.println(max);
}
Write the content of each number on new line. While reading the file, maintain a max element.
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
public class CreateDataFile {
public static void main(String[] args) {
int[] integers = new int[10000];
Random r = new Random();
try {
PrintWriter p = new PrintWriter("dataset529.txt");
for (int i = 0; i < integers.length; i++) {
int number = r.nextInt(1000000) + 1;
p.print(number + "\n");
}
p.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Now read the file line by line.
public class ProcessDataFile {
public static void main(String[] args) throws IOException {
int max = Integer.MIN_VALUE;
String line = null;
BufferedReader br = new BufferedReader(new FileReader("dataset529.txt"));
while ((line = br.readLine()) != null) {
int num = Integer.parseInt(line);
if (max < num) {
max = num;
}
}
}
System.out.println(max);
}
Got an Error with NullPointerException . (cs106A handout 6 - Name Count using hash map)
Debugger told me the problem located # String input variable. I got no idea how to solve it.
thanks for reading.
import acm.io.*;
import acm.program.*;
import acm.util.*;
import java.util.*;
import java.io.*;
import java.io.BufferedReader.*;
import java.lang.*;
public class NameCounts extends ConsoleProgram{
// hashmap
static HashMap<String,Integer> myUniq = new HashMap<String,Integer>();
static String input ;
static public void insertName(){
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true){
System.out.println("Enter name:");
// if keyboard input contain new unique name ,
// store it in the hashmap and count the value +1
input = br.readLine();
if(input.equals("")) break;
if( myUniq.containsKey(input) ==false){
Integer temp = myUniq.get(input);
temp = temp + 1;
myUniq.put(input,temp);
}
}
}
catch (IOException e){ };
}
// print and show every single hash map and count value
static public void releaseUnique(){
for(int i= 1 ; i < myUniq.size() ; i++){
System.out.println("Entry"+"[" + input + "]"+"has count"+myUniq.get(input));
}
}
public static void main (String[] args){
insertName();
releaseUnique();
}
}
I think you should change
if( myUniq.containsKey(input) ==false){
Integer temp = myUniq.get(input);
temp = temp + 1;
myUniq.put(input,temp);
}
to
if(myUniq.containsKey(input)) {
Integer temp = myUniq.get(input);
temp = temp + 1;
myUniq.put(input, temp);
} else {
myUniq.put(input, 1);
}