InputMismatch error trying to take integer as user input - java

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;
}

Related

NoSuchElementException in Java. Grading Students Problem on Hackerrank

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;

I am trying to make a for loop with a if statement in it to find a specific name in an arraylist

I have a scanner for input to find a name in an arraylist but when i try to use the .get method it says it can only do that with integers is there any way to get the persons input to == names(i)?
here is my code
import java.util.ArrayList;
import java.util.Scanner;
public class Searching {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<String> names = new ArrayList<String>();
names.add("Liam");
names.add("Noah");
names.add("William");
names.add("James");
names.add("Logan");
names.add("Benjamin");
names.add("Mason");
names.add("Elijah");
//Part 1
System.out.println("Please pick a name:");
Scanner input = new Scanner(System.in);
String sentence = input.nextLine();
int counter = 0;
for (String i : names)
{
if (sentence = names.(i))
{
}
counter++;
}
}
}
I think what you have to do, is
for (String name : names) //change i to name (for better readability)
{
if (name.equals(sentence))
{
}
counter++;
}
and i is of type String, ArrayList::get method gets an int.

For every services I'm getting same price (output)

import java.util.Scanner;
import java.util.Arrays;
public class CarCareChoice{
public static void main(String[] args) {
String[] choices=new String[5];
int j ;
boolean validItem=false;
double price=0.0;
int p;
String str;
//When i'm entering services I'm getting 5.o for all services plz help
String[] services={"Am","Bm","Cm","Dm","Em"};
double prices[]={1.0,2.0,3.0,4.0,5.0};
//Scanner
Scanner input = new Scanner(System.in);
System.out.println("enter");
str= input.nextLine();
for(j = 0; j < choices.length;j++){
if(Arrays.asList(services).contains(str)){
validItem=true;
price=prices[j];
}
}
if (validItem)
System.out.println("service"+""+price);
else
System.out.println("Invalis enter");
}
}
output
enter
Am
service5.0
output
enter
Bm
service5.0
when I enter Am i supposed to get 1.0 for "Bm 2.0 and etc but I'm getting only 5.0
You rather improve your code as following:
System.out.println("enter");
List<String> choiceList = Arrays.asList(services);
str= input.nextLine();
int index = choiceList.indexOf(str);
if ( index!=-1 )
{
price = prices[i];
validItem = true;
}
if (validItem)
System.out.println("service"+""+price);
else
System.out.println("Invalis enter");
You need not do this in for loop. Because when you have converted your array to a list then just find the index. If that is -1 then its definitely not a valid item else return the price at that index of the array. ArrayList is backed by an array internally.
import java.util.Arrays;
class Main {
public static final int INVALID_INDEX = -1;
public static void main(String[] args) {
String[] services={"Am","Bm","Cm","Dm","Em"};
double prices[]={1.0,2.0,3.0,4.0,5.0};
String input = "Em";
int index = Arrays.asList(services).indexOf(input);
System.out.println((index!=INVALID_INDEX)? prices[index]+"":"invalid input");
}
}
Use a Map<String,Double> instead if possible.

Why is this code getting a Java NoSuchElement exception?

I have traced through this code and can't figure out how to fix it. When running the code why wouldn't the user be prompted for input rather than Java determining that there is no input? Error trace below.
import java.util.*;
public class SortAsInserted {
public static void main(String[] args) {
int array_size = GetArraySize();
//System.out.println(array_size);
String[] myArray = new String[array_size];
for (int i = 0; i < array_size; i++){
String next_string = GetNextString();
System.out.println(next_string);
}
}
//public static String[] SortInsert(String nextString){
//}
public static int GetArraySize(){
Scanner input = new Scanner(System.in);
System.out.print("How many items are you entering?: ");
int items_in_array = input.nextInt();
input.close();
return items_in_array;
}
public static void PrintArray(String[] x) {
for (int i = 0; i < x.length; i++){
System.out.print(x[i]);
}
}
public static String GetNextString(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the next string: ");
String next_string = input.nextLine();
input.close();
return next_string;
}
Here is the error --
How many items are you entering?: 2
Enter the next string:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at SortAsInserted.GetNextString(SortAsInserted.java:40)
at SortAsInserted.main(SortAsInserted.java:10)
The simple answer is when you close Scanner -- underlying input stream also closes:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#close()
To fix this create Scanner once in main:
public class SortAsInserted {
static Scanner input;
public static void main(String[] _) {
input = new Scanner(System.in);
....
input.close();
}
Remove input.close(); from the code
Removing the scanner.close() method from two functions will solve your problem.
import java.util.*;
public class SortAsInserted {
public static void main(String[] args) {
int array_size = GetArraySize();
//System.out.println(array_size);
String[] myArray = new String[array_size];
for (int i = 0; i < array_size; i++){
String next_string = GetNextString();
System.out.println(next_string);
}
}
//public static String[] SortInsert(String nextString){
//}
public static int GetArraySize(){
Scanner input = new Scanner(System.in);
System.out.print("How many items are you entering?: ");
int items_in_array = input.nextInt();
//input.close();
return items_in_array;
}
public static void PrintArray(String[] x) {
for (int i = 0; i < x.length; i++){
System.out.print(x[i]);
}
}
public static String GetNextString(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the next string: ");
String next_string = input.nextLine();
// input.close();
return next_string;
}
}

Display Selected Message String

I'm working on a method that goes through all of my array messages and displays the selected message. I'm new to Java so I'm still trying to figure out methods and Arrays. When I run this, it says that it's successful but it doesn't display anything. Can someone help me figure this out.
package chatbox;
import java.util.Scanner;
public class ChatBox
{
public static void main(String[] args)
{
String chatMessages[] = new String[10];
//declare arrays
chatMessages[0]= "Pepperoni";
chatMessages[1]= "Olives";
chatMessages[2]= "Cheese";
chatMessages[3]= "Onions";
chatMessages[4]= "Bacon";
chatMessages[5]= "Tomato sauce";
chatMessages[6]= "Bell peppers";
chatMessages[7]= "Mushrooms";
chatMessages[8]= "Sausage";
chatMessages[9]= "Beef";
}
Scanner scan = new Scanner (System.in);
public Scanner chatCannedMessage(String chatMessages)
{
for (int i=0;i<chatMessages.length;i++){
System.out.println(chatMessages[i]); //Prints Message
}
System.out.println("Select a message");
String chatMessage = scan.next();
scan.nextLine();
return scan;
}
}
As PM 77-1 said, you never invoked your shoutOutCannedMessage method and also never print out or return any string.
I tried to minimize changes to your code, and I think this might be what you intended to do.
import java.util.Scanner;
public class ShoutBox {
Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
String messages[] = new String[10];
//declare 10 arrays
messages[0] = "Pepperoni";
messages[1] = "Olives";
messages[2] = "Cheese";
messages[3] = "Onions";
messages[4] = "Bacon";
messages[5] = "Tomato sauce";
messages[6] = "Bell peppers";
messages[7] = "Mushrooms";
messages[8] = "Sausage";
messages[9] = "Beef";
String m = new ShoutBox().shoutOutCannedMessage(messages);
System.out.println(m);
}
public String shoutOutCannedMessage(String[] messages) {
for (int i = 0; i < messages.length; i++) {
System.out.println(i+". "+messages[i]); //Should print the messages
}
System.out.println("Select a message");
int idx = scan.nextInt();
String message = messages[idx];
return message;
}
}

Categories

Resources