Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
Improve this question
import java.util.*;
import java.util.Map.Entry;
public class fff2 {
public static void main(String[] args) throws NullPointerException{
try {
LinkedHashMap<String, Integer> score = new LinkedHashMap<String,Integer>();
score.put("Fail",39);
score.put("Third Class", 49);
score.put("Second Class, Division 2",59);
score.put("Second Class, Division 1",69);
score.put("First Class",70);
Scanner scan = new Scanner(System.in);
System.out.println("What was your mark?");
int mark = scan.nextInt();
if(mark >100 && mark < 0) {
System.out.println("Invalid Input: out of range.");
}
for(String i: score.keySet()) {
if(mark< score.get(i)) {
System.out.println("You got a "+i);
break;
}
}
}
catch(InputMismatchException e) {
System.out.println("Invalid Input, program terminating");
}
}
So I am trying to make a grading system but it isn't working can i have some help please? I am trying to make it so that a mark of 40 is a pass as a third class but i want to use a hashmap to challenge myself as opposed to the switch case.
I assume you want something like this:
LinkedHashMap<String, Integer> score = new LinkedHashMap<String,Integer>();
score.put("Fail",39);
score.put("Third Class", 49);
score.put("Second Class, Division 2",59);
score.put("Second Class, Division 1",69);
score.put("First Class",70);
Scanner scan = new Scanner(System.in);
System.out.println("What was your mark?");
String keyScore = scan.nextString();
System.out.println(score.getOrDefault(keyScore, "Invalid Input: key not in map"));
where on input you put one of the keys from the map, and not the value.
Replace
score.put("First Class",70);
with
score.put("First Class",100);
and also replace
if(mark< score.get(i)) {
with
if(mark<= score.get(i)) {
import java.util.*;
public class fff {
public static void main(String[] args) throws NullPointerException{
try {
LinkedHashMap<Integer, String> score = new LinkedHashMap<Integer,String>();
score.put(70, "First class");
score.put(59, "Second Class, Division 1");
score.put(49, "Second Class, Divison 2");
score.put(39, "Third Class");
Scanner scan = new Scanner(System.in);
System.out.println("What was your mark?");
int mark = scan.nextInt();
if(mark >100 && mark < 0) {
System.out.println("Invalid Input: out of range.");
}
for(Integer i: score.keySet()) {
if(mark <= 39) {
System.out.println("You got a Fail");
System.exit(0);
}
if(mark>=i) {
System.out.println("You got a "+score.get(i));
break;
}
}
}
catch(InputMismatchException e) {
System.out.println("Invalid Input, program terminating");
}
}
}
This is my final code and it now works.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have a console application with a main method and some methods that I call from main. There, I want to ask the user for some input, for which I use the Scanner class.
Here's my problem:
I find there is no way to use Scanner when reading inputs from outside main without random exceptions or unexpected behaviour. I have tried two approaches:
Having a Scanner global variable in the class containing main. Then
I use this same Scanner in all functions in that same class.
In every function I need to ask for input, I declare a new Scanner
variable, use it, and close it before exiting the function.
1. makes Scanner try to read twice. I mean, I have a sc.readLine in a function and, when I exit that function, I have another sc.readLine in main. I input once and the two readLine lines get executed, the second one reading an empty String.
2. throws Exception (base class Exception) when I call any sc.readLine for a second time during the execution of the program.
I have also noticed that any other method other than readLine is going to read various items on the same line. For example, line "10 20 30 40" would execute 4 sc.nextInt calls.
TL;DR: how do you use Scanner in a console application?
One way:
import java.util.Scanner;
public class Main {
private Scanner scanner = new Scanner(System.in);
public Scanner getScanner() {
return scanner;
}
void fun1() {
Scanner in = getScanner();
System.out.print("Enter a string: ");
System.out.println("You entered: " + in.nextLine());
}
void fun2() {
Scanner in = getScanner();
System.out.print("Enter an integer: ");
int n = 0;
try {
n = Integer.parseInt(in.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
System.out.println(n + " + 10 = " + (n + 10));
}
public static void main(String[] args) {
Main m = new Main();
m.fun1();
m.fun2();
}
}
A sample run:
Enter a string: Hello world!
You entered: Hello world!
Enter an integer: 25
25 + 10 = 35
Another way:
import java.util.Scanner;
public class Main {
static void fun1(Scanner in) {
System.out.print("Enter a string: ");
System.out.println("You entered: " + in.nextLine());
}
static void fun2(Scanner in) {
System.out.print("Enter an integer: ");
int n = 0;
try {
n = Integer.parseInt(in.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
System.out.println(n + " + 10 = " + (n + 10));
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
fun1(in);
fun2(in);
}
}
A sample run:
Enter a string: Hello world!
You entered: Hello world!
Enter an integer: 25
25 + 10 = 35
Regarding your problem with next() or nextInt(): Given below is the recommended way for multiple inputs in one go.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean valid = true;
System.out.print("Enter some intgers: ");
String strNum = in.nextLine();
String[] strNumArr = strNum.split("\\s+");
int[] numArr = new int[strNumArr.length];
for (int i = 0; i < strNumArr.length; i++) {
try {
numArr[i] = Integer.parseInt(strNumArr[i]);
} catch (NumberFormatException e) {
numArr[i] = Integer.MIN_VALUE;
valid = false;
}
}
System.out.println(Arrays.toString(numArr));
if (!valid) {
System.out.println("Note: invalid inputs have been reset to " + Integer.MIN_VALUE);
}
}
}
A sample run:
Enter some intgers: 10 5 20 15
[10, 5, 20, 15]
Another sample run:
Enter some intgers: 4 40 a 20 b 15
[4, 40, -2147483648, 20, -2147483648, 15]
Note: invalid inputs have been reset to -2147483648
Check Scanner is skipping nextLine() after using next() or nextFoo()? for more information about console input using Scanner.
to use a single instance of Scanner (or any other datatype or class), you can use the design pattern "Singleton" which consist to instantiate a single instance of your Object for the whole project.
The Singleton definition (a new class) :
import java.util.Scanner;
public class ScannerSingleton {
private static Scanner sc = null;
private ScannerSingleton() {
sc = new Scanner(System.in);
}
public static Scanner getInstance() {
if (sc == null) {
synchronized(ScannerSingleton.class) {
if (sc == null)
sc = new ScannerSingleton();
}
}
}
}
and each time you want to use your scanner anywhere you only have to call ScannerSingleton.getInstance() which will return your single instance of scanner
example of use:
String test = ScannerSingleton.getInstance().nextLine();
I suggest to pass your Scanner object as another parameter for your functions.
public static void main(String[] args)
{
Scanner scanner=new Scanner(System.in);
String answer = ask(scanner, "what is your name?");
System.out.println("Oh! Hello dear " + answer + "!");
scanner.close();
}
private static String ask(Scanner scanner, String question)
{
System.out.println(question);
return scanner.nextLine();
}
This question already has answers here:
How do I make my program repeat according to certain circumstances?
(3 answers)
Closed 4 years ago.
Hello everyone i just started programming with java but i have kinda a problem question i am making a game where the user needs to put in a a number between 1 and 9 if the user puts a number under 1 or above 9 it gives an error and the user needs to put in a number again but when the user puts in a invalid number the program gives an error and stops working how can i fix this?
My code
public void game()
{
Scanner inputnumber = new Scanner(System.in);
System.out.println("Please select a number (1-9): ");
int number = inputnumber.nextInt();
if (number <1 || number > 9)
{
System.out.println("Please select a number: " + number);
System.out.println("This value is out of range. Please enter a value between 1 and 9.");
while (number <1 || number > 9)
{
return;
}
}
else{
System.out.println("That is a valid entry!");
}
}
}
This would also serve the purpose.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner inputnumber = new Scanner(System.in);
int n;
do{
System.out.println("Please select a number (1-9): ");
n = inputnumber.nextInt();
} while ( n >= 1 && n <= 9);
}
}
you can use a do while loop for this.
todo Handle exceptions to support your use case.
One thing which you can try is to use try catch block.
For example :
public class ab {
int inputNumber;
public static void main(String[] args) {
// TODO Auto-generated method stub
takeInput();
}
public static void takeInput()
{
Scanner inputnumber = new Scanner(System.in);
System.out.println("Please select a number (1-9): ");
try {
int number = inputnumber.nextInt();
if (number >=1 && number <=9) {
System.out.println("Valid Number");
}
else
{
takeInput();
}
}
catch (Exception e) {
// TODO: handle exception
System.out.println("Invalid number");
takeInput();
}
}
}
I am tasked to develop a program that prompts users to create their own questions and answers, which will be stored into the arrayList. After that, whenever the user types the same question, the program will automatically extract the answer.
What I did so far: I manage to store the questions and answers into the arrayList, but I have no idea how to trigger the program to extract exact answer when the user asked the question that he had just created. Here are my codes :
import java.util.ArrayList;
import java.util.Scanner;
public class CreateQns {
public static void main(String[] args) {
String reply;
ArrayList qns = new ArrayList();
ArrayList ans = new ArrayList();
System.out.println("Type 0 to end.");
do {
Scanner input = new Scanner (System.in);
System.out.println("<==Enter your question here==>");
System.out.print("You: ");
reply = input.nextLine();
if(!reply.equals("0")) {
qns.add(reply);
System.out.println("Enter your answer ==>");
System.out.print("You: ");
ans.add(input.nextLine());
}
else {
System.out.println("<==End==>");
}
}while(!reply.equals("0"));
}
}
You may use a HashMap<String, String> which stores Key/value
The user enter a question, check if it is in the map, if yes print the answer, if not ask the answer and store it :
public static void main(String[] args) {
String reply;
HashMap<String, String> map = new HashMap<>();
System.out.println("Type 0 to end.");
do {
Scanner input = new Scanner(System.in);
System.out.println("<==Enter your question here==>");
System.out.print("You: ");
reply = input.nextLine();
if (!reply.equals("0")){
if (map.containsKey(reply)) // if question has already been stored
System.out.println(map.get(reply)); // print the answer
else {
System.out.println("Enter your answer ==>");
System.out.print("You: ");
map.put(reply, input.nextLine()); // add pair question/answer
}
}else{
System.out.println("<==End==>");
}
} while (!reply.equals("0"));
}
But to answers directly to what you ask, instead of the map.contains() you should do :
int index;
if ((index = qns.indexOf(reply)) >= 0){
System.out.println(ans.get(index));
}
But that is less convenient, less powerfull than Map
Please find the code without using the HashMap.
import java.util.ArrayList;
import java.util.Scanner;
public class CreateQns {
public static void main(String[] args) {
String reply;
ArrayList<String> qns = new ArrayList();
ArrayList<String> ans = new ArrayList();
System.out.println("Type 0 to end.");
do {
Scanner input = new Scanner (System.in);
System.out.println("<==Enter your question here==>");
System.out.print("You: ");
reply = input.nextLine();
if(!reply.equals("0")) {
if(qns.contains(reply))
{
System.out.println("your answer is==>"+ans.get(qns.indexOf(reply)));
}
else
{
qns.add(reply);
System.out.println("Enter your answer ==>");
System.out.print("You: ");
ans.add(input.nextLine());
}
}
else {
System.out.println("<==End==>");
}
}while(!reply.equals("0"));
}
}
You need to use a Map<String, String> to correlate the question you are asking to the response the user typed in for it.
Your code should say: if the questions map contains the question the user just typed in, then print the value associated to the question in the map, otherwise ask the user to type and answer and add the question/answer to the map.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
7267881 is in my file as an account and after the file is scanned if you do
System.out.println(Account[2][1]);
it prints back 7267881, but when prompted if the user enters 7267881 it returns that it is an invalid number... all the other account numbers in the file work just not this one... why?
import java.io.File;
import java.util.Scanner;
public class AcccountArray {
public static void main(String[] args)
{
//Scan the file and save account details to array
File file = new File ("customers.txt");
System.out.println("Path : " + file.getAbsolutePath());
try{
Scanner scanner = new Scanner(new File("customers.txt"));
String[][] Account = new String[Integer.valueOf(scanner.nextLine())][3];
for(int i=0;i<Account.length;i++)
{
Account[i][0]=scanner.nextLine();
Account[i][1]=scanner.nextLine();
Account[i][2]=scanner.nextLine();
}
scanner.close();
System.out.println(Account[2][1]);
Scanner userinput = new Scanner(System.in);
System.out.println("Please enter account number: ");
String accountNumber = userinput.next();
int matchindex = 0;
Boolean match = false;
for (int k =0;k<Account.length;k++)
{
if(Account[k][1].equals(accountNumber))
{
match = true;
matchindex = k;
}
}
if(match)
{
Account ac = new Account();
ac.toString(Account[matchindex][0], Account[matchindex][1], Account[matchindex][2]);
System.out.println("Enter 'D' for deposite\nEnter 'W' for withdrawal\nEnter 'Q' for quit");
Scanner transaction = new Scanner(System.in);
String type = transaction.next();
Scanner ammount = new Scanner(System.in);
switch (type) {
case "D":
System.out.println("Enter the ammount : ");
float diposit = ammount.nextFloat();
float curent = Float.valueOf(Account[matchindex][2]);
System.out.println("New balance = "+(curent+diposit));
break;
case "W":
System.out.println("Enter the ammount : ");
float withdrawal = ammount.nextFloat();
float balance = Float.valueOf(Account[matchindex][2]);
System.out.println("New balance = "+(balance-withdrawal));
break;
case "Q":
System.out.println("Exit");
break;
default:
System.out.println("Invalid transaction");
}
}
else
{
System.out.println("Invalid user account number");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
the file looks like
4
John Anderson
4565413
250.00
Louise Carter
2323472
1250.45
Paul Johnson
7267881
942.81
Sarah Wilson
0982377
311.26
The immediate error is arguably in your input file. There appears to be a space after the account number in question. You need to either make the account number in the file exactly as it will be typed during the probe, or trim the strings on input.
However, you do need to learn how to debug effectively. I have some advice on how to do it, with a worked example in Java, at Debug Strategy.
This question already has answers here:
How to repeat/loop/return to a class
(4 answers)
Closed 8 years ago.
I want to make a logic of getting grades. I proceed in a way of getting total marks as input from user using the Scanner class, then I'm validating marks if it is between 0 and 100(both inclusive).
Now if the marks are not in between this range, I print "Enter valid marks!!", and I want it to go to previous step and ask for the input from user again.
import java.util.Scanner;
class Performance
{
public static void main(String[] aa)
{
Scanner scnr = new Scanner(System.in);
System.out.println("Enter the marks :"); // Line 7
int marks= scnr.nextInt();
if(marks<0 || marks>100)
{
System.out.println("Enter valid marks!!");
}
// Now if this condition is true then I want the control to go again to line 7
// Please suggest me the way to Proceed
}
}
Please suggest the way to proceed with the modification in the above code.
See this link.
You want to do something like that:
do {
code line 1;
code line 2;
code line 3;
} while(yourCondition);
Now, if yourCondition is satisfied, the code will go to code line 1 again (will perform the code block between do and while).
Now, after you understand how it works, you can easily apply this to your task.
Scanner scnr = new Scanner(System.in);
do {
System.out.println("Enter the marks :"); // Line 7
int marks= scnr.nextInt();
if(marks<0 || marks>100)
{
System.out.println("Enter valid marks!!");
} else
break;
} while (true);
Try this:
boolean b = true;
while(b){
if(marks<0 || marks>100){
System.out.println("Enter valid marks!!");
marks= scnr.nextInt();
}
else{
b= false;
//Do something
}
}
8 int marks = scnr.nextInt();
9 while(marks<0 || marks>100)
10 {
11 System.out.println("Enter valid marks!!");
12 System.out.println("Enter the marks :");
13 marks = scnr.nextInt();
14 }
Thanks Guys for your help.
FInally i proceeded in the way as follows:
public static void main(String[] aaa)
{
int counter=0;
Scanner scnr = new Scanner(System.in);
int marks;
do
{
counter++;
System.out.println("Enter the marks :");
marks= scnr.nextInt();
if(marks<0 || marks>100)
{
System.out.println("Marks entered are not valid");
if(counter>=3)
{
System.out.println("You have exceeded the maximum number of attempts!!");
System.exit(1);
}
else
System.out.println("Enter valid marks!!");
}
else
break;
} while(true);
}