This is a fairly basic question but as a new Java student it's stumped me. This a practice problem that I'm working on and can't figure out how to call the hotOrColdOutside method into the main. As of now it's not compiling and asking for a return but my instructions specify there is no arguments or return in this instance. I feel like this is something simple that I know but is going over my head at the moment and any help in correcting this will be appreciated.
import java.util.Scanner;
class TempExp
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String answer = outsideTemp();
System.out.print(answer);
}//end main
public static String outsideTemp()
{
Scanner input = new Scanner(System.in);
System.out.print("What is the temperature outside: ");
int userIn = input.nextInt();
if(userIn >= 80)
{
System.out.print("It is very hot outside.");
}
else if(userIn >= 60)
{
System.out.print("It is very nice outside.");
}
else
{
System.out.print("It is very cold outside.");
}//end if/else
}//end method
}
The function
public static String outsideTemp()
returns a String. The main function doesn't return anything, though.
You'll want something like this:
import java.util.Scanner;
class TempExp
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String answer = outsideTemp();
System.out.print(answer);
}//end main
public static String outsideTemp()
{
Scanner input = new Scanner(System.in);
System.out.print("What is the temperature outside: ");
int userIn = input.nextInt();
if(userIn >= 80)
{
return "It is very hot outside.";
}
else if(userIn >= 60)
{
return "It is very nice outside.";
}
else
{
return "It is very cold outside.";
}//end if/else
}//end method
}
Because you say your instructions (I'm guessing you mean the assignment?) say there are no arguments or returns, you need to replace the String part of the function definition of outsideTemp() with void. Because it will not return anything, your main function will also need to be changed to not expect anything to be returned.
public static void main(String[] args)
{
outsideTemp();
}//end main
public static void outsideTemp()
{
... // this all stays exactly how it is now
}
However, if you do mean to return a string, use John's answer
Related
I am working on a homework assignment for an advanced C++ course. The program simulates the back-end of an online store. Luckily there is an autograder for the assignment and my Product and Customer classes pass every test case, however my Store class has a segmentation fault somewhere, and since the auto-grader unit-tests each function, I know the fault is occuring in addProduct(), it may also be occurring in getProduct() since addProdcut() calls getProduct().
I am not sure where the fault is occurring, I've tried to recreate it on my machine using driver code, but the auto grader just says that a segmentation fault occurred and doesn't tell me where. https://imgur.com/a/W1dzI7K
//numProducts is a static int and a data member of the Store class
static int Store::numProducts = 0;
//The products array is an array of Product pointers maximum size 100
Product* products[100];
//Each product has a unique id of type integer
bool Store::addProduct(int productID, const char productName[])
{
Product* product = getProduct(productID);
if (numProducts == 99) { return false; }
else if (product != nullptr) { return false; }
else
{
Product* newProduct = new Product(productID, productName);
products[numProducts] = newProduct;
numProducts++;
return true;
}
}
Product* Store::getProduct(int productID)
{
for (Product* product : products)
{
if (product->getID() == productID) {return product;}
}
return nullptr;
}
int Product::getID() const { return id; }
//here is the Product constructor, however i know that this is perfectly fine since the product class passes all unit-testing.
Product::Product(int productID, const char productName[]) :
id(productID), inventory(0), numSold(0), totalPaid(0.0) {
setName(productName);
strcpy_s(this->description, "");
}
//And here is the setName function in case you want to recreate this
void Product::setName(const char productName[]) {
if (strlen(productName) > 0) {
strcpy_s(this->name, productName);
}
else {
//Counter is a static int
counter++;
ostringstream oss;
oss << "Product " << counter;
strcpy_s(this->name, oss.str().c_str());
}
}
It seems like you forgot to zero-check product (compare it with nullptr) before calling its method
product->getID();
in
Store::getProduct()
Obviously, calling a method by a zero-initialized pointer isn't a good idea.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
So I'm really new to java and I was trying to practice using while and if statements through a guessing game app.
Everything seemed to work until I'm promped to play again. When I type Y, the loop ends. This isn't supposed to happen as the while argument at the beginning of the code says to keepPlaying if true.
I've tried playing with the argument to make it: while (answer == "Y"). I've played around with it but it always keeps exiting. Please help!!
Here's the code:
import java.util.Scanner;
public class GuessingGame
{
static Scanner sc = new Scanner(System.in);
public static void main(String[] args)
{
// TODO Auto-generated method stub
String answer = "Y";
int guess;
int number;
String again;
boolean keepPlaying = true;
System.out.println("Let's play a guessing game!");
while (keepPlaying)
{
System.out.println("I'm thinking of a number between 1 and 10.");
System.out.print("What do you think it is? ");
guess = sc.nextInt();
while (guess > 10 || guess < 1)
{
System.out.print("I said, between 1 and 10. Try again: ");
guess = sc.nextInt();
}
number = (int)(Math.random() *10 + 1);
if (guess == number)
{
System.out.println("You're right!");
}
else
{
System.out.println("You're wrong! the number was " + number);
}
System.out.print("Play again? (Y or N)");
answer = sc.next();
if (answer == "Y")
{
keepPlaying = true;
}
else
{
break;
}
}
System.out.println("Thank you for playing");
}
}
In the comparison, you should compare using the String requirements:
if (answer.equals("Y")) // NOTE: I'd use .equalsIgnoreCase(...)
{
keepPlaying = true;
}
else
{
break;
}
Also note that since this comparison is at the end of the loop, you could simplify to:
keepPlaying = answer.equalsIgnoreCase("Y");
As you do not need the break statement since the loop will be re-evaluated.
import javax.swing.JOptionPane;
public class sam{
public static void main(String[]args){
String a;
String b;
int c;
sam s1 = new sam();
a=s1.getInfo();
c=s1.getBalance();
b=s1.getMenu(a,c);
}
//menu method starts here
public String getMenu (String c, Integer d) {
String[] a;
String[] choices = { "Account Balance", "Deposit", "Withdraw", "User Account", "Exit options"};
String input = (String) JOptionPane.showInputDialog(null, "What would you like to do?",
"ATM menu", JOptionPane.QUESTION_MESSAGE, null,choices,choices[0]);
if ((choices[0] == choices[0])){
JOptionPane.showMessageDialog(null,"Your Account Balance is: "+d,"ATM machine",JOptionPane.INFORMATION_MESSAGE);}
//the if statement is executing properly
else if ((choices[1] == choices[1])){
String in=JOptionPane.showInputDialog("Deposit: ");
int deposit=Integer.parseInt(in);
int add=d+deposit;
JOptionPane.showMessageDialog(null,"Your Current Balance: "+add,"ATM machine",JOptionPane.INFORMATION_MESSAGE);}
//but when I chose account balance it displays the if statement not the else-if one
else if ((choices[2] == choices[2])){
String in=JOptionPane.showInputDialog("Withdraw: ");
int withdraw=Integer.parseInt(in);
int sub=d+withdraw;
JOptionPane.showMessageDialog(null,"Your Current Balance: "+sub,"ATM machine",JOptionPane.INFORMATION_MESSAGE);}
else if ((choices[3] == choices[3])){
JOptionPane.showMessageDialog(null," "+c,"ATM machine",JOptionPane.INFORMATION_MESSAGE);}
else if ((choices[4] == choices[4])){
JOptionPane.showMessageDialog(null,"The program will be terminated in a few seconds","ATM machine",JOptionPane.INFORMATION_MESSAGE);
}
return input;
}
//I'm quite new to programming, I rushed coded it for finals.
All of your if statements will evaluate to true. I think your intentions were to compare String c with each of the Strings in the choices array.
When comparing Strings always use .equals() not ==.
Example:
if (c.equals(choices[0])) {
// code
} else if (c.equals(choices[1])) {
//code
} else if (c.equals(choices[2])) {
// code
}
I wrote this bubble sort and used it in a test program that gives random numbers in a list by an amount inputted by the user. It was then given a list of 10,000 random ints and came back with a stack overflow at line 55 "if (swaps != 0){sort();}" why is this. Also at times it works but gives back a value for myCompares and mySwaps that is negative. Can you help?
public class Bubbly {
private int[] sortedList;
private static long myTime = 0;
private static int myCompares = 0;
private static int mySwaps = 0;
public Bubbly(int[] list) {
sortedList = list;
StopWatch stop = new StopWatch();
stop.start();
sort();
stop.stop();
myTime = stop.getElapsedTime();
}
public int[] getList(){
return sortedList;
}
public long getTime(){
return myTime;
}
public int getCompares(){
return myCompares;
}
public int getSwaps(){
return mySwaps;
}
public void sort(){
int length = sortedList.length, i = 0, num, swaps = 0;
while (i < length - 1){
if (sortedList[i] > sortedList[i + 1]) {
myCompares++;
num = sortedList[i];
sortedList[i] = sortedList[i+1];
sortedList[i+1] = num;
swaps++;
mySwaps++;
}
myCompares++;
i++;
}
if (swaps != 0){
sort();
}
}
}
Your program is recursive, probably the first recursive bubblesort I've ever seen :-)
Recursive implies that the function doesn't return until the work is done, instead each time sort() is called an extra call is pushed onto the stack. And after a number of recursive calls the stack is full and overflows.
So, get rid of the recursion, it's not useful here, just use a loop.
Regarding the variables that get negative values, start by getting rid of the static modifier on mySwaps, myTime and myCompare as it inhibits their correct initialization on each test run.
Only got rough idea of what I want, perhaps someone could pad it out and/or tell me if its possible.
I would like to simplify my multiply nested loops, to that end I would like to be able to call a function (for example that uses boost::filesystem) that returns a file in a directory, each successive call would return the next file, until all were exhausted. Also i would like to be able to do this with a vector, and have the function return successive elements.
Any ideas how this could be done? thanks
Create a functor: an object that is called like a function.
The object will hold the query results and the current state of the query. You define an operator() so the object can be called as if it were a function. Each time this function is called you return one result and update the object's internal state.
Example:
#include <iostream>
using namespace std;
class CountDown {
unsigned count;
public:
CountDown(unsigned count) : count(count) {}
bool operator()() { return count-- > 0; }
};
int main()
{
CountDown cd(5);
while( cd() ) {
cout << "Counting" << endl;
}
return 0;
}
use Iterator pattern. In Java you'd have smth like this:
class FileIterator {
private int index;
private File[] files;
public FileIterator(File[] files) {
this.files = files;
this.index = 0;
}
public boolean hasNext() {
if (index < files.length - 1) {
return true;
} else {
return false;
}
}
public File next() {
return this.files [index ++];
}
}
and you'd use it like this:
FileIterator it = new FileIterator(theFiles);
while (it.hasNext()) {
File f = it.next();
}
You can use BOOST_FOREACH to simplify loops link to docs and stackoverflow