My code so far:
import java.util.*;
import java.util.Scanner.*;
public class Project{ // The Main Method
public static void main(String [] args){ // Creates the Main Method
System.out.println("Name a Method (Stability, efficiency ..)"); // Asks the user to select a method
Scanner scan = new Scanner(System.in); // Creates the Scanner
String splash = scan.nextLine(); // Transitions the user to the next line after choosing a method
if(splash.equals("efficiency")) // If users chooses Efficiency then it goes to the Efficiency method
{
efficiency(); // Calls the Efficiency method
}
if(splash.equals("Stability")) // If user chooses Stability then it goes to the Stability Method
{
stable(); // Calls the Stability method
}
else // What happens if the input wasnt recognized
{
System.out.println("I don't recognize this"); // what happens if an irrelevant method is chosen
}
}
}
How would I make it so that instead of:
else // What happens if the input wasnt recognized
{
System.out.println("I don't recognize this"); // what happens if an irrelevant method is chosen
}
It will refresh or restart the main method?
Wrap your code in a while loop which you leave when the user chooses the exit command:
public static void main(String [] args){
while (true) {
System.out.println("Name a Method (Stability, efficiency ..)");
Scanner scan = new Scanner(System.in);
String splash = scan.nextLine();
if (splash.equals("exit")) {
break;
} // else if (splash.equals("efficiency")) ...
}
}
Related
Here's the code I have created using the collection and the scanner parameters. I've been so confused to combine it into recursive, I used iteration.
public class Main {
public static void main(String[] args) {
Deque deque = new LinkedList<>();
Scanner sc = new Scanner(System.in);
System.out.println("Enter your words (type R to reverse):");
while(sc.hasNext()) {
String line = sc.next();
if(line.toLowerCase().equals("r")) {
break;
}
deque.add(line);
}
System.out.println("\n===== Reversed Lines =====\n");
Iterator reverse = deque.descendingIterator();
while (reverse.hasNext()) {
System.out.println(reverse.next());
}
}
}
First of all, quick recap on recursion.
Every recursive method consists of two parts:
Base case - that represents a simple edge-case (condition when recursion terminates) for which the outcome is known in advance.
Recursive case - a part of a solution where recursive calls are made and where the main logic resides.
You can extract the code responsible for reading the user input into a separate method and substitute the while loop with the recursive call.
The base case is represented by two situations: sc.hasNext() yields false and user input is equal to "r". Otherwise, the line will be added to queue and a new recursive call will be made.
And printing the content from the queue could be done recursively as well. The base case for this method is when reverse.hasNext() returns false. In the recursive case the next element will be printed, and a subsequent recursive call will be made.
So in order to be able to use Scanner and Queue you can either pass them as parameters or make them accessible globally.
Because of the requirements for this task, Scanner and Queue are declared locally inside the method readAndPrint() and as parameters of the method readInput().
public class Main {
public void readAndPrint() {
Scanner sc = new Scanner(System.in);
Deque<String> deque = new LinkedList<>();
System.out.println("Enter your words (type R to reverse):");
readInput(sc, deque); // recursive helper-method that read from the console
System.out.println("\n===== Reversed Lines =====\n");
print(deque.descendingIterator()); // recursive helper-method that prints to the console
}
public static void print(Iterator<String> reverse) {
if (!reverse.hasNext()) { // base case
return;
}
System.out.println(reverse.next());
print(reverse); // recursive call
}
public void readInput(Scanner sc, Deque<String> deque) {
if (!sc.hasNext() && sc.hasNextLine()) { // no more input on this line, but there's at least one more line
sc.nextLine(); // advance to the next line
}
if (!sc.hasNext()) { // base case
return;
}
String line = sc.next();
if (line.equalsIgnoreCase("r")) { // base case
return;
}
deque.add(line);
readInput(sc, deque); // recursive call
}
public static void main(String[] args) {
ri.readAndPrint();
}
}
Output
Humpty Dumpty // multyline input
sat on a wall R
===== Reversed Lines =====
wall
a
on
sat
Dumpty
Humpty
I've been teaching myself Java with http://www.cs.princeton.edu/courses/archive/spr15/cos126/lectures.html as a reference. They have a library called algs4 and it has several classes including StdIn, which I'm trying to implement below.
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
public class Tired
{
public static void main(String[] args)
{
//I thought this while statement will ask for an input
//and if an input is provided, it would spell out each character
while (!StdIn.hasNextChar()) {
StdOut.print(1); //seeing if it gets past the while conditional
char c = StdIn.readChar();
StdOut.print(c);
}
}
}
//This is from StdIn class. It has a method called hasNextChar() as shown below.
/*
public static boolean hasNextChar() {
scanner.useDelimiter(EMPTY_PATTERN);
boolean result = scanner.hasNext();
scanner.useDelimiter(WHITESPACE_PATTERN);
return result;
}
*/
If i run the code, it does ask for an input, but regardless of what i type in, nothing happens and nothing gets printed out.
I see that even StdOut.print(1); doesnt get printed out, so for some reason, it just gets stuck on while
It looks like the issue is with the condition for your while loop:
!StdIn.hasNextChar()
This says to continue as long as there isn't a next char. But you want to continue while there is one, so get rid of that ! and you should be good.
Here is some alternative code that works similarly. Not the best coding but works.
import java.util.Scanner;
public class test{
static Scanner StdIn = new Scanner(System.in);
static String input;
public static void main(String[] args){
while(true){
if(input.charAt(0) == '!'){ // use ! to break the loop
break;
}else{
input = StdIn.next(); // store your input
System.out.println(input); // look at your input
}
}
}
}
This question already has answers here:
How to call a method in another class of the same package?
(8 answers)
Closed 7 years ago.
Hi I have a robot which I need to tell it to move a certain number of times forward by saying forward 5. I have the method, I just need to get it to work in my class. Here is the method:
public void moveNumOfTimes(int num)
{
//-----------------------------------------------------------------------------------------------
int i=0;
while(i<num) {
if (this.frontIsClear()){ // if the front is NOT clear the robot should not move, otherwise will collide into the wall
this.move();
}
i++; // same as i=i+1;
}
//-----------------------------------------------------------------------------------------------
}
How do I enter that in my program? Is it like this?
moveNumOfTimes(int num);
Hope someone can help. Thanks
You should use a Scanner object to take input from the console.
Scanner sc = new Scanner(System.in);
You can implement like this.
class Robot{
public static void main(String args[]){
Scanner sc = new Scanner();
int numOfSteps = sc.nextInt(); //This line takes a integer input from the user
YourClassName r = new YourClassName();
//DO any initialization operations here
r.moveNumOfTimes(numOfSteps);
//Post movement operations come here
}
You can learn more on scanner here
How do I enter that in my program? Is it like this?
moveNumOfTimes(int num);
Yes, you could use something similar to this if you were trying to pass a command in from another method call. Something like:
public void Control(int moveNumber) {
... some other code, do some other stuff...
moveNumOfTimes(moveNumber); //Here you are passing a parameter value to your original method;
}
Or you could control it directly with another method like:
public void moveFive() {
moveNumOfTimes(5);
}
More likely, however, you wouldn't want to hardcode a method but rather call your original method directly through your Main method.
public static void main(String [ ] args) {
Robot r = new Robot();
r.moveNumOfTimes(5); //Here you have moved your new robot!
}
And if you really want to get fancy, look into working with the System and Scanner classes so you can prompt your user to tell the robot how much to move:
public static void main(String [ ] args) {
Robot r = new Robot();
Scanner reader = new Scanner(System.in);
System.out.println("How far should the robot move?"); //Output to the console window
int input = reader.nextInt(); //Reads the next int value
r.moveNumOfTimes(input); //Calls your method using the scanned input
}
I was doing some programming (self taught) and I have been struggling with an else statement but I fixed it. Now when I run it, it runs the wrong reply.. If that makes sense. I hope I am clear enough for you to help!w
import java.util.Scanner;
public class Test {
private static Scanner scanner;
public static void main(String[] args) {
// TODO Auto-generated method stub
String answer;
scanner = new Scanner(System.in);
System.out.println("Hello Human");
System.out.println("Do you want to build a snowman?");
answer = scanner.next();
if (answer.equals("Yes"))
System.out.println("Yay, Now you must think hard of what Olaf Looks like Okay? (say okay to coninue)");
{
else
System.out.println("Go away! I hate you"); //This happens when I try to say Yes.. This is meant for no.
}
}
}
You provided the wrong braces for if-else block. Please check the below code.
You can use equalsIgnoreCase() for case in-sensitivity for the user input.
import java.util.Scanner;
public class Test {
private static Scanner scanner;
public static void main(String[] args) {
// TODO Auto-generated method stub
String answer;
scanner = new Scanner(System.in);
System.out.println("Hello Human");
System.out.println("Do you want to build a snowman?");
answer = scanner.next();
if (answer.equalsIgnoreCase("Yes")) {
System.out.println("Yay, Now you must think hard of what Olaf Looks like Okay? (say okay to coninue)");
}
else {
System.out.println("Go away! I hate you"); //This happens when I try to say Yes.. This is meant for no.
}
}
}
PS: The if andelse` block here, are having only single statements, you if you want then you can remove them completely. But you have more than one then you must use the brackets.
The position of your brace: { is wrong. The message doesn't fall inside the if block and it'll always get printed. It should be as below,
import java.util.Scanner;
public class Test {
private static Scanner scanner;
public static void main(String[] args) {
// TODO Auto-generated method stub
String answer;
scanner = new Scanner(System.in);
System.out.println("Hello Human");
System.out.println("Do you want to build a snowman?");
answer = scanner.next();
if (answer.equals("Yes")) {
System.out.println("Yay, Now you must think hard of what Olaf Looks like Okay? (say okay to coninue)");
{ else
System.out.println("Go away! I hate you"); //This happens when I try to say Yes.. This is meant for no.
}
}
}
This question already has answers here:
Cannot make a static reference to the non-static method
(8 answers)
Closed 8 years ago.
Pre Edit: The problem is when I mark it as static, so
public static int printMenuGetSelection()
it gives me the message
This Static method cannot hide the instance method from AMenu
I'm writing a Java program that reads files and gives the user multiple options for displaying things about the file. I'm currently writing a menu interface that implements an actual Interface and makes the program easier to use. However, I'm getting an exception when I try to call the menu method in my main method. The error is on the one active line in the main method where I call printMenuGetSelection(), and it says
Cannot make static reference to the non-static method printMenuGetSelection() from the type SpecialAssignment1
How do I fix this bug? here is my program:
import java.util.*;
import java.io.*;
import java.text.*;
public class SpecialAssignment1 implements AMenu {
public static void main(String[] args) throws FileNotFoundException{
printMenuGetSelection();
/*System.out.println(RewardCustomer("transactions1.dat")); //CURRENTLY DISPLAYING TOP 6, DOESN'T WORK WITH TIES OR TOPN < lines
ProcessTransactionsFile("transactions2.dat", 52);*/
}
public int printMenuGetSelection() throws FileNotFoundException{
boolean runProgram = true;
Scanner s = new Scanner(System.in);
printStartMenu();
String startMenuSelection = s.next();
while(runProgram){
if(startMenuSelection.equals("1")){
startMenu1();
} else if(startMenuSelection.equals("2")){
startMenu2();
} else if(startMenuSelection.equals("3")){
startMenu3();
} else if(startMenuSelection.equals("4")){
startMenu4();
} else if(startMenuSelection.equals("5")){
runProgram = false;
} else {
System.out.println("***Selection Invalid!***");
}
}
return 1;
}
public static void printStartMenu(){
System.out.println("**********************************************************");
System.out.println("Main Menu...");
System.out.println(" (1) RewardCustomers");
System.out.println(" (2) ProcessTransactionFiles");
System.out.println(" (3) TopCustomers");
System.out.println(" (4) QueryStatsFile");
System.out.println(" (5) Quit");
System.out.println(" Enter a valid selection: ");
}
public static void startMenu1() throws FileNotFoundException{
boolean runMenu1 = true;
while(runMenu1){
Scanner s = new Scanner(System.in);
System.out.println("Reward Customers Menu...");
System.out.println(" (1) Use transactions1.dat");
System.out.println(" (2) Use transactions2.dat");
System.out.println(" (3) Quit");
System.out.println(" Enter a valid selection: ");
String menu1Selection = s.next();
if(menu1Selection.equals("1")){
System.out.println(RewardCustomer("transactions1.dat"));
} else if(menu1Selection.equals("2")){
System.out.println(RewardCustomer("transactions2.dat"));
} else if(menu1Selection.equals("3")){
runMenu1 = false;
} else {
System.out.println("***Selection Invalid!***");
}
}
}
public static void startMenu2(){
boolean runMenu2 = true;
while(runMenu2){
Scanner s = new Scanner(System.in);
System.out.println("Process Transaction Files Menu...");
System.out.println(" (1) Create transactions2.dat file");
System.out.println(" (2) Display transactions1.dat");
System.out.println(" (3) Display transactions2.dat");
System.out.println(" (4) Query transactions1.dat");
System.out.println(" (5) Query transactions2.dat");
System.out.println(" (6) Quit");
System.out.println(" Enter a valid selection: 4");
String menu2Selection = s.next();
if(menu2Selection.equals("1")){
}
}
}
public static void startMenu3(){
}
public static void startMenu4(){
}
I removed the code not pertaining to the question to make it easier to read, if it's needed I'll put it in. Also, here is the AMenu Interface. Please do not suggest any other changes to my program. If you think it's dumb to have the menu as an Implemented Interface, I 100% agree with you but that's the requirement. For reference, here is the AMenu Interface:
import java.io.FileNotFoundException;
public interface AMenu {
/**
* Prints a menu with selections and logic to return a valid selection.
* #return the selected item
*/
abstract int printMenuGetSelection() throws FileNotFoundException;
/**
* #return the numberOfMenuItems
*/
abstract int getNumberOfMenuItems();
}
Since printMenuGetSelection() is non static, you cannot call it from within the static method main() unless you create an instance of SpecialAssignment1 and call the method on that object.
you need to create an instance of your SpecialAssignment1 then call the method from that, as abstract requires an object.
As other people have said, you need to create an instance of SpecialAssignment1, then call printMenuSelection() on it. Part of what's making this confusing though is that you've stuck the main method inside the menu interface class. This whole thing would make more sense if you had a class SpecialAssignment1 with just the main method and a separate MenuGenerator class with all the menu generation stuff.