I make program like a marks journal. I am stuck in at users input. I want to make method which takes users input and puts it in HashMap. I guess there is a problem in my understanding methods works with each other.
import java.io.*;
import java.util.*;
public class Main {
HashMap marks;
public void scanMark(){
Scanner scan = new Scanner(System.in);
System.out.println("Class Mark");
String classname = scan.next();
int mark = scan.nextInt();
marks.put(classname, mark);
scan.close();
}
public static void main(String[] args) {
HashMap<String, Integer> markList = new HashMap<>();
System.out.println("1.Add Mark\n2.Delete Mark\n3.Show Mark");
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
sc.close();
if(x == 1){
markList.scanMark();
}
}
}
scanMark is a method of the class Main, so you just can not do this:
markList.scanMark();
because markList is a HashMap object and has no method scanMark
so you can create an instance of the Main class and on that object call the method scanMark
public static void main(String[] args) {
Main mApp = new Main();
HashMap<String, Integer> markList = new HashMap<>();
System.out.println("1.Add Mark\n2.Delete Mark\n3.Show Mark");
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
sc.close();
if (x == 1) {
mApp.scanMark();
}
}
You can't call the scanMark method on your HashMap since HashMap does not have that method. The scanMark method is located inside your Main class, so you need to call the scanMark method on an instance of Main. So your main will look like the following:
public static void main(String[] args) {
HashMap<String, Integer> markList = new HashMap<>();
` `Main main = new Main(); //create an instance of Main
System.out.println("1.Add Mark\n2.Delete Mark\n3.Show Mark");
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
sc.close();
if(x == 1){
main.scanMark(); //call scanMark on Main object
}
}
I did several changes in your code. It is working now ;)
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
/**
* #author pakOverflow
*/
public class Main
{
/** Constant - ADD MARK */
private static final String ADD_MARK = "Add Mark" ;
/** Constant - DELETE MARK */
private static final String DELETE_MARK = "Delete Mark" ;
/** Constant - SHOW MARK */
private static final String SHOW_MARK = "Show Mark" ;
/** Hash Map */
private Map<String, Integer> marks ;
private Main()
{
this.marks = new HashMap<String, Integer>() ;
}
public void scanMark()
{
Scanner scan = new Scanner(System.in) ;
final int itemNumber = scan.nextInt() ;
System.out.println("Item Number: " + itemNumber) ;
String classname = null ;
switch (itemNumber)
{
case 1:
classname = ADD_MARK ;
break ;
case 2:
classname = DELETE_MARK ;
break ;
case 3:
classname = SHOW_MARK ;
break ;
default:
classname = "Not found" ;
}
this.marks.put(classname, Integer.valueOf(itemNumber)) ;
System.out.println(this.marks);
scan.close() ;
}
public static void main(String[] args)
{
Main main = new Main() ;
System.out.println("1." + ADD_MARK + "\n2." + DELETE_MARK + "\n3." + SHOW_MARK);
main.scanMark() ;
}
}
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;
}
How to get input from user for Hashmap using scanner and print the respective hashmap?
import java.util.HashMap;
import java.util.Scanner;
public class Map {
public static void main(String[] args) {
HashMap<Integer, Integer> hmap = new HashMap<>();
Scanner in = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
Integer a = in.nextInt();
Integer b = in.nextInt();
hmap.put(a, b);
System.out.println(hmap.put(a, b));
}
}
}
I am not getting the desired output. I want to print what is inserted in hmap.
Change your System.out.println statement to,
System.out.println(hmap.get(a));
This is another way to put data into a HashMap at runtime:
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
class MapDemo {
public static void main(String[] args) {
HashMap<Integer, String> hmap = new HashMap<>();
Scanner in = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
Integer a = in.nextInt();
String b = in.next();
hmap.put(a, b);
}
for (Map.Entry<Integer, String> m : hmap.entrySet()) {
System.out.println(m.getKey() + " " + m.getValue());
}
}
}
Javadoc for the HashMap util can be found here.
To add a key/value pair to a HashMap you use hashmap.put(x, y).
Using hashmap.get(x) at a later time will return y.
Edit: It looks like from other comments you are trying to have it print out both the key and the value. In the case that you are trying to print out all keys and values something like this may work.
hashMap.forEach((e, k) -> {
System.out.println("E: " + e + " K: " + k);
})
If this is not your intended purpose I would strongly recommend reading over the method summary section of the javadocs.
What do you expect this to do? It is wrong, why would you print hmap.put(a,b)
System.out.println(hmap.put(a,b));
Just take it out of the for loop and print it separately
for (Map.Entry<Integer, Integer> pair: hmap.entrySet()) {
System.out.println(pair.getKey() + "->" + pair.getValue());
}
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
class Call {
public static void main(String[] as) {
getData();
}
public static void getData() {
Map<Integer, String> hashmap = new HashMap<>();
Scanner sc = new Scanner(System.in);
System.out.print("Shashank Pathak\nEnter number of character: ");
int n = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < a.length; i++) {
Integer b = sc.nextInt();
String c = sc.nextLine();
hashmap.put(b, c);
}
for (Map.Entry<Integer, String> mp : hashmap.entrySet()) {
System.out.println("\n" + mp.getKey() + " " + mp.getValue());
}
}
}
I find this, And it is exactly the same as I want.
System.out.println("How many producs you want");
int listOfItem = sc.nextInt();
System.out.println("Type the product name and quantity you want to purchace and get the bill");
HashMap<Integer, String> products = new HashMap<>();
while(listOfItem-- >0){
products.put(sc.nextInt(),sc.nextLine());
}
System.out.println(products);
Output of above program
import java.util.*;
class hash1 {
void dic(){
HashMap<Integer,Integer> hmap = new HashMap<Integer,Integer>();
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
hmap.put(a,b);
System.out.println(hmap);
}
}
public class answer {
public static void main(String[] args) {
hash1 obj = new hash1();
for(int z = 0;z < 3;z++){
obj.dic();
}
}
}
So I'm writing a basic MasterMind game that is... mostly functional. However, its exhibiting odd behavior and I'm unsure why.
The idea is that what defines a Code and its behavior is one file, the gameplay is another, and the Main just creates a new game and starts playing. When I initialize the game, the computer creates a new random string of 4 (the "secret code"), as expected; but then once I get input for the User guess, it seems to rewrite the secret code into whatever I've input. Further, my methods for evaluating matches don't work at all, but considering that the secret code keeps changing means that it's not being set to begin with, and I'm unsure why.
All three classes below. Why is my class variable in Game not setting properly and accessible to the other methods?
Main.java
class Main {
public static void main(String[] args) {
Game newGame = new Game();
newGame.play();
}
}
Code.java
import java.util.Random;
import java.util.HashMap;
import java.util.Collection;
import java.util.ArrayList;
import java.util.Set;
import java.lang.Math;
import java.lang.StringBuilder;
class Code {
private static HashMap<String,String> PEGS;
private static ArrayList<String> pegStrings;
protected static String secretCodeString;
public static void main(String[] args) {
}
public Code(String input){
this.secretCodeString = input;
}
public Code(){
randomize();
}
//literally just creates the peghash
public static void setPegs(){
PEGS = new HashMap<String,String>();
PEGS.put("C","c");
PEGS.put("Y","y");
PEGS.put("R","r");
PEGS.put("P","p");
PEGS.put("O","o");
PEGS.put("G","g");
}
//turns the pegs ito something randomize can use
public static ArrayList<String> makePegArray(){
setPegs();
pegStrings = new ArrayList<String>();
Collection<String> pegValues = PEGS.values();
Object[] pegObjects = pegValues.toArray();
for (int i = 0; i < pegObjects.length; i++){
pegStrings.add(pegObjects[i].toString());
}
return pegStrings;
}
// sets Class Variable secretCode to a four letter combination
public static Code randomize(){
secretCodeString = new String();
Random rand = new Random();
int randIndex = rand.nextInt(makePegArray().size());
for (int i = 0; i < 4; i++){
randIndex = rand.nextInt(makePegArray().size());
secretCodeString = secretCodeString.concat(makePegArray().get(randIndex));
}
Code secretCode = parse(secretCodeString);
return secretCode;
}
public static Code parse(String input) {
setPegs();
makePegArray();
String[] letters = input.split("");
StringBuilder sb = new StringBuilder();
for (String letter : letters) {
if (pegStrings.contains(letter)) {
sb.append(letter);
} else {
System.out.println(letter);
throw new RuntimeException();
}
}
String pegListString = sb.toString();
Code parsedCode = new Code(pegListString);
//System.out.println(parsedCode);
return parsedCode;
}
public int countExactMatches(Code guess){
String guessString = guess.secretCodeString;
int exactMatches = 0;
String[] guessArray = guessString.split("");
String[] winningCodeArray = (this.secretCodeString).split("");
for(int i = 0; i < 4; i++){
if(guessArray[i] == winningCodeArray[i]){
exactMatches++;
}
}
return exactMatches;
}
public int countNearMatches(Code guess) {
String guessString= guess.secretCodeString;
HashMap<String,Integer> guessCount = new HashMap<String,Integer>();
HashMap<String,Integer> secretCodeCount = new HashMap<String,Integer>();
Set<String> codeKeys = guessCount.keySet();
int matches = 0;
int keys = guessCount.keySet().size();
String[] keyArray = new String[keys];
for(int i = 0; i < guessString.length(); i++) {
//removes character from string
String codeCharacter = String.valueOf(guessString.charAt(i));
String guessShort = guessString.replace(codeCharacter,"");
//counts instances of said character
int count = guessString.length() - guessShort.length();
guessCount.put(codeCharacter, count);
}
for(int i = 0; i < secretCodeString.length(); i++) {
//removes character from string
String winningString = this.secretCodeString;
String winningCodeCharacter = String.valueOf(winningString.charAt(i));
String winningCodeShort = guessString.replace(winningCodeCharacter,"");
//counts instances of said character
int count = winningString.length() - winningCodeShort.length();
secretCodeCount.put(winningCodeCharacter, count);
}
for (int i = 0; i < keys; i++) {
codeKeys.toArray(keyArray);
String keyString = keyArray[i];
if (secretCodeCount.containsKey(keyString)) {
matches += Math.min(secretCodeCount.get(keyString), guessCount.get(keyString));
}
}
int nearMatches = matches - countExactMatches(guess);
return nearMatches;
}
}
Game.java
import java.util.Scanner;
class Game {
protected static Code winningCode;
public static void main(String[] args){
}
public Game(){
winningCode = new Code();
}
protected static Code getGuess() {
Scanner userInput = new Scanner(System.in);
int count = 0;
int maxTries = 5;
while(true){
try {
String codeToParse = userInput.next();
Code guess = Code.parse(codeToParse);
return guess;
} catch(RuntimeException notACode) {
System.out.println("That's not a valid peg. You have " + (maxTries - count) + " tries left.");
if (++count == maxTries) throw notACode;
}
}
}
protected static void displayMatches(Code guess){
int nearMatches = winningCode.countNearMatches(guess);
int exactMatches = winningCode.countExactMatches(guess);
System.out.println("You have " + exactMatches + " exact matches and " + nearMatches + " near matches.");
}
protected static void play(){
int turnCount = 0;
int maxTurns = 10;
System.out.println("Greetings. Pick your code of four from Y,O,G,P,C,R.");
while(true){
Code guess = getGuess();
displayMatches(guess);
if (guess == winningCode) {
System.out.print("You win!!");
break;
} else if (++turnCount == maxTurns) {
System.out.print("You lose!!");
break;
}
}
}
}
On every guess, you call Code.parse, Code.parse creates a new Code (new Code(pegListString);) and that constructor sets the secretCodeString and because that's static, all instances of Code share the same variable. You need to avoid mutable static members.
Another tip is to either have a method return a value, or mutate state (of either its input, or its own instance, this), but avoid doing both.
"Why is my class variable rewriting itself after an unrelated method runs?"
Because, actually, it is not unrelated. The "mess" that you have created by declaring variables and methods as static has lead to unwanted coupling between different parts of your code.
It is difficult to say what the correct solution is here because your code has gotten so confused by the rewrites that it is hard to discern the original "design intent".
My advice would be to start again. You now should have a clearer idea of what functionality is required. What you need to do is to redo the object design so that each class has a clear purpose. (The Main and Game classes make sense, but Code seems to be a mashup of functionality and state that has no coherent purpose.)
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;
}
}
I created a code that is meant to accept a user-input then add 5 to it, this is the code. When I enter any number, It returns 0. EDIT: I moved the reCalculate down under main, nothing changes
package files;
import java.util.*;
public class CalculatorTest {
static Scanner userFirstNumber = new Scanner(System.in);
static int numberReCalculated;
public static int reCalculate(int a){
int numberReCalculated = a + 5;
return numberReCalculated;
}
public static void main(String[] args){
int bobson;
System.out.print("Enter a number, I will do the rest : ");
bobson = userFirstNumber.nextInt();
reCalculate(bobson);
System.out.println(numberReCalculated);
}
}
Your declaration of int numberReCalculated = a + 5; shadows the field declaration static int numberReCalculated;. Either change int numberReCalculated = a + 5; to numberReCalculated = a + 5;, or rewrite the entire code to be idiomatic and organized:
public class CalculatorTest {
static Scanner userFirstNumber = new Scanner(System.in);
public static int reCalculate(int a){
return a + 5;
}
public static void main(String[] args){
int input;
System.out.print("Enter a number, I will do the rest : ");
input = userFirstNumber.nextInt();
int result = reCalculate(bobson);
System.out.println(result);
}
}
I have no idea how "bobson" is a descriptive and self-documenting variable name.