Java Scanner doesn't work in Processing - java

For an assignment I have due, my group and I were asked to code an educational/interactive game, and we decided on a basic maths one.
To get the users answers, we decided to use Java Scanner and put this line of code at the top of all the code we have;
java.util.Scanner
One of the loops that use this is the page with the questions on it, the loop looking something like this;
scoreCount = 0;
for (questions = 0; questions < 5;) {
//get the user's answer
userAnswer[questions] = input.nextInt();
//text box for users answer
if (userAnswer[questions] == compAnswer) {
//put tick next to answer
//add one to score
scoreCount = scoreCount + 1;
} else if (userAnswer[questions] != compAnswer) {
//put cross next to answer
}
//go to next question
questions++ ;
}
I'm working through all the errors that were thrown up and every time i don't have java.util.Scanner commented out Processing throws us the errors unexpected token: and then either class or void, which i don't get, but when java.util.Scanner is commented out, the classes and voids all work and the .input.nextInt() isn't recognised.
I am new to Java programming and Processing, any help at all would be greatly appreciated
EDIT
i think this is the link which lets you see my code, it's called Test;
https://github.com/MeganSime/Week8DataVis

you have to check if scanner has next int (token)
Scanner input = new Scanner(System.in);
.
.
if(input.hasNextInt()) { // or hasNext()
userAnswer[questions] = input.nextInt();
}

You're probably inserting a non int value where the scanner expects that. You should do something like that:
if(input.hasNextInt()) {
userAnswer[questions] = input.nextInt();
} else {
scan.next(); //consume any non-int value like ":"
}

Related

how do you use a string in a while loop and then number the string?

in my intro to programming class. I am supposed to make a program that asks the user to enter his/her name and then use a while loop to print the name in the following manner:
(user entered Caroline)
C
a
r
o
l
i
n
e
Caroline, there are 8 letters in your first name.
--I've tried a bunch of things but still can't figure it out.--This is what I have so far
Assuming you are correctly getting the user entered string from the STDIN.
You may look to do something like this in your language of choice:
Find the length of your string
Use the while loop, with the condition relating to the length of your string, to move through the string character by character
Print out to a newline each individual character in your string
Feel free to ask questions and I would be happy to elaborate. Adding some examples of your code so far and the problems your facing would be useful.
In C++, this would be:
#include<iostream>
#include<string>
using namespace std;
int main()
{
int i=0;
string s;
cin>>s;
while(i<s.length())
{ cout<<i+1<<"."<<cout<<s[i]<<endl;
i++;
}
cout<<s<<", "<<"There are "<<s.length()<<" letters in your first name.";
return 0;
}
This is also very similar in Java, you should be able to derive it looking at this if you expected it in a programming language of your choice.
inside your main method try this:
//Asks user name.
System.out.println("What's your name?");
//Instantiates scanner
Scanner sc = new Scanner(System.in);
//With the scanner it reads user input and save it in the variable name
String name = sc.nextLine();
//It is a good programming practice to close the scanner
sc.close();
/*The loop that for each letter of the name also prints the position
number plus 1*/
int i = 0;
while (i < name.length()) {
System.out.println(i+1 + ". " + name.charAt(i));
i++;
}
As per snap shot shared by OP:
Here, you need to modify this lines:
System.out.println(name.charAt(i));
to
System.out.printf("%d. %c%n",(1+i),name.charAt(i));
Also, change this line:
i++;
}}}
to
i++;
}
System.out.printf("%s, there are %d letters in your first name%n",name,i));
}}

Using Scanner to change boolean in java

This is my first post here, so I decided to browse around various posts here in order to try and get a feel for how questions should be posted.
Hence, if I mess up please let me know so I can fix my post accordingly ASAP.
So here is my problem:
I started learning Java today and I'm working on just getting a feel for how everything works. I have the code below set to tell if kids are good or bad and display corresponding replays.
Good kids get candy, bad kids get none. I want to be able to limit the users choices to good or bad and have their answer change the Boolean to true or false to run the right if statement.
I saw a Math.random way of doing it but when I tried it I got more problems.
Thank you for your time.
The following is my code:
import java.util.Scanner;
public class Main {
public static void main (String args[]) {
//take user info
Scanner sc = new Scanner(System.in);
int candy = 12;
int kids = 4;
int bad = 1;
String a = sc.nextLine();
int answer = candy / kids;
String answer2 = "No Candy";
boolean good = false;
System.out.println(a);
//closeing the scanner
sc.close();
if(bad == 1) {
System.out.println(answer2);
} else {
if(bad == 2)
good = true;
System.out.println(answer);
}
if(good == true) {
System.out.println("Good Job");
} else {
System.out.println("Try again tomorrow!");
}
}
}
For one, it is not necessary to end the scanner before your code ends. You can leave it around, closing it is not necessary. (Unless your IDE forces you to , then yes, you should, but close it at the end just in case. I have Eclipse, so my code still runs without a glitch.)
Another comment is, just for the sake of aesthetics you should concatenate some kind of string on to the end of answer, so the reader understands what the variable means.
One more thing. I often find it helpful to name my scanner something a little more intuitive, such as input. Because after all, that's what it is. (I'm only commenting a lot about your code because you are just beginning to learn things, so you should get into good habits early.)
What you can do in this situation is convert your string inputs to booleans, by using boolean userInput = Boolean.parseBoolean(answer). Then, depending on the input the user gives by using an if statement, they can control the flow of the code.
I cleaned up your code a little bit, if you don't mind.
import java.util.Scanner;
public class lol {
public static void main (String args[]){
//take user info
Scanner sc = new Scanner(System.in);
int candy = 12;
int kids = 4;
int answer = candy / kids;
String answer2 = "No Candy";
System.out.println("Are youkids good or bad?");
System.out.println("[1] Good = true");
System.out.println("[2] Bad = false");
String a = sc.nextLine();
boolean userInput = Boolean.parseBoolean(a);
if(userInput== false){
System.out.println(answer2);
System.out.println("Try again tomorrow!");
}
else{
System.out.println("Good Job");
System.out.println("You get" +answer+"pieces.");
}
}
}
Seeing as you're just starting out, I'll try and keep it simple. There are plenty of ways to force your reader to say either "good" or "bad" that are better than below, but they require loops (which I assume you haven't touched yet).
Consider the following:
boolean good = false;
if (a.equals("good")) { // they said good
good = true;
} else if (a.equals("bad")) { // they said bad
good = false;
} else { // they said neither
System.out.println("You didn't say a correct word!");
}
You first specify that you have a boolean good (which you can either give a default value as above, or nothing). Then, depending on the user's input, you can set the boolean to be whatever is appropriate.
The reasoning behind having to declare the boolean good above the if statements has to do with the scope of a variable. If your book/teacher hasn't explained what that is, you should look it up now. The TL;DR is that if you only first declare your variable inside the if statements, then it will disappear as soon as you leave the if statements. You can see how in this case that would basically defeat the purpose of the if statements entirely.
You can limit the input by enclosing it in a loop.
List<String> accepted = new ArrayList<String>();
accepted.add("good");
accepted.add("bad");
System.out.println("Good or bad?");
String input = sc.nextLine();
while(!accepted.contains(input)) {
System.out.println("Invalid query '" + input + "'. Try again.");
input = sc.nextLine();
}
The code you have, well I don't know exactly what it's trying to do. It doesn't look functional at all. So where this fits in I'm not 100% sure.
package test;
import java.util.Scanner;
public class app {
public static void main (String args[]){
//take user info
Scanner sc = new Scanner(System.in);
String a="?";
while(!a.equals("good") && !a.equals("bad")){
System.out.println("Was the kid good or bad ?");
a = sc.nextLine();
}
boolean wasKidGood = a.equals("good");
String result = (wasKidGood ? "Good kid gets candy" : "No candy for bad kid");
System.out.println(result);
sc.close();
}
}
Hello, I wrote something, that will help you grasp a while loop and a ternary operator (alternative version of if loop). You also need to pay attention as to where you are allowed to use == and where you should use the equals() method. Regards

Checking if user entered anything?

I am trying to check if a user entered a number and if not, then it uses a default number like 10. How do i check if the user just presses enter and doesn't enter anything in Java
input = scanner.nextInt();
pseudo code:
if(input == user just presses enter without entering anything){
input = 10;
}
else just proceed with input = what user entered
//scanner is a Scanner
int i; // declare it before the block
try {
i = scanner.nextInt();
}
catch (InputMismatchException ime) {
i = 10;
}
// i is some integer from the user, or 10
First things first, geeeeeez guys, when the OP says something like
"I don't want an exception, i want i = 10 if nothing is entered, so what do i do"
That should clue you in that he probably doesn't know too much about exceptions (maybe even java) and might need a simple answer. And if that's not possible, explain to him the difficult ones.
Alright, here's the plain and simple way to do it
String check;
int input = 10;
check = scanner.nextLine/*Int*/();
if(check.equals(""))
{
//do nothing since input already equals 10
}
else
{
input = Integer.parseInt(check);
}
Let me explain what this code is doing. You were originally using nextInt() to get your number for input, correct? The problem is, nextInt() only responds if the user actually inputs something, not if they press enter. In order to check for enter, we used a method that actually responds when the user presses enter and used that to ensure that our code does what we wanted to. One thing I recommend using is an API, Java has one.
Here's the link for the API HERE
And here's the link for the actual method I used HERE. You can find descriptions and instructions on many methods you'll run into on this API.
Now, back to my answer, that's the easy way to do it. Problem is, this code isn't necessarily safe. It'll throw exceptions if something goes wrong, or if someone is trying to hack into your system. For example, if you were to enter a letter instead of pressing enter or entering a number, it would throw an exception. What you've been seeing in the other answers is what we call exception handling, that's how we make sure exceptions don't happen. If you want an answer that'll catch most of these exceptions, you need to make sure your code catches them, or avoids them all together (I'm simplifying things immensely). The above answer is working code, but isn't safe code, you wouldn't ever use something like this all by itself in real life.
Here is something that might be considered safe code. And no exceptions to keep it simple! ;)
import java.util.Scanner;
public class SOQ15
{
public Scanner scanner;
public SOQ15()
{
scanner = new Scanner(System.in);
int input = 10;
boolean isAnInt = true;
String check;
check = scanner.nextLine/*Int*/();
if(check.equals(""))
{
//do nothing since input already equals 10
}
for(int i = 0; i < check.length(); i++)
{
if(check.charAt(i) >= '0' && check.charAt(i) <= '9' && check.length() < 9)
{
//This is if a number was entered and the user didn't just press enter
}
else
{
isAnInt = false;
}
}
if(isAnInt)
{
input = Integer.parseInt(check);
System.out.println("Here's the number - " + input);
}
}
public static void main(String[] args)
{
SOQ15 soq = new SOQ15();
}
}
I don't have time to go into all the details right now, but ask and I'll gladly respond when I get the time! :)
Well if you are using scanner, given the details provided, you can try:
Scanner in = new Scanner(System.in);
if in.hasNextInt(){ //Without this, the next line would throw an input mismatch exception if given a non-integer
int i = in.nextInt(); //Takes in the next integer
}
You said you wanted a default of 10 otherwise so:
else {
int i = 10;
}

How do I check an unknown amount of inputs java and stop checking at the end of a line

This is my first question. I am a second year computer science student and I'm having some trouble reading several inputs correctly. I'm creating a board game that accepts a line of commands.
This is what some of the problem code looks like:
User is asked to input a command like that could look like this: create 0 0 fast flexible, or like this: create 0 0, with the integers being of any value and fast or flexible being able to be entered without the other.
if((keyboard.next()).equals("create"))
{
xValue = keyboard.nextInt();
yValue = keyboard.nextInt();
if((keyboard.next().equals("fast")))
{
pieceType = "FP";
if((keyboard.next().equals("flexible")))
{
pieceType = "FF";
}
}
if((keyboard.next().equals("flexible")))
{
pieceType = "SF";
if((keyboard.next().equals("fast")))
{
pieceType = "FF";
}
}
}
The program consistently wants 7 inputs.
How do I make it stop checking for inputs after the user presses enter?
I guess you could split the whole string according to the white-spaces and then process the string sequentially by words (or parts). Anyway, you should assert the input as a whole carefully.
try with
String NEW_LINE_SIGN = "\n";
if (keyboard.next().contains(NEW_LINE_SIGN){ /* .... */ }
This should work...
Scanner kbd = new Scanner(System.in);
kbd.useDelimiter(System.getProperty("line.separator"));
//you could create a rule automatically with some kind of a rules engine
if(kbd.hasNext("create(\\s+)(\\d+)(\\s+)(\\d+)(\\s+)(fast|flexible)(\\s+)(fast|flexible)")) {
MatchResult res = kbd.match();
for(int i = 0; i <= res.groupCount(); ++i) {
System.out.println(res.group(i));
//handleRules(res.group(i), i);
}
}
kbd.close();

Array setting length and storing information

This is homework. I'm trying to work with arrays and this is the first project working with them. My book shows all kinds of examples but the way they code the examples doesn't do any justice to what the assignment calls for.
I am trying to write a program that asks a user to enter students into the system. The program first asks how many you will enter then it will prompt you for the first name, last name, and score.
What I am trying to accomplish with this section of code is to ask the user how many students they will enter. The line of code that says
getStudentCount();
is a method that collects that information and then returns studentCount
I tried to code this to where the length of the array is going to be the number the user enters but it's not working so I wanted to ask for guidance. Ideally if this works and the user enters 3 then you will be prompted to enter the information 3 times. If the user enters 0 then the program doesn't ask you anything.
public static void main(String[] args)
{
System.out.println("Welcome to the Student Scores Application.");
int studentCount = 1;
getStudentCount();
studentCount = sc.nextInt();
String [] students = new String[studentCount];
for (int i = 0; i < students.length; i++)
{
Student s = new Student();
String firstName = getString("Enter first name: ");
s.setFirstName(firstName);
String lastName = getString("Enter last name: ");
s.setLastName(lastName);
int score = getScore("Enter score: ");
s.setScore(score);
}
}
Everything I had in the program worked up until I tried to code
String [] students = new String[studentCount];
for (int i = 0; i < students.length; i++)
which tells me there is something wrong with the way I am doing this.
Also the assignment asks that I store the information in the array. I'm not clear on how to call it or I guess store it.... I have another class with setters and getters. Is that enough to store it? How would I call it?
Again this is homework so any guidance is appreciated.
Thanks!
Well that's at least a homework example that shows some work on the part of the askee (and nicely written), so here's some help:
You set the studentCount to 1 and then call getStudentcount(), but never assigns the return value to your variable, hence the variable stays 1 (though you're overwriting it afterwards with sc.nextInt() which is probably not what you want if you already have a nice method for it). The fix is just to assign the return value of your method to the variable [1]
[1] Yes I know I shouldn't answer homework questions completely, but I really saw no way whatsoever to answer that only partially - proposals welcome though :)
My hints:
Look carefully at how you are getting the student count, and where you are putting it. You seem to be getting the count in two different ways, and that is at best redundant, and probably a bug.
Presumably there is a stack trace. Read it!!
The stack trace will tell you what exception was thrown, what its diagnostic message is, where it was thrown, and where in your code it was executing when the problem happened.
If you are having difficulty visualizing what is going on, use your Java IDE's debugger and single step the program.
Based on your follow-up comments, there isn't a stack trace. But if there was one, you should read it :-)
I don't understand your lines
getStudentCount();
studentCount = sc.nextInt();
if getStudentCount() "returns" the number they input (as you describe in your text), seems like you should be doing
int studentCOunt = getStudentCount();
I'm trying not to completely do your homework for you, but take a look at the code below for a glimpse of how to do this:
/* Some Declarations You're Going to Need */
private static Scanner scan = new Scanner(System.in); //Private, only need it in here
public static Student[] students; //Public, access it from any class you may need
public static void main(String[] args) {
System.out.println("Welcome to the Student Scores Application.");
System.out.print("Amount of students:");
int studentCount = scan.nextInt();
students = new Student[studentCount];
for (int i = 0; i < students.length; i++) {
students[i] = new Student();
System.out.print("Enter first name:");
String firstName = scan.next();
students[i].setFirstName(firstName);
System.out.print("Enter last name:");
String lastName = scan.next();
students[i].setLastName(lastName);
System.out.print("Enter score:");
int score = scan.nextInt();
students[i].setScore(score);
}
scan = null; //Done with scanner
}

Categories